<?php namespace App\Controllers;
/**
 * File			: App.php
 * Description  : Controller untuk utility
 * Created By	: Hendi
 * Created Date : 20 Jan 2021
 * Last Update  : 06 Apr 2021
**/

class App extends MyBaseController
{
	public function index()
	{
		//
	}
	
	public function show404() 
	{
		echo 'Maaf, halaman tidak ditemukan :)';
	}
	
	# ubah password
	public function changePassword()
	{
		# fn isLoggedIn di MyBaseController
		if (!$this->isLoggedIn()) return redirect()->to(base_url('login'));
		# jika sudah menu dinamis diisi dari array hasil query
        $data_sidebar = []; 
		# jika dibutuhkan data untuk konten
		$data_content = ['mod' => 'change_password'];
		$data = [
			'title' => 'Ubah Password',
			'sidebar' => view('contents/sidebar', $data_sidebar),
			'content' => view('contents/change_password', $data_content)
		];
		return view('templates/index', $data);
	}
	
	public function doChangePassword()
	{
		# fn isLoggedIn di MyBaseController
		if (!$this->isLoggedIn()) return redirect()->to(base_url('login'));
		
		$post = [];
		foreach($_POST as $k => $v) $post[$k] = $this->request->getPost($k);
		
		# roles 'change_password' sudah didefinisikan di Config/Validation.php
		if ($this->form_validation->run($post, 'change_password') === FALSE) 
		{
			# mengembalikan nilai input yang sudah diinput sebelumnya
            $this->session->setFlashdata('inputs', $post);
            # memberikan pesan error 
			$this->session->setFlashdata('errors', $this->form_validation->getErrors());
           	return redirect()->to(base_url('change-password'));
		}
		else
		{
			$user_id = $this->session->get('user_id');
			$password = $this->request->getPost('password');
			$UserModel = new \App\Models\UserModel();
			$data = $UserModel->where('user_id', $user_id)->first();
			if ($data) 
			{
				$password_hash = $data['password'];
				//echo password_hash("a", PASSWORD_DEFAULT)."\n"; 
				$verify_pass = password_verify($password, $password_hash);
				if(!$verify_pass)
				{
					$this->session->setFlashdata('errors', ['Password Lama tidak sama']);
					return redirect()->to(base_url('change-password'));
				}
			}
			$new_password = $this->request->getPost('new_password');
			$post['password'] = password_hash($new_password, PASSWORD_DEFAULT);
			# tidak disertakan dalam validasi / penyimpanan
			unset($post['csrf_token_name']);
			# jika satu baris saja boleh tanpa tanda {}
			$res = $UserModel->update($user_id, $post);
			
			# memberikan pesan, pake ul jadi pake []
			if ($res) #true
				$this->session->setFlashdata('success', 'Password berhasil diubah. Silahkan login ulang');
			else
				$this->session->setFlashdata('errors', ['Password gagal diubah']);
			
			return redirect()->to(base_url('change-password'));
		}
	}
}
