<?php 
	session_start();
	date_default_timezone_set('Africa/Blantyre'); // Example: Malawi

	
	
	include_once 'admin/model/users_model.php';
	$user_model = new users_model();
	
	$username = "";
	$pass = "";
	
	if(isset($_POST['username'])){
	$username = $_POST['username'];
	}
	if (isset($_POST['pass'])) {
	$pass = $_POST['pass'];
	$hashed_password = password_hash($pass, PASSWORD_BCRYPT);

	}
	
	$user = $user_model->authenticateUser($username);

    
	if (!$user) {
		$_SESSION['notification'] = [
			'type' => 'error',
			'title' => 'LOGIN FAILED',
			'message' => 'Invalid Username'
		];
		header('Location: login.php');
		exit();
	} else {

		$emp_id = $user['user_code'];
		$account = $user['role'];
		$state = $user['user_state'];

		$stored_hashed_password = $user['password'];
		if (password_verify($pass, $stored_hashed_password)) {
			session_regenerate_id();
			$_SESSION['sess_user_id'] = $user['id'];
			$_SESSION['sess_username'] = $user['username'];
			$_SESSION['sess_userrole'] = $user['role'];
			$_SESSION['sess_userstate'] = $user['user_state'];
			$_SESSION['sess_usercode'] = $user['user_code'];
	
			if ($user['user_state'] == 0) {
				$_SESSION['notification'] = [
					'type' => 'error',
					'title' => 'FAILED',
					'message' => 'Your Account Has Been Suspended<br>Consult System Administrator'
				];
				header('Location: login.php');
				exit();
			} else {
				// Handle based on user role
				switch ($user['role']) {
					case 'Admin':
						$_SESSION['notification'] = [
							'title' => 'SUCCESS',
							'type' => 'success',
							'message' => 'Login Successful'
						];
						session_write_close();
						header('Location: admin/dashboard.php');
						break;
	
					
					
	
					default:
						$_SESSION['notification'] = [
							'title' => 'LOGIN FAILED',
							'type' => 'error',
							'message' => 'Your Role Has Not Been Assigned'
						];
						header('Location: login.php');
						break;
				}
				exit();
			}
		} else {
			
			$_SESSION['notification'] = [
				'type' => 'error',
				'title' => 'LOGIN FAILED',
				'message' => 'Invalid Password'
			];
			header('Location: login.php');
			exit();
		}
	}
	
	
?>