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

	class Login extends CI_Controller {
	    public function __construct() {
	        parent::__construct();
	        $this->session->set_userdata('enter_uri', 'home');
	    }

	    public function index($test = false) {
	    	$fileName = "application/controllers/installation.php";
	    	if (file_exists($fileName)) {
	    		redirect(base_url() . "installation", 'refresh');
	    		return 0;
	    	}

	    	if($this->session->userdata('logged_in')){
	    		redirect(base_url().'home', 'refresh');
	    	}

	    	$data['prevurls'] = base_url() . $this->session->userdata('first_uri');
			$data['expired'] = 0;
			$data['mode'] = 0;
	        $this->layouts->view('login', array(), $data, false);
	    }

	    public function change_language($lang = "en"){
			$referer = urlencode($_SERVER['HTTP_REFERER']);
			$this->session->set_userdata('language', $lang);
			redirect(urldecode($referer), 'refresh');
	 }

	    public function page(){

			$this->layouts->view('login', array(), array(), true);
	    }

	    public function removeInstallation() {
			$fileName = "application/controllers/installation.php";
			rename($fileName, "application/controllers/installationOld.php");
			redirect(base_url(), 'refresh');
	    }

	    public function deleteCompanyCheckPass() {
			$this->load->model('Usermaster');
	        $result = $this->Usermaster->getLogin(element('userid', $this->session->userdata('logged_in')), $this->input->post('pwd'));
	        if ($result) {
	            echo "true";
	        } else {
	            echo "false";
	        }
	    }

	    public function admin() {
	    	$data['prevurls'] = base_url() . $this->session->userdata('first_uri');
			$data['expired'] = 0;
			$data['mode'] = 1;
	        $this->layouts->view('adminLogin', array(), $data, false);
	    }

	    public function verifylogin() {
	    	$this->load->model('license_model');
	    	$this->load->model('Usermaster');
	    	// $this->load->library('form_validation');
	    	// $this->load->library('layouts');
//akmal 20160104 no companyID verification in login. companyID is based on login id
//	    	$this->form_validation->set_rules('compID', 'Company', 'required');
	    	$this->form_validation->set_rules('userID', 'User Id', 'required');
	    	$this->form_validation->set_rules('password', 'Password', 'required|callback_check_database');
	    	$urls_info = $this->input->post('prevurls');
	    	$data["dbname"] = "";

	    	$checkExpiry = $this->Usermaster->usermaster_checkEmailExpiry($this->input->post('userid'));


	    	$a = 0;

	    if($checkExpiry == TRUE){
	    			$a = 0;
	    		}
	    		else{
	    			$a = 1;
	    		}

	    	if($a == 0){

	    		if ($this->form_validation->run() == FALSE) {
	    			$this->layouts->set_title('SPS - Tekun');
	    			$default = false;
	    			$data['prevurls'] = base_url() . $this->session->userdata('first_uri');
//	    			$this->load->model('Company/Company_info_model');
//	    			$data['companyList'] = $this->Company_info_model->company_all();
	    			$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-en.js')
	    			->add_includes('js/validationengine/jquery.validationEngine.js');
	    			$this->layouts->view('/login', array(), $data, false);
	    		} else {
/* //akmal 20160411 disable tekun version check. 
	    			$next_version_set = "http://demo.salihinpremier.com/ss-ss/latest_sps_update/setting.txt";


	    			$online_upadte_setting = json_decode(str_replace("\r", "", @file_get_contents($next_version_set)));

	    			$sys_version = $this->config->item("application_version");

	    			if ($online_upadte_setting && ($sys_version !== $online_upadte_setting->current_version)) {
	    				$this->session->set_userdata("latest_sps_version", $online_upadte_setting->current_version);
	    				$this->session->set_userdata('is_latest', "no");
	    			}
	    			$this->session->set_flashdata('current_version', $this->config->item("application_version"));
	    			$updateOnline = array(
	    					'online' => 1
	    			);

	    			$result = $this->Usermaster->usermaster_edit($updateOnline, element('role', $this->session->userdata('logged_in')));


	    			//before go to urls info, check system general setup. if incomplete, redirect to general info. -akmal 20140804
	    			$this->load->model('systemgeneral/systemgeneral_model');
	    			if ($this->systemgeneral_model->complete_setup_bycompanyID()) {
	    				redirect('systemgeneral/generalSetup', 'refresh');
	    			} else */ if ($urls_info) {
	    				$urls = $this->session->userdata('first_uri');
	    				$urls = str_replace('usersetting/useronlinestatus', '', $urls);
	    				if ($urls) {
	    					redirect($urls, 'refresh');
	    				} else {
	    					redirect('/login', 'refresh');
	    				}
	    			} else {
	    				redirect('/login', 'refresh');
	    			}
	    		}

	    	}
	    	else{
	    		$data['expired'] = 1;
	    		$this->layouts->set_title('SPS - Tekun');
	    		$default = false;
	    		$data['prevurls'] = base_url() . $this->session->userdata('first_uri');
//	    		$this->load->model('Company/Company_info_model');
//	    		$data['companyList'] = $this->Company_info_model->company_all();
	    		$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-en.js')
	    		->add_includes('js/validationengine/jquery.validationEngine.js');
	    		$this->layouts->view('/login', array(), $data, false);
	    	}
	    	//        } else {
	    	//            redirect(base_url() . "license/error_key");
	    	//        }
	    }

	    public function verifyadmin() {
	    	$this->load->model('license_model');
	    	$this->load->model('Usermaster');
	    	// $this->load->library('form_validation');
	    	// $this->load->library('layouts');
//	    	$this->form_validation->set_rules('compID', 'Company', 'required');
//	    	$this->form_validation->set_rules('userid', 'User Id', 'required');
	    	$this->form_validation->set_rules('password', 'Password', 'required|callback_check_database_admin_login');
	    	$urls_info = $this->input->post('prevurls');
	    	$data["dbname"] = "";

	    	$data['expired'] = 0;

	    	$checkExpiry = $this->Usermaster->usermaster_checkEmailExpiry($this->input->post('userid'));
	    	$a = 0;

	    if($checkExpiry == TRUE){
	    			$a = 0;
	    		}
	    		else{
	    			$a = 1;
	    		}

	    	if($a == 0){

	    		if ($this->form_validation->run() == FALSE) {
	    			$this->layouts->set_title('SPS - Tekun');
	    			$default = false;
	    			$data['prevurls'] = base_url() . $this->session->userdata('first_uri');
//	    			$this->load->model('Company/Company_info_model');
//	    			$data['companyList'] = $this->Company_info_model->company_all();
	    			$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-en.js')
	    			->add_includes('js/validationengine/jquery.validationEngine.js');
	    			$this->layouts->view('/login', array(), $data, false);
	    		} else {
	    			$next_version_set = "http://demo.salihinpremier.com/ss-ss/latest_sps_update/setting.txt";


	    			$online_upadte_setting = json_decode(str_replace("\r", "", @file_get_contents($next_version_set)));

	    			$sys_version = $this->config->item("application_version");

	    			if ($online_upadte_setting && ($sys_version !== $online_upadte_setting->current_version)) {
	    				$this->session->set_userdata("latest_sps_version", $online_upadte_setting->current_version);
	    				$this->session->set_userdata('is_latest', "no");
	    			}
	    			$this->session->set_flashdata('current_version', $this->config->item("application_version"));
	    			$updateOnline = array(
	    					'online' => 1
	    			);

	    			$result = $this->Usermaster->usermaster_edit($updateOnline, element('role', $this->session->userdata('logged_in')));


	    			//before go to urls info, check system general setup. if incomplete, redirect to general info. -akmal 20140804
	    			$this->load->model('systemgeneral/systemgeneral_model');
	    			if ($this->systemgeneral_model->complete_setup_bycompanyID()) {
	    				redirect('systemgeneral/generalSetup', 'refresh');
	    			} elseif ($urls_info) {
	    				$urls = $this->session->userdata('first_uri');
	    				$urls = str_replace('usersetting/useronlinestatus', '', $urls);
	    				if ($urls) {
	    					redirect($urls, 'refresh');
	    				} else {
	    					redirect('/login', 'refresh');
	    				}
	    			} else {
	    				redirect('/login', 'refresh');
	    			}
	    		}

	    	}
	    	else{
	    		$data['expired'] = 1;
	    		$this->layouts->set_title('SPS - Tekun');
	    		$default = false;
	    		$data['prevurls'] = base_url() . $this->session->userdata('first_uri');
//	    		$this->load->model('Company/Company_info_model');
//	    		$data['companyList'] = $this->Company_info_model->company_all();
	    		$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-en.js')
	    		->add_includes('js/validationengine/jquery.validationEngine.js');
	    		$this->layouts->view('/login', array(), $data, false);
	    	}
	    	//        } else {
	    	//            redirect(base_url() . "license/error_key");
	    	//        }
	    }

	    public function check_database_admin_login($password) {
	        $userid = $this->input->post('userid');
	        $this->load->model('Usermaster');
	        //Getting user company information (Sayem 27-11-2015).
	        $userCompany = $this->Usermaster->getUserComp($this->input->post('userID'));
	        $compID = $this->input->post('compID');//$userCompany[0]->companyID;
	        $this->load->model('company/company_info_model');
	        $query = $this->company_info_model->company_id($compID);

	        // var_dump($this->license_model->decrytCompanyCode($query[0]->keyCode));
	        //var_dump($this->company_info_model->company_id($compID));

	        // if ($query) {
	        //     if ($this->license_model->decrytCompanyCode($query[0]->keyCode) != $query[0]->companyNo && $query[0]->companyNo != "demo") {

	        //         $this->form_validation->set_message('check_database', 'Invalid Company Activation Code');
	        //         return false;
	        //     }
	        // } else {
	        //     $this->form_validation->set_message('check_database', 'Invalid Company');
	        //     return false;
	        // }

	        $result = $this->Usermaster->get_admin_Login($userid, $password);
	        if ($result) {
	            $this->load->model('license_model');

	            $sess_array = array();
	            foreach ($result as $row) {
	                if (empty($row->language))
	                    $row->language = 'en';
	                $sess_array = array(
	                    'userid' => $row->userid,
	                    'username' => $row->username,
	                    'compName' => $query[0]->companyName,
	                    'compNo' => $query[0]->companyNo,
	                    'compCurrency' => $query[0]->currencyID,
	                    'currencyWord' => $query[0]->currencyWord,
	                    'logo' => $query[0]->uploadLogo,
	                    'compID' => $compID,
	                    'email' => $row->email,
	                    'language' => $row->language,
	                    'dtFormat' => $query[0]->dtFormat,
	                    'dtFormatJava' => $query[0]->dtFormatJava,
	                    'role' => $row->fldid,
	                    'userProfilePic' => $row->imageFile
	                    );
	                $this->session->set_userdata('admin_master_code', md5("yes"));
	                $this->session->set_userdata('logged_in', $sess_array);
	                $this->session->set_userdata('language', $row->language);
	            }
	            return TRUE;
	        } else {
	            $this->form_validation->set_message('check_database', 'Invalid username or password');
	            return false;
	        }
	    }

	    public function check_database($password) {
	       if($this->input->post('adminlogin') =="adminlogin"){
	           return  $this->check_database_admin_login($password);
	       }
	        $userid = $this->input->post('userID');
	        $this->load->model('Usermaster');
	        //Getting user company information (Sayem 27-11-2015).
	        $userCompany = $this->Usermaster->getUserComp($this->input->post('userID'));
// var_dump($this->input->post()); 			
// echo '<br>'.$this->db->last_query(); //exit();
	//        var_dump($userCompany); exit();
			$compID = (!empty($userCompany))?$userCompany[0]->companyID:'';//$this->input->post('compID');
	        $this->load->model('company/company_info_model');
	        $query = $this->company_info_model->company_id($compID);
	        //var_dump($this->license_model->decrytCompanyCode($query[0]->keyCode));
	        if ($query) {
	            if ($this->license_model->decrytCompanyCode($query[0]->keyCode) != $query[0]->companyNo && $query[0]->companyNo != "demo") {

	                $this->form_validation->set_message('check_database', 'Invalid Company Activation Code');
	                return false;
	            }
	        } else {
	            $this->form_validation->set_message('check_database', 'Invalid Company');
	            return false;
	        }
	        $result = $this->Usermaster->getLogin($userid, $password);
// echo '<br>'.$this->db->last_query().'<br>'; //exit();
// var_dump($result); //exit();
	        if ($result) {
	            $this->load->model('license_model');


	//var_dump($row->language);
	//exit();
	            $sess_array = array();
	            foreach ($result as $row) {
	                if (empty($row->language))
	                    $row->language = 'en';
	                $sess_array = array(
	                    'userid' => $row->userid,
	                    'username' => $row->username,
	                    'compName' => $query[0]->companyName,
	                    'compNo' => $query[0]->companyNo,
	                    'compCurrency' => $query[0]->currencyID,
	                    'currencyWord' => $query[0]->currencyWord,
	                    'logo' => $query[0]->uploadLogo,
	                    'compID' => $compID,
	                    'email' => $row->email,
	                    'language' => $row->language,
	                    'dtFormat' => $query[0]->dtFormat,
	                    'dtFormatJava' => $query[0]->dtFormatJava,
	                    'role' => $row->fldid,
	                    'userProfilePic' => $row->imageFile

	                    );
	                $this->session->set_userdata('is_latest', "yes");
	                $this->session->set_userdata('logged_in', $sess_array);
	                $this->session->set_userdata('language', $row->language);
// var_dump($this->session->userdata); exit();
				}
	            return TRUE;
	        } else {
	            $this->form_validation->set_message('check_database', 'Invalid username or password');
	            return false;
	        }
	    }

	    public function check_userIP() {
	        $this->load->model('Usermaster');
	        $result = $this->Usermaster->usermaster_userid($this->input->post('userID'));
	        $userOnline = $this->Usermaster->userOnlinebyUserID($this->input->post('userID'));
	        $companyList = $this->Usermaster->getUserComp($this->input->post('userID'));
	        if (!empty($userOnline) && $userOnline[0]->last_seen_ip != $this->getIP()) {
	            echo json_encode(array('status'=>'error','compList'=>$companyList));
	        } else {
	            echo json_encode(array('status'=>'success','compList'=>$companyList));
	        }
	    }

	    function getIP() {
	        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
	            $ip = getenv("HTTP_CLIENT_IP");
	        } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
	            $ip = getenv("HTTP_X_FORWARDED_FOR");
	        } else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
	            $ip = getenv("REMOTE_ADDR");
	        } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
	            $ip = $_SERVER['REMOTE_ADDR'];
	        } else {
	            $ip = "unknown";
	        }
	        return($ip);
	    }

	    public function reset_ip() {
	        $this->load->model('Usermaster');
	        $userOnline = $this->Usermaster->userOnlinebyUserID($this->input->post('userID'));
	        $this->db->set(array(
	                    'last_seen_ip' => $_SERVER['REMOTE_ADDR'],
	                ))
	                ->where(array(
	                    'fldid' => $userOnline[0]->fldid
	                ))
	                ->update('tbl_usermaster');
	        if ($this->db->affected_rows() > 0) {
	            echo "success";
	        } else {
	            echo "error";
	        }
	    }

	    public function slctCompany(){
	        $this->load->model('Usermaster');
	        $result = $this->Usermaster->getLogin($this->input->post('userID'), $this->input->post('pass'));
	        if($result){
	            echo json_encode(array(
	                                'status'=>'success',
	                                'compList' => $this->Usermaster->getUserComp($this->input->post('userID'))
	                            ));
	            exit();
	        }else{
	            echo json_encode(array(
	                                'status'=>'error',
	                                'data'=>'Invalid username or password'
	                            ));
	            exit();
	        }
	    }

	    public function fgtpwdSubmit() {
	        //   $this->load->model('Usermaster');
	        //  echo $this->Usermaster->forgetPwd($this->input->post('userName'));
	    }
	}
?>
