<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class AuthController extends BaseController
{

	public function loginPage()
	{
		return view("login");
	}

	public function login()
	{
		helper(['form', 'url']);
		$session = session();
		$db = \Config\Database::connect();

		$userid = strtoupper(trim($this->request->getPost('userid')));
		$password = $this->request->getPost('password');

		$query = $db->query("SELECT * FROM gdc_cmod.dbo.USERS WHERE USERID = ?", [$userid]);
		$user = $query->getRowArray();

		if ($user && !empty($user['PASSWORD']) && password_verify($password, $user['PASSWORD'])) {

			$roleId = (int) $user['USERROLEID'];
			$role = ROLE_NAMES[$roleId] ?? '';

			$session->set([
				'isLoggedIn' => true,
				'userid' => (string) $user['USERID'],
				'userroleid' => (int) $user['USERROLEID'],
				'userrole' => (string) $role,
			]);

			switch ((int) $user['USERROLEID']) {
				case 0:
					return redirect()->to('superuser');
				case 1:
					return redirect()->to('admin');
				case 2:
					return redirect()->to('lab');
				case 3:
					return redirect()->to('phlebo');
				case 4:
					return redirect()->to('cs');
				default:
					return redirect()->to('login');
			}
		} else {
			$session->setFlashdata('error', 'Invalid User ID or Password.');
			return redirect()->back();
		}
	}

	public function logout()
	{
		$session = session();
		$session->destroy();
		return redirect()->to('login');
	}

	public function setPassword()
	{
		$input = $this->request->getJSON(true);
		$userid = $input['userid'];
		$password = $input['password'];
		$password = password_hash($password, PASSWORD_DEFAULT);
		$db = db_connect();
		$sql = "update GDC_CMOD.dbo.USERS set PASSWORD='$password' where USERID='$userid'";
		$db->query($sql);
		$data = ['status' => 'success', 'message' => 'Password updated successfully', 'data' => "$userid"];
		return $this->response->setJSON($data);
	}
}
