<?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');
	}

	/**
	* LOGIN MAIN
	* @author : Zul Zolkaffly
	* @last-update : 08/08/2016
	*/
	public function index() {
		if($this->session->userdata('logged_in') && strtoupper(element('role', $this->session->userdata('logged_in'))) == "ADMIN"){
			redirect('home', 'refresh');
		}
		$this->load->view('login', array(), '');
	}
	
	/**
	* VERIFY LOGIN
	* @author : Zul Zolkaffly
	* @last-update : 08/08/2016 (Zul Zolkaffly)
	*/
	public function verifylogin() {
		// LOAD MODEL
		$this->load->model('Usermaster');
		// SET VALIDATION RULES
		$this->form_validation->set_rules('userID', 'User Id', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required|callback_verifyPassword');

		if ($this->form_validation->run() == FALSE) {
			$this->layouts->set_title('SPS - Tekun');
			return false;
		} else {
			redirect(base_url().'company', 'refresh');
		}
	}

	/**
	* FORM VALIDATION CALLBACK TO VERIFY PASSWORD
	* @author : Zul Zolkaffly
	* @last-update : 08/08/2016 (Zul Zolkaffly)
	*/
	public function verifyPassword($password) {
		// RETRIEVE USER LOGIN ID FROM FORM
		$userid = $this->input->post('userID');
		// VERIFY LOGIN AND FETCH DATA
		$result = $this->Usermaster->getLogin($userid, $password);
		if($result) {
			$expired = $this->Usermaster->checkExpired($userid);
			if($expired) {
				echo"<script>alert('Akaun tamat tempoh. Sila hubungi kami untuk kemaskini.'); window.location='".base_url()."'</script>";
				return false;
			} else {
				$sess_array = array();
				// SET DEFAULT LANGUAGE
				if(empty($result->language)) $result->language = 'ms';
				// INIT SESSION ARRAY
				$sess_array = array(
					'userid' => $result->fldid,
					'username' => $result->username,
					'email' => $result->email,
					'language' => $result->language,
					'role' => (($result->role) ? strtoupper($result->role) : "USER"),
					'userProfilePic' => $result->imageFile
				);
				
				// UPDATE LAST SEEN IP ADDRESS
				$last_seen_ip = $_SERVER['REMOTE_ADDR'];
				$access_comp = rand(100,10000);
				$this->Usermaster->usermaster_edit(array( 'last_seen_ip' => $last_seen_ip, 'access_comp' => $access_comp ), $result->fldid);
				// SET USER DATA
				$this->session->set_userdata('logged_in', $sess_array);
				$this->session->set_userdata('language', $result->language);
				$this->session->set_userdata('last_seen_ip', $last_seen_ip);
				$this->session->set_userdata('access_comp', $access_comp);
				return true;
			}
		} else {
			echo"<script>alert('Emel atau kata laluan salah.');window.location='".base_url()."'</script>";
			
			return 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 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 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'));
	}
}
?>
