<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

	public function __construct() {
		parent::__construct();
	//	date_default_timezone_set("Asia/Kolkata");		
		if($this->session->userdata('logged_in')) { 
			redirect(base_url().'dashboard');
		}		
		$this->load->helper(array('form'));		
		$this->load->model('login_model');		
 	}
	public function index(){
		
		$template['page_title'] = "Login";
		if(isset($_POST)) {
			$this->load->library('form_validation');		
			$this->form_validation->set_rules('username', 'Username', 'trim|required');
			$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database');       
			if($this->form_validation->run() == TRUE) {
				redirect(base_url().'dashboard');
			}			
		}		
		$this->load->view('login-form');		
	}
	
	function check_database($password) {
		$username = $this->input->post('username');	
		$result = $this->login_model->login($username, md5($password));		
		if($result) {			  
			$this->session->set_userdata('logged_in',$result);		    
		    return TRUE;
		}
		else {
			$this->form_validation->set_message('check_database', 'Invalid username or password');
			return false;
		}		
	}
}
