<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start(); //we need to call PHP's session object to access it through CI
class login_controller extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->model('backend/login_model');
        $this->load->helper(array('form', 'url','html'));
        $this->load->library(array('form_validation','session'));
    }
    
    public function index()
    {
        $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
        
        $data = "";
        if($this->form_validation->run() == FALSE) {
            $this->load->view('backend/header');
            $this->load->view('backend/login',$data);
            $this->load->view('backend/footer');
        } else {
            //Go to private area
            redirect('/administrator/home', 'refresh');
        } 
    }
    
    function check_database($password) {
        //Field validation succeeded.  Validate against database
        $username = $this->input->post('username');
        //query the database
        $result = $this->login_model->login($username, $password);
        if($result) {
            $sess_array = array();
            foreach($result as $row) {
                //create the session
                $sess_array = array('id' => $row->id,
                    'username' => $row->username);
                //set session with value from database
                $this->session->set_userdata('logged_in', $sess_array);
                }
         return TRUE;
         } else {
             //if form validate false
             $this->form_validation->set_message('check_database', 'Invalid username or password');
             return FALSE;
         }
    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */