<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends back_end {

	public function __construct() {
		parent::__construct();

		// Load necessary libraries and helpers
		$this->load->library('form_validation');
		$this->load->library('auth');
		$this->form_validation->CI =& $this;
		$this->load->helper('utils');

		// Set form validation error delimiters
		$this->form_validation->set_error_delimiters('<p class="notice error rnd3"><a href="javascript:void(0)" class="close"></a>', '</p>');
	}

	public function index() {
		// Set form validation rules
		$this->form_validation->set_rules('username', 'اسم المستخدم', 'trim|required');
		$this->form_validation->set_rules('password', 'كلمة المرور', 'trim|required');
		// Dummy field to trigger check_login callback
		$this->form_validation->set_rules('login_validation', 'Login Validation', 'callback_check_login');

		// Run form validation
		if ($this->form_validation->run() == FALSE) {
			// Load the login view with a new token
			$data['token'] = generate_token();
			$this->load->view('admin/login', $data);
		} else {
			// Redirect to dashboard on successful login
			redirect('admin/dashboard');
		}
	}

	public function check_login($dummy) {
		// Log that the function was called
		log_message('debug', 'check_login function has been called.');

		// Retrieve form data
		$username = $this->input->post('username');
		$password_input = $this->input->post('password');

		// Check if username and password are provided
		if (empty($username) || empty($password_input)) {
			$this->form_validation->set_message('check_login', 'اسم المستخدم وكلمة المرور مطلوبة.');
			return FALSE;
		}

		// Hash the password
		$password = md5($password_input);

		// Retrieve and validate the token
		$token = $this->input->post('token');
		if (!check_token($token, 1200)) {
			$this->form_validation->set_message('check_login', 'خطأ أمنى من فضلك حاول مرة أخرى');
			return FALSE;
		}

		// Authenticate using the auth library
		$login_success = $this->auth->login($username, $password);

		if ($login_success) {
			// Set session data
			$this->session->set_userdata('notify', '1');
			$this->session->set_userdata('state', 'valid');
			return TRUE;
		} else {
			// Invalid credentials
			$this->form_validation->set_message('check_login', 'خطأ فى ادخال اسم المستخدم / كلمة المرور.');
			return FALSE;
		}
	}
}
