<?php
namespace App\Controllers;
use CodeIgniter\Cookie\Cookie;
use DateTime;

helper('cookie');
class Auth extends BaseController {
	
	// public function login() {
	// 	if ($this->request->getMethod() === 'POST') {

	// 		$data['email'] = $this->request->getVar('email');
	// 		$data['password'] = $this->request->getVar('password');
	// 		$data['rememberme'] = $this->request->getVar('rememberme');
			
	// 		$db = \Config\Database::connect();
	// 		$sql = "SELECT firstname, lastname, userid, initial, userposid, level FROM users WHERE email_1='".$data['email']."'";
	// 		$query = $db->query($sql);
	// 		$row = $query->getRow();
	// 		if(isset($row)) {
	// 			$userid = $row->userid;
	// 			$initial = $row->initial;
	// 			$level = $row->level;
	// 			$firstname = $row->firstname;
	// 			$userposid = $row->userposid;
	// 			$sessiondata = [
	// 				'email' => $data['email'],
	// 				'userid' => $userid,
	// 				'userposid' => $userposid,
	// 				'initial' => $initial,
	// 				'level' => $level,
	// 				'firstname' => $firstname,
	// 			];
	// 		}
			
	// 		$rules = [
	// 			'email' => 'required|valid_email',
	// 			'password' => 'required|validateLogin[email, password]'
	// 		];
	// 		$errors = [
	// 			'password' => [
	// 				'validateLogin' => 'Wrong password'
	// 			]
	// 		];
			
	// 		if($this->validate($rules,$errors)){
	// 			session()->set( $sessiondata );
	// 			if( isset($data['rememberme']) ) {
	// 				$time = 30*24*60*60;// 30days
	// 				set_cookie ("email", $data['email'], $time);  
	// 				set_cookie ("password", $data['password'], $time);
	// 				set_cookie ("rememberme", $data['rememberme'], $time);
	// 				//echo "cookie set";
	// 			} else {
	// 				delete_cookie ("email");  
	// 				delete_cookie ("password");
	// 				delete_cookie ("rememberme");
	// 			}
	// 			return redirect()->to('/');
	// 		} else {
	// 			$data['validation'] = $this->validator;
	// 			return view('auth_login',$data);
	// 		}
			
	// 	}
		
	// 	$data['email'] = get_cookie('email');
	// 	$data['password'] = get_cookie('password');
	// 	$data['rememberme'] = get_cookie('rememberme');
		
	// 	return view('auth_login',$data);
	// }
	
	// mikael.zakaria.37@gmail.com
	public function login() {

		// Cek Apakah sudah login atau belum
		if (session()->has('userid')) {
			return redirect()->to('/');
		}

		if ($this->request->getMethod() === 'POST') {

			$data = [
				'email'     => $this->request->getVar('email'),
				'password'  => $this->request->getVar('password'),
				'rememberme'=> $this->request->getVar('rememberme')
			];

			// RULES VALIDATION
			$rules = [
				'email'    => 'required|valid_email',
				'password' => 'required'
			];

			if (! $this->validate($rules)) {
				return view('auth_login', [
					'validation' => $this->validator,
					'password'   => $data['password'],
					'rememberme' => $data['rememberme'],
					'email'      => $data['email'] // biar tetap terisi
				]);
			}

			// CARI USER
			$db      = \Config\Database::connect();
			$builder = $db->table('users');
			$builder->select('userid, firstname, lastname, initial, userposid, level, password');
			$builder->where('email_1', $data['email']);
			$user = $builder->get()->getRow();

			if ($user && password_verify($data['password'], $user->password)) {
				// SET SESSION
				$sessionData = [
					'userid'    => $user->userid,
					'firstname' => $user->firstname,
					'initial'   => $user->initial,
					'userposid' => $user->userposid,
					'level'     => $user->level,
					'email'     => $data['email'],
					'isLoggedIn'=> true
				];
				session()->set($sessionData);

				// REMEMBER ME (hanya email)
				if ($data['rememberme']) {
					$time = 60*60*24*30; // 30 hari
					set_cookie('email', $data['email'], $time);
					set_cookie('rememberme', true, $time);
				} else {
					delete_cookie('email');
					delete_cookie('rememberme');
				}

				return redirect()->to('/');
			}

			// JIKA PASSWORD SALAH
			session()->setFlashdata('loginError', 'Email atau password salah.');
			return view('auth_login', [
				'password' => $data['password'],
				'rememberme' => $data['rememberme'],
				'email' => $data['email']
			]);
		}

		// AUTO-FILL DARI COOKIE
		$data['email']      = get_cookie('email');
		$data['rememberme'] = get_cookie('rememberme');

		return view('auth_login', $data);
	}

	public function logout() {
		session()->destroy();
        return redirect()->to('/auth/login');;
	}
	
	public function setPass() {
		if ($this->request->getMethod() === 'POST') {
			$data['email'] = $this->request->getVar('email');
			$data['password'] = $this->request->getVar('password');
			$data['passwordconf'] = $this->request->getVar('passwordconf');
			$rules = [
				'email' => 'required|valid_email',
				'password' => 'required',
				'passwordconf' => 'required|matches[password]'
			];
			if($this->validate($rules)){
				$email = $data['email'];
				$password = password_hash($data['password'],PASSWORD_DEFAULT);
				$db = \Config\Database::connect();
				$sql = "update users set password='$password' where email_1='$email'";
				if($db->query($sql)) { return view('form_success'); } 
				else { return view('form_fail'); }
			} else {
				return view('auth_setPass',$data);
			}
		}
		return view('auth_setPass');
	}
}
