<?php

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

/**
 * Admin        Class
 * Extends      MX_Controller
 * @property    Admin $admin
 * @property    CI_Form_validation $form_validation
 * @author 	Mohamed Mahdy
 */
class Admin extends back_end {

    /**
     * Constructor
     * @access	public
     */
    function __construct() {
        parent::__construct();

        $this->load->library('form_validation');
        $this->load->library('auth');

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

    /**
     * Default Controller Function
     * @access	public
     */
    public function index() {

        // Redirects the user back to the dashboard if he/she is allready logged in "NO STUPIDITY HERE".
        $this->form_validation->set_rules('username', 'اسم المستخدم', 'trim|xss_clean|required');
        $this->form_validation->set_rules('password', 'كلمة المرور', 'trim|xss_clean|required');
        $this->form_validation->set_rules('token', 'token', 'callback_check_login');

        if (!$this->form_validation->run()) {
             print_r("bbbbbbbb");exit;
            $data['token'] = generate_token();
            $this->load->view('admin/login', $data);
        } else {
              print_r("aaaa");exit;
            if($this->check_login()){
                redirect('admin/dashboard');
            }else{
                print_r("aaaa");exit;
               redirect_back();
            };
        }
    }

    function check_login() {

        $username = $this->input->post('username');
        $password = md5($this->input->post('password'));

        $token = $this->input->post('token');
        if (!check_token($token, 1200)) {
            // Expired or incorrect token
            $this->form_validation->set_message('check_login', 'خطأ أمنى من فضلك حاول مرة أخرى');
            return FALSE;
        }
        $login = $this->auth->login($username, $password);
                print_r($login);exit;
        if ($login) {
            $this->session->set_userdata('notify', '1');

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

}
