<?php

use PhpOffice\PhpSpreadsheet\Calculation\Token\Stack;

include (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "admin/UserClass.php") ;
require_once (PATH_MODELS . "admin/UserResetPasswordHistoryClass.php") ;
require_once (PATH_MODELS . "admin/UserPasswordHistoryClass.php") ;
require_once (PATH_LIB . "LicenseFile.php") ;

class MobileSignIn extends MobileBase {
	private $clsuser ;
	private $type ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
		$this->clsuser = new UserClass($this->db) ;

	}
	function __destruct() {
		unset($this->clsuser) ;

	}
	public function processRequest($params) {
		$username = "" ;
		$pwd = "" ;
		$token = "" ;
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
			$isTurnOff = false;
			if (isset($params) && count($params) > 0) {
				//for processQuery()
				//===============================
				if (isset($params['pwd1']))
					$pwd1 = $params['pwd1'] ;
				//===============================
				if (isset($params['type']))
					$this->type = $params['type'] ;
				if (isset($params['id']))
					$username = $params['id'];
				if (isset($params['turn_off']) && $params['turn_off'] == 'y'){
					$isTurnOff = true;
				}
				if (isset($params['pwd'])) {
					if ($isTurnOff){
						$pwd = $params['pwd'];
					} else {
						$pwd = Util::decryptData($params['pwd'],$_SESSION[SE_USERKEY]) ;
					}
				}
				if (isset($params['token'])) {
					$token = $params['token'];
				}
			}

			switch ($this->type) {
				case REQ_SIGNIN:
					$this->processLogin($username,$pwd, false, $isTurnOff,$token) ;
					break ;
				case REQ_SIGNOUT:
					$this->processLogout($username) ;
					break ;
				case REQ_QUERY:
					$this->processQuery($username, $pwd1, $isTurnOff) ;
					break ;
				case REQ_NEW:
					$this->processLogin($username,$pwd,true) ;
					break ;
				case REQ_VIEW:
					$this->processView() ;
					break ;
				case Command::InvalidSession:
					$this->invalidSession() ;
					break ;
				default:
					$this->sendJsonResponse(Status::Error,"Invalid request.","") ;
					break ;
			}
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
	}

	private function invalidSession(){
		$this->sendJsonResponse(Status::Error,"Your session has timeout, please login again.","", $this->type);
	}
	
	private function processLogin($username,$pwd,$firsttime=false, $isTurnOff=false, $token="",$loginwin=false) {
		$status = "" ;
		$mesg = "" ;
		$data = "" ;
		$id = "" ;
		$orgid = -1 ;
		$row = $this->clsuser->getRecordByName(0,$username);
		$cls = new UserPasswordHistoryClass($this->db);
		$chngpwd = 0;

		if (is_null($row) || count($row) == 0) {
			$status = Status::Error ;
			$mesg = "Invalid user code.";
		} else {
			$id = $row[UserTable::C_ID];
			$name = $row[UserTable::C_NAME] ;
			$orgid = $row[UserTable::C_ORG_ID] ;
			$group = $row[UserTable::C_USER_GROUP] ;
			$fullname = $row[UserTable::C_FULL_NAME];

			$cnt = $row[UserTable::C_FAIL_COUNT];
			$chngpwd = $row[UserTable::C_CHANGE_PWD];

			if ($cnt > 2) {
				$status = Status::Error;
				$mesg = "Your account have been disabled. Please contact your system administrator for assistance.";
			}

			// if ($status == "") {
			// 	//if ($row[UserTable::C_START_DATE] > time()) {
			// 	if (date_create($row[UserTable::C_START_DATE])->format('Y-m-d') > date('Y-m-d')) {
			// 		$status = Status::Error;
			// 		$mesg = "You can only login after 1 " . date_create($row[UserTable::C_START_DATE])->format('d/m/Y') ;
			// 	} 
			// }
			// if ($status == "") {
			// 	$dte = date_create($row[UserTable::C_EXPIRY_DATE]) ;
			// 	if ($dte != date_create(MAX_DATE)) {
			// 		//if ($row[UserTable::C_EXPIRY_DATE] < time()) {
			// 		if (date_create($row[UserTable::C_EXPIRY_DATE])->format('Y-m-d') < date('Y-m-d')) {
			// 			$status = Status::Error ;
			// 			$mesg = "Yours account have already expired. Please contact your system administrator for assistance.";
			// 		}
			// 	}
			// }

		}

		if ($status == "") {
			if ($firsttime) {
				$strCheck = Util::checkPasswordComplexity($pwd);
				if($strCheck != ""){
					$status = Status::Error ;
					$mesg = $strCheck ;
				} else{
					if($cls->checkPasswordSimiliarToPrevious($id, $pwd)){
						$cls->insertPasswordHistory($id, $pwd);
						$this->clsuser->changePassword($id,$pwd) ;
					}else{
						$status = Status::Error ;
						$mesg = "New password cannot be same as previous 3 password" ;
					}
				}
			} else {
				if(!$loginwin){
					if ($this->clsuser->encryptPwd1($pwd) != $row[UserTable::C_PWD1]) {
						$status = Status::Error ;
						$mesg = "Invalid password. Please try again." ;
						$this->clsuser->updateFailCount($id,$cnt + 1) ;
					}
				}else{
					$status="";
				}
			}
		}
		if ($status == "") {
			// if($typename="REQ_SIGNIN") {
			// 	$status = Status::Info ;
			// } else if ($typename = "REQ_NEW") {
				$status = Status::Ok ;
			// }
			$this->clsuser->updateLogin($id, $chngpwd) ;

			if($isTurnOff){
				$data = array();

				//user profile
				$arrEmp = array();

				$arrEmp['user_id'] 		= $row[UserTable::C_ID];
				$arrEmp['user_name'] 	= $row[UserTable::C_NAME];
				// $arrEmp['user_email'] 	= $row[UserTable::C_EMAIL];
				$data['user_profile'] = $arrEmp;

				unset($row);
				unset($arrEmp);

				$data['lic_modules'] = $this->getLicenseModules();

				$mesg = "Login Success";
				Log::write("login 9");
			} else {
				Log::write("login 8");
				if($_SESSION[SE_USERID] != $row[UserTable::C_ID]){
					session_regenerate_id(true);
					$_SESSION[SE_ID] = session_id();
				}
				$this->setLogin($id,$name,$fullname,$orgid,$group) ;
				$data = "index.pzx?c=" . Util::convertLink("ScheduleList");
				if($loginwin){
					header("Location:".$data."&d=" . time());
					//$_SESSION[SE_WIN]="";
					exit();
				}			
			}
		} else {
			Log::write("login 7");
		}
		
		$this->sendJsonResponse($status,$mesg,$data, $this->type);
	}

	private function getLicensing(){
		$licenseFile = new LicenseFile();
		$licenseFile->read(PATH_CODE . "sbg.lic");

		$dtLicense = new DateTime($licenseFile->getExpiryDate());
		//$dtLicense = new DateTime('2015-03-01');
		$dtNow = new DateTime();
		if($dtLicense < $dtNow)
			return 1;

		$dtdiff = $dtLicense->diff($dtNow);
		if($dtdiff->days < 60)
			return 2;

		return 0;
	}
	private function getLicenseDate(){
		$licenseFile = new LicenseFile();
		$licenseFile->read(PATH_CODE . "sbg.lic");

		$dtLicense = new DateTime($licenseFile->getExpiryDate());

		return $dtLicense->format("d/m/Y");
	}
	private function getLicenseModules(){
		$licenseFile = new LicenseFile();
		$licenseFile->read(PATH_CODE . "sbg.lic");

		$datas = array();

		// $datas['ExpenseClaims'] = Util::isModuleEnabled(ModuleInfo::ExpenseClaims);
		// $datas['eLeave'] = Util::isModuleEnabled(ModuleInfo::eLeave);

		return $datas;
	}
	private function processQuery($username, $pwd1, $isTurnOff = false) {
		$status = "" ;
		$mesg = "" ;
		$data = "" ;
		$id = "" ;
		$chngpwd = false ;
		$orgid = -1;
		$key = "" ;
		$row = $this->clsuser->getRecordByName(0,$username);
		
		if (is_null($row) || count($row) == 0) {
			$status = Status::Error ;
			$mesg = "Invalid username.";
		} else {
			$id = $row[UserTable::C_ID];
			$name = $row[UserTable::C_NAME] ;
			$orgid = $row[UserTable::C_ORG_ID] ;

				$chngpwd = $row[UserTable::C_CHANGE_PWD] ;
				$cnt = $row[UserTable::C_FAIL_COUNT];

			if ($cnt > 2) {
				$status = Status::Error;
				$mesg = "Your account have been disabled. Please contact your system administrator for assistance.";
			}

			// if ($status == "") {
			// 	//if ($row[UserTable::C_START_DATE] > time()) {
			// 	if (date_create($row[UserTable::C_START_DATE])->format('Y-m-d') > date('Y-m-d')) {
			// 		$status = Status::Error;
			// 		$mesg = "You can only login after 2 " . date_create($row[UserTable::C_START_DATE])->format('d/m/Y') ;
			// 	} 
			// }
			// if ($status == "") {
			// 	$dte = date_create($row[UserTable::C_EXPIRY_DATE]) ;
			// 	if ($dte != date_create(MAX_DATE)) {
			// 		//if ($row[UserTable::C_EXPIRY_DATE] < time()) {
			// 	if (date_create($row[UserTable::C_EXPIRY_DATE])->format('Y-m-d') < date('Y-m-d')) {
			// 			$status = Status::Error ;
			// 			$mesg = "Yours account have already expired. Please contact your system administrator for assistance.";
			// 		}
			// 	}
			// }

		}
		
		if ($status == "") {
			$mesg = "" ;
			$key = Util::createMD5(time().$username,"","",true) ;
			$_SESSION[SE_USERKEY] = $key ;
			$data = $key ;
			if ($chngpwd == 2) {
				//check if password is same as generated password in email
				if ($this->clsuser->encryptPwd1($pwd1) != $row[UserTable::C_PWD1]) {
					$status = Status::Error;
					$mesg = "Invalid password. Please try again.";
				}else{
					$status = Status::Info ;
				}
			} else if($chngpwd == 1){
				$status = Status::Info ;
			} else {
				if($isTurnOff){
					//temporary - start
					$data = array();
					$data['user_ID'] = $row[UserTable::C_ID] ;
					$data['user_CODE'] = $row[UserTable::C_NAME] ;
					$data['ORG_ID'] = $row[UserTable::C_ORG_ID] ;
					$data['COY_ID'] = $row[UserTable::C_COY_ID] ;

					//$data = json_encode($data);
					$mesg = $key ;
					//temporary - end
				}
				$status = Status::Confirm ;
			}
		}

		$this->sendJsonResponse($status,$mesg,$data);
	}
	private function processLogout($params) {
		$this->setLogin("","","","",-1,0) ;
		$_SESSION[SE_USERKEY] = "" ;
	
		unset($_SESSION[SE_BU]);
		$this->sendJsonResponse(Status::Ok,"","index.pzx") ;
	}
	private function setLogin($userid,$username,$fullname,$orgid,$usergroup) {
		$_SESSION[SE_USERID] 		= $userid ;
		$_SESSION[SE_INIT] 			= true ;
		$_SESSION[SE_USERNAME] 		= $username ;
		$_SESSION[SE_USERGROUP] 	= $usergroup ;
		$_SESSION[SE_PORT_FULLNAME] = $fullname ;
		//$_SESSION[SE_MENU] 		= "";
		
		// to ensure org_id
		if($userid != ""){
			$row = $this->clsuser->getRecord($userid);
			$orgid = $row[UserTable::C_ORG_ID] ;
		}
		$_SESSION[SE_ORGID] 		= $orgid ;
		$_SESSION[SE_PORT_ORGNAME] 	= "";
		$_SESSION[SE_LEDGER] 		= "";
	}
	private function testing(){
			Log::write("testing");
			$url = 'https://fcm.googleapis.com/fcm/send';

		    $fields = array(
		    			"to" => "cu37WUj_SoCosi6EyXVEKN:APA91bENxUDwGPHoHOIkWCMjF8CiWY3Aji_5Run9vA5aYYS1T_DnuH2-X3ghiijlkAuzOyGjiYlfsk2tYJddsg-vT59fIINB8PpKzG_d99Q5uPVtX49KmVAt_vWfj_LI3dmegYb3RLxK",
		    		  	"priority" => "high",
		    		   	"notification" => array(
		    		   						"title" => "Leave Notification",
		    		   						"body" => "Dear test, there is new an update to your Leave Code [test], Let's check it out!",
		    		   					),
		    		   	"data" => array(
		    		   				"click_action" => "FLUTTER_NOTIFICATION_CLICK",
		    		   				"status" => "done",
		    		   				"sound" => "default",
		    		   				"screen" => "LEAVE_PAGE",
		    		   			)
		    		  );

		    $fields = json_encode($fields);

		    $headers = array (
		            		'Authorization: key=' . "AAAARCw-D7s:APA91bHuTDgXydsiVLyLmfdEReOjyF8Fmi_JjnEeJ-uwbNKHqjAb4kiE7lC-Jm-kBIFbj4A7QzqcPjic072qXx0ZIzo2npB4ikWCkCKpsPVaDJ1Ms1uWGIm72ryZcfsD8UC25-bPcnyy",
		            		'Content-Type: application/json'
		    			);

		    $ch = curl_init();
		    curl_setopt($ch, CURLOPT_URL, $url);
		    curl_setopt($ch, CURLOPT_POST, true);
		    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

		    $result = curl_exec($ch);
		    var_dump($result);

		    if($result === false){
	    		$response = curl_error($ch);
	    		Log::write(curl_getinfo($ch));
		    }

		    curl_close($ch);
	}
	private function processView() {
		ob_start() ;
		include (PATH_VIEWS . "mobile/MobileSignInView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}
	private function getLicensingAPI(){
		$status 	= "" ;
		$mesg 		= "" ;
		$data 		= 0 ;

		$licenseFile = new LicenseFile();
		$licenseFile->read(PATH_CODE . "sbg.lic");

		$dtLicense = new DateTime($licenseFile->getExpiryDate());
		$dtNow = new DateTime();
		if($dtLicense < $dtNow) {
			$status 	= Status::Ok ;
			$data 		=  1;
			$mesg 		= "The license for this product is expired. Please contact system administrator.";
		}

		$dtdiff = $dtLicense->diff($dtNow);
		if($dtdiff->days < 60){
			$status 	= Status::Ok ;
			$data 		= 2;
			$mesg 		= "The license for this product is expiring soon. Please contact system administrator.";
		}

		$this->sendJsonResponse($status,$mesg,$data,$this->type);
	}
}
?>
