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

class Dashboard extends CI_Controller {

	function __construct()
	{
		parent:: __construct();
		$this->load->library('form_validation');
		$this->load->library('email');
		$this->load->model('login_model');
		
		date_default_timezone_set("Africa/Nairobi");
	}
	
	public function index()
	{		
		$this->load->view('external/index');
	}
	
	public function welcome()
	{
		$this->login_model->authenticate();
		$this->last_login();
		$user_id = $this->login_model->user_id();
			
		$topbar_data['additional_css'] = array(NULL);
		$topbar_data['profile_photo'] = $this->main_model->create_thumbnail(160,160,$user_id);
		$sidebar_data['menu'] = $this->menu_control->get_menu($user_id);
		$dashboard_data['user_id'] = $user_id;
		
		$jquery_data['additional_jquery'] = array(NULL);
		$jquery_data['functions'] = array(NULL);
		
		$this->load->view('sections/topbar',$topbar_data);
		$this->load->view('sections/sidebar',$sidebar_data);
		$this->load->view('sections/content',$dashboard_data);
		$this->load->view('sections/footer',$jquery_data);
	}
	
	//display a normal login form with username and password fields
	function displayLoginForm()
	{
		$this->session->sess_destroy();
		$data = array('message' =>'');
		$this->load->view('external/login',$data);	
	}
	
	//display a list of all accounts found. User to select one to proceeed on.
	function multipleAccountsForm()
	{
		$this->session->sess_destroy();
		$data = array('message' =>'');
		$this->load->view('external/multiple_accounts',$data);	
	}
	
	function login()
	{
		$this->form_validation->set_rules('national_id_no', 'Id No.', 'required|numeric');
		$this->form_validation->set_rules('password', 'Password', 'required');
		
		$this->form_validation->set_error_delimiters('<span class="error-message">', '</span>');
		
		if ($this->form_validation->run() == FALSE) // validation hasn't been passed
		{		  
			$this->displayLoginForm();		  
		}
		else
		{
			$national_id_no = $this->security->xss_clean($this->input->post('national_id_no'));
			$password = $this->security->xss_clean($this->input->post('password'));
			
			$newUser = new login_model($national_id_no,$password);
			$response = $newUser -> login();
			
			
			switch($response)
			{
				case 0:
						$this->fail();
					break;
				case 1:
						$this->fail();
					break;
				case 2:
						$this->deactivated_account();
					break;
				case 3:
						$this->welcome();
					break;
				case 4:
						$this->multiple_accounts($national_id_no,$password);
					break;
			}
		}
	}
			
	function fail(){
		$this->session->sess_destroy();
		$data = array('message' =>' Wrong Login and/or password');
		$this->load->view('external/login',$data);
		}
	
	//user tries to access system with expired session data	
	function unauthorised(){
		$this->session->sess_destroy();
		$data = array('message' =>'Access Denied! (login to access the system)');
		$this->load->view('external/login',$data);
		}
	
	//function called if the account has been deactivated	
	function deactivated_account(){
		$this->session->sess_destroy();
		$data = array('message' =>'Your account has been deactivated. Contact Admin.');
		$this->load->view('external/login',$data);
		}
		
	//this function is used when a user has more than one account in the system; same id_no(same pwd/same pwd??)
	function multiple_accounts($id_no,$pwd)
	{
		$data['accounts'] = $this->login_model->multiple_accounts_select_account($id_no,$pwd);
		$this->load->view('external/multiple_accounts',$data);
	}
	
	//use user_id to login user - called by ajax at multiple_accounts.php view
	function select_user_account()
	{
		$user_id = $this->input->post('user_id');
		$response = $this->login_model->select_user_account_forAjax($user_id);
	/*	if($response !=3)
		{
			$this->unauthorised();
		}
		else*/
			echo $response;
	}		
	
	function logout()
	{
		$this->session->sess_destroy();
		redirect('dashboard/index');	
		//$this->index();
	}
	
	//update last login in users  table
	function last_login()
	{
		$last_login = time();
		$last_IP = $this->input->ip_address();
		$user_id = $this->login_model->user_id();
		
		$this->login_model-> update_last_login($last_login, $last_IP, $user_id);
		
	}
	
	//used to request for password request when not logged in
	function request_password_reset()
	{
		$this->session->sess_destroy();
		$data = array('class'=>'','message' =>'');
		$this->load->view('external/password_reset',$data);		
	}
	
	function process_password_reset()
	{
		$this->form_validation->set_rules('national_id_no', 'Id No.', 'required|numeric');
		
		$this->form_validation->set_error_delimiters('<span class="error-message">', '</span>');
		
		if ($this->form_validation->run() == FALSE) // validation hasn't been passed
		{		  
			$this->request_password_reset();		  
		}
		else
		{
			$national_id_no = $this->security->xss_clean($this->input->post('national_id_no'));
			
			$response = $this->login_model->password_reset($national_id_no);
			
			if($response == FALSE)
			{
				$data = array('class'=> 'negative-message','message' => "The Id No. you submitted is not registered.");
				$this->load->view('external/password_reset',$data);
			}
			else
			{
				
				$id_no = $response[0]['national_id_no'];
				$email_address = $response[0]['email_address'];
				$fullname = $response[0]['name'];
				//generate a random session_id and encrypt it to get a unique session value
				$rand = mt_rand(11111,99999);
				$session_id = strrev($id_no.$rand);
				$session = md5($rand);
				//$link = {unwrap}.site_url().$session_id.'/'.$session{/unwrap};
				$link = site_url('dashboard/new_password').'/'.$session_id.'/'.$session;
				
				//build array
				$passwordReset = array(
										'national_id_no' => $national_id_no,
										'request_time' => time(),
										'request_ip' => $this->input->ip_address(),
										'email_address' => $email_address,
										'session_id' => $session_id,
										'session' => $session,
										'link' => $link,
										'status' => 0
										);
				$this->main_model->insert_data('external_password_reset', $passwordReset);
				$this->send_password_reset_email($email_address,$fullname,$id_no,$link);
				$data = array('class'=> 'positive-message','message' => "A password reset link has been sent to your email.");
				$this->load->view('external/password_reset',$data);
			}
		}
		
	}
	
	function send_password_reset_email($to,$fullname,$id_no,$link)
	{		
		$emailBody = "
Dear $fullname,

A request has been triggered to reset password for National Id NO: $id_no which corresponds to this email address.
If you initiated the request use this link: ".$link." to reset your password.

Note:
	1. The link expires after 24 hours after which a new request must be made.
	2. The link can only be used once.
	3. All accounts associated with the National Id NO will have the password reset. You may change passwords for individual accounts when logged in.
	4. If you did not initiate the request, just ignore and your current password will not be changed.

Contact System Admin <admin@sacccomanager.com> in case of any queries or assistance.

Kind regards,
SaccoManager.com
		
		";
		
		$this->email->from('passwords@saccomanager.com', 'SaccoManager Passwords');
		$this->email->reply_to('admin@sacccomanager.com', 'SaccoManager Admin');
		$this->email->to($to); 
		
		$this->email->subject('SaccoManager.com Password Reset');
		$this->email->message($emailBody);	
		
		$this->email->send();
		
		//echo $this->email->print_debugger();
	}
	
	//called using link sent to email
	function new_password($session_id = NULL,$session =NULL)
	{
			$rand = strrev(substr($session_id,0,5));
			$id_no = strrev(substr($session_id,5));
			
			if($session != md5($rand) || !isset($rand) || !isset($id_no))
			{
				$data = array('class' => "negative-message", 'message' => "The link is not authentic.Request for another link.");
				$this->load->view('external/password_reset',$data);
			}
			else 
			{
				$this->session->set_flashdata('ID_NO', $id_no);
				$this->session->set_flashdata('SESSION', $session);
				
				$data = array('class' => "", 'message' => "");
				$this->load->view('external/new_password',$data);
			}
				
	}
	
	function process_new_password()
	{
		$this->form_validation->set_rules('password', 'Password', 'required');
		$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
		
		$this->form_validation->set_error_delimiters('<span class="error-message">', '</span>');
		
		if ($this->form_validation->run() == FALSE) // validation hasn't been passed
		{		  
			$this->new_password();		  
		}
		else
		{
			$id_no = $this->session->flashdata('ID_NO');
			$session = $this->session->flashdata('SESSION');
			$current_time = time();
			$current_ip = $this->input->ip_address();
			$password = md5($this->security->xss_clean($this->input->post('password')));
			
			if(empty($id_no) || empty($session))
			{
				$data = array('class' => "negative-message", 'message' => "Visit Password Reset Link afresh.");
				$this->load->view('external/new_password',$data);
			}
			else
			{
				$response = $this->login_model->set_new_password($id_no,$session,$current_time,$current_ip,$password);
				
				if($response == "EXPIRED")
				{
					$data = array('class' => "negative-message", 'message' => "The link has expired.Request for another.");
					$this->load->view('external/new_password',$data);
				}
				else if($response == "USED")
				{
					$data = array('class' => "negative-message", 'message' => "The link has been used.Request for another.");
					$this->load->view('external/new_password',$data);
				}
				else if($response == "SUCCESS")
				{
					$data = array('class' => "positive-message", 'message' => "Password reset successful.You may login.");
					$this->load->view('external/new_password',$data);
				}
				else if($response == "FAILED")
				{
					$data = array('class' => "negative-message", 'message' => "Password reset failed. You may try again.");
					$this->load->view('external/new_password',$data);
				}
			}
		}
	}
}
