<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;

class Auth extends BaseController
{
	public function __construct()
	{
		$this->userModel = new UserModel;
	}

	public function index()
	{
		if ($this->session->get('logged_in')) {
			return redirect()->to('/admin/dashboard');
		}
		return view('auth/login');
	}

	public function login()
	{
		$rules = [
			'email' => [
				'rules'  => 'required',
				'errors' => []
			],
			'password' => [
				'rules'  => 'required',
				'errors' => []
			],
		];


		$email = $this->request->getPost('email');
		$password = $this->request->getPost('password');

		if (!$this->validate($rules)) {
			return redirect()->back()->withInput();
		} else {
			$cekLogin = $this->userModel->where('email', $email)->get()->getRowArray();
			if ($cekLogin != null) {
				$verify_password = $cekLogin['password'];
				if (password_verify($password, $verify_password)) {
					$data = [
						'id' => $cekLogin['id'],
						'email' => $cekLogin['email'],
						'username' => $cekLogin['username'],
						'nama' => $cekLogin['nama'],
						'roles' => $cekLogin['roles'],
						'logged_in' => TRUE
					];
					$this->session->set($data);
					return redirect()->to('/admin/dashboard');
				} else {
					$this->session->setFlashdata('danger', 'Email atau Password salah.');
					return redirect()->to('/login');
				}
			} else {
				$this->session->setFlashdata('danger', 'Email dan Password harus diisi.');
				return redirect()->to('/login');
			}
		}
	}

	public function logout()
	{
		$data = ['id', 'email', 'username', 'nama', 'roles', 'logged_in'];
		session()->remove($data);
		session()->setFlashdata('success', 'Berhasil Logout.');
		return redirect()->to('/login');
	}

	public function forgotPassword()
	{
		if ($this->session->get('logged_in')) {
			return redirect()->to('/admin/dashboard');
		}
		return view('auth/forgot_password');
	}

	public function verifyAccount()
	{
		$rules = [
			'username' => [
				'rules'  => 'required|min_length[3]',
				'errors' => [
					'required' => 'Username harus diisi.',
					'min_length' => 'Username minimal 3 karakter.'
				]
			],
			'email' => [
				'rules'  => 'required|valid_email',
				'errors' => [
					'required' => 'Email harus diisi.',
					'valid_email' => 'Format email tidak valid.'
				]
			],
		];

		$username = $this->request->getPost('username');
		$email = $this->request->getPost('email');

		if (!$this->validate($rules)) {
			return redirect()->back()->withInput();
		}

		// Cek apakah username dan email cocok di database
		$user = $this->userModel->where('username', $username)->where('email', $email)->first();
		
		if ($user) {
			// Simpan user ID dalam session untuk proses selanjutnya
			$this->session->set('reset_user_id', $user['id']);
			return redirect()->to('/auth/reset-password');
		} else {
			$this->session->setFlashdata('danger', 'Username dan Email tidak cocok atau tidak ditemukan.');
			return redirect()->back()->withInput();
		}
	}

	public function resetPassword()
	{
		// Cek apakah ada session reset_user_id
		$userId = $this->session->get('reset_user_id');
		if (!$userId) {
			$this->session->setFlashdata('danger', 'Sesi verifikasi tidak ditemukan. Silakan ulangi proses.');
			return redirect()->to('/auth/forgot-password');
		}

		// Ambil data user
		$user = $this->userModel->find($userId);
		if (!$user) {
			$this->session->setFlashdata('danger', 'User tidak ditemukan.');
			return redirect()->to('/auth/forgot-password');
		}

		$data = [
			'user' => $user
		];

		return view('auth/reset_password', $data);
	}

	public function updatePassword()
	{
		$userId = $this->session->get('reset_user_id');
		if (!$userId) {
			$this->session->setFlashdata('danger', 'Sesi verifikasi tidak ditemukan.');
			return redirect()->to('/auth/forgot-password');
		}

		$rules = [
			'password' => [
				'rules'  => 'required|min_length[6]',
				'errors' => [
					'required' => 'Password baru harus diisi.',
					'min_length' => 'Password minimal 6 karakter.'
				]
			],
			'confirm_password' => [
				'rules'  => 'required|matches[password]',
				'errors' => [
					'required' => 'Konfirmasi password harus diisi.',
					'matches' => 'Konfirmasi password tidak cocok dengan password baru.'
				]
			],
		];

		if (!$this->validate($rules)) {
			return redirect()->back()->withInput();
		}

		$password = $this->request->getPost('password');
		$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

		// Update password
		$updateData = [
			'password' => $hashedPassword,
			'updated_at' => date('Y-m-d H:i:s')
		];

		if ($this->userModel->update($userId, $updateData)) {
			// Hapus session reset
			$this->session->remove('reset_user_id');
			$this->session->setFlashdata('success', 'Password berhasil diubah. Silakan login dengan password baru.');
			return redirect()->to('/login');
		} else {
			$this->session->setFlashdata('danger', 'Terjadi kesalahan saat mengubah password.');
			return redirect()->back();
		}
	}
}
