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

class Login extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
 
	 public function __construct(){
		parent::__construct();
 		$this->load->model(array('admin/admin_model','admin/admin_mail_model'));
		//var_dump($this->session->userdata('BIBLEALL_RP_ADMIN'));exit;
// 		if($this->session->userdata('BIBLEALL_RP_ADMIN')){ redirect('admin/dashboard', 'refresh'); exit;}
 		 
    }
	 
	public function index( )
	{
  		// $data = array();
  		// echo "test";
  		// exit;
// 		$loggedRow = $this->session->userdata('BIBLEALL_RP_ADMIN');
//  		if(!empty($loggedRow) && !empty($loggedRow['ID'])){ redirect('admin/dashboard', 'refresh');exit; }
    		$this->load->view('admin/login');
	}
 	function setLogin(){
 		
		if(!$this->input->post('adminLoginName', TRUE)){
			redirect('admin');exit;	
		}
		
 		 $ip = $this->input->ip_address();
		 $ua = $this->input->user_agent();
		$this->form_validation->set_rules('adminLoginName', 'Username', 'trim|xss_clean');
		$this->form_validation->set_rules('adminLoginPass', 'Password', 'trim|xss_clean');
		$this->form_validation->set_rules('adminLoginCode', 'Verify code', 'trim|xss_clean');
  		if ($this->form_validation->run() == FALSE) {
			 $data['loginError'] =  true;
 			 $this->load->view('admin/login',$data);
		}else{
  				$errMsg = '';$canAddLog = false;$userRow='';
				$captchaCode = $this->input->post('adminLoginCode',TRUE);
				$sessionCaptcha = $this->session->userdata('S4A_CAPTCHA_login');
				// $captchaCodepsw = $this->input->post('adminLoginCodepsw',TRUE);
				//   var_dump($this->session->userdata('S4A_CAPTCHA_cal'));
				// var_dump($sessionCaptcha); exit();
				//   var_dump($captchaCode); exit();
				  
				 if(strcmp(strtoupper($captchaCode),strtoupper($sessionCaptcha)) != 0){
 					$errMsg =  'Verify code mismatching. Please try again!';//$canAddLog = true;
				}else{
					$adminLoginPass = ($this->input->post('adminLoginPass', TRUE));
					$userRow = $this->admin_model->adminLoginRow($this->input->post('adminLoginName', TRUE));
				// 	print_r($userRow);exit;
 					 if($userRow === false){
						$errMsg =  'Invalid Username!'; //$canAddLog = true;
					 } else {
						// print_r($_POST);exit;
 							if($userRow->accountActivated == 0){
								$errMsg =  'Account not yet verified. <a href="'.base_url().'admin/login/resendEmailVerfication/'.$userRow->userId.'">Resend</a> verification email.'; 	 
							}
							else if( ! password_verify($adminLoginPass , $userRow->accountPassword)){
 							// else if($userRow->accountPassword != $adminLoginPass){
								$errMsg =  'Invalid Password!';// 	$canAddLog = true; 
							}else if($userRow->accountDeleted  != 0){
								$errMsg =  'Account Deleted!. Please contact Admin!.'; 	 
							}else if($userRow->accountDisabled  != 0){
								$errMsg =  'Account Disbaled!. Please contact Admin!.'; 	 
							}
 					 }
				 }
 			if(!empty($errMsg)){
				$log_account = '0'; 
				if($userRow){ $log_account = $userRow->accountId; }
				if($canAddLog){
 					$arrData =array('log_account' => $log_account, 'log_type' => 'AdminLogin',
								'log_ip' =>$ip, 'log_ua' => $ua, 'log_status_msg' => 'InvalidLogin', 'log_msg' => $errMsg ); 
					 $resMsg =  $this->admin_model->addLogMsg($arrData);  
 					if(!empty($resMsg))$errMsg .= $resMsg;
				}
   			 	$this->session->set_flashdata('errMsg',$errMsg);
				redirect('admin');exit;
			}else if($userRow){
				 
				 $newdata['BIBLEALL_RP_ADMIN']['authorized'] = 1;
				 $newdata['BIBLEALL_RP_ADMIN']['ID'] = $userRow->accountId;
				 $newdata['BIBLEALL_RP_ADMIN']['NAME'] = $userRow->accountFirstname;
				 $newdata['BIBLEALL_RP_ADMIN']['USERNAME'] = $userRow->accountUsername;
				 $newdata['BIBLEALL_RP_ADMIN']['EMAIL'] = $userRow->accountEmail;
				 $newdata['BIBLEALL_RP_ADMIN']['USER_TYPE'] = $userRow->accountType;
				 $newdata['BIBLEALL_RP_ADMIN']['PRIVILEGE'] = $userRow->accountAccessPrivilege;
				 $newdata['BIBLEALL_RP_ADMIN']['ACCESS'] = $userRow->accountAccessModule;
				 $newdata['BIBLEALL_RP_ADMIN']['LAST_LOGIN'] = $userRow->accountLastLoginTime;
				
				 $userLoginCount = $userRow->accountLogincount;$userLoginCount++;
				 $updateData = array();
				 $updateData['accountLastLoginTime'] = 	'UNIX_TIMESTAMP(NOW())';
				 $updateData['accountLastLoginIP'] = 	$this->input->ip_address();
				 $updateData['accountLastLoginUA'] = 	$this->input->user_agent();
				 $updateData['accountLogincount'] = 	$userLoginCount;    
 				 $this->admin_model->updateAccountData($updateData,$userRow->accountId);
 				 $track_user_details="";
 				 
				 if($userRow->accountType == 'Admin') {
					 $track_user_details = 'Admin has been logged in';
				 } else  if($userRow->accountType == 'SubAdmin') {
					 $track_user_details = 'Sub Admin has been logged in';
				 }
 				 $arrTracking =array( 'log_type' => 'AdminActivity', 'log_status_msg' => 'Login', 'log_msg' => $track_user_details ); 
 				 $this->admin_model->tracking($arrTracking);
  				 $this->session->set_userdata($newdata);
  				
			    redirect('admin/one_link', 'refresh');exit;
			}
 		}
 		
	}
	function resendEmailVerfication($userId = false){
 		$adminRow = $this->admin_model->getAdminRow($userId);
		if($adminRow){
			$sendmail = $this->admin_mail_model->sendVerificaionEmailToAdmin($adminRow->userFirstName,$adminRow->userEmail,$adminRow->userActiveKey);
			if($sendmail){
				$this->session->set_flashdata('errMsg','Verification email has been sent. Please check your mail inbox.');
				redirect('admin');exit;	
			}
		}else{
			$this->session->set_flashdata('errMsg','Invlaid URL!');
					redirect('admin');exit;	
		}
		 
	}
	function forgot(){
	    
	   // $this->admin_mail_model->checkSMTPMail_2();
	   // echo 'sad';
	   // exit;
		if(!$this->input->post('adminForgotEmail', TRUE)){
			redirect('admin');exit;	
		}
				$captchaCode = $this->input->post('adminForgotCode',TRUE);
				$sessionCaptcha = $this->session->userdata('S4A_CAPTCHA');
				 
				 if(strcmp(strtoupper($captchaCode),strtoupper($sessionCaptcha)) != 0){
 					$errMsg =  'Verify code mismatching. Please try again!'; 
					$this->session->set_flashdata('errMsg','Verify code mismatching. Please try again!');
					redirect('admin');exit;	
				}
				
				
		$result = $this->admin_model->adminForgotPass($this->input->post('adminForgotEmail', TRUE));
 			if(!empty($this->admin_model->errors)){
				$errors = implode('<br/>',$this->admin_model->errors);
				$this->session->set_flashdata('errMsg',$errors);
			}
			if($result === true){
				$this->session->set_flashdata('successMsg','Change password mail has been sent. Please check your mail inbox.');
			}
		redirect('admin');exit;				
	} 
	function verify($verifyToken = false){
		if($verifyToken){
			$adminRow = $this->admin_model->getAdminRowByKey($verifyToken);
 			if($adminRow){
				$data['activated'] = 'activated';
				$data['verifyToken'] = $verifyToken;
				$adminRow = $this->admin_model->activateAdminAccount($verifyToken);
				if($this->input->post('loginBtn',TRUE)){
					$captchaCode = $this->input->post('adminLoginCode',TRUE);
					$sessionCaptcha = $this->session->userdata('S4A_CAPTCHA');
 					 if(strcmp(strtoupper($captchaCode),strtoupper($sessionCaptcha)) != 0){
						$errMsg =  'Verify code mismatching. Please try again!'; 
						$this->session->set_flashdata('errMsg','Verify code mismatching. Please try again!');
						redirect('admin/verify/'.$verifyToken);exit;	
					}
 					$changepass = $this->admin_model->updatePassword($verifyToken);
					if($changepass){
						$this->session->set_flashdata('successMsg','Password has been changed! Please login.');
						redirect('admin');exit;	
					}
				}
				$this->load->view('admin/change-password',$data);
			}else{
				$this->session->set_flashdata('errMsg','Invalid URI!');
				redirect('admin');exit;	
			}
		}else{
			$this->session->set_flashdata('errMsg','Invalid URI!');
			redirect('admin');exit;	
		}
	}
	function blockLogin(){
		header('HTTP/1.1 403 Forbidden'); 
		echo '<h1>403 Forbidden</h1>';
		exit;	
	}
}

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