<?php
include (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "admin/UserClass.php") ;
require_once (PATH_MODELS . "admin/UserResetPasswordHistoryClass.php") ;
require_once (PATH_MODELS . "general/ContactInfoClass.php") ;
require_once (PATH_MODELS . "admin/OrganizationOptions.php") ;
require_once (PATH_MODELS . "admin/OrganizationClass.php") ;
require_once (PATH_LIB . "LicenseFile.php") ;

class MobileSignIn extends ActivityBase {
    private $clsUser;
	function __construct() {
		$this->db = $_SESSION[SE_DB];
        $this->clsUser = new UserClass($this->db);
	}
	function __destruct() {
        unset($this->clsUser) ;
	}
	public function processRequest($params) {
		// log::write(print_r($params,true));
		$userName = "" ;
		$pwd = "" ;
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
			$this->loadOrganizationName();
			$isTurnOff = false;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
				if (isset($params['id']))
					$userName = $params['id'];
				if (isset($params['pwd'])) {
                    $pwd = Util::decryptData($params['pwd'],$_SESSION[SE_USERKEY]) ;
				}
			}

			switch ($this->type) {
				case REQ_SIGNIN:
					$this->processLogin($userName,$pwd, false, $isTurnOff) ;
					break ;
				case REQ_SIGNOUT:
					$this->processLogout($userName) ;
					break ;
				case REQ_QUERY:
					$this->processQuery($userName, $isTurnOff) ;
					break ;
				case REQ_NEW:
					$this->processLogin($userName,$pwd,true) ;
					break ;
				case REQ_VIEW:
					$this->processView() ;
					break ;
				case "RESET_PWD":
					$this->processResetPwd($userName) ;
					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 processResetPwd($empcode){
        $clsUserResetPasswordHistory = new UserResetPasswordHistoryClass($this->db);
        
		$row = $this->clsUser->getRecordByName(0, $empcode);
		if(is_null($row)){
			$this->sendJsonResponse(Status::Error,"cannot find username","", $this->type);
			return;
		}
		
		if(trim($row[UserTable::C_EMAIL]) == ""){
			$this->sendJsonResponse(Status::Error,"Your email address is not registered. Please contact your system administrator.","", $this->type);
			return;
		}
		
		try{
			
			$newPwd = Util::randomPassword($row[UserTable::C_ID]);
		
			$lines  = "Dear " . $row[UserTable::C_FULL_NAME] . ", <br><br>";
			$lines .= "This is an automated message generated by system to help you reset your eService password. <br><br>";
			$lines .= "<table>";
			$lines .= "<tr><td style='text-align:right'>Login using new password :</td><td>" . $newPwd . "</td></tr>";
			$lines .= "<tr><td style='text-align:right'>Generated on :</td><td>" . date_format(new DateTime(), 'd/m/Y h:i:s') . "</td></tr>";
			$lines .= "</table><br><br>";
			
			$lines .= "Please enter the above code to login into system. You can change the password after you login.<br><br>";
			
			$this->orgId = $row[UserTable::C_ORG_ID];
			$resEmail =  $this->sendEmail("[NO-REPLY] eService Password Reset", 
											$lines,
											null, 
											explode(";",$row[UserTable::C_EMAIL]), 
											null,
                                            null);
			
			if($resEmail){
				//$this->clspwd->changePassword($id, $newPwd);
				$this->clsUser->forgetPassword($row[UserTable::C_ID], $newPwd);
                
                $clsUserResetPasswordHistory->insertHistoryReset($row[UserTable::C_ID], $row[UserTable::C_ID], 1);
                
				$this->sendJsonResponse(Status::Ok,"An email containing your reset code has been sent to your email address. Please use the code to login.","", $this->type);
			} else {
				$this->sendJsonResponse(Status::Error,"There is an error in sending email for password reset. Please contact administrator.", "", $this->type);
			}
		} catch (Exception $e){
			Log::write("[RESET_PWD] " . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Unsuccessful database operation","",$this->type) ;
		}
		
		$this->orgId = -1;
        
        unset($clsUserResetPasswordHistory);
	}
	private function processLogin($username,$pwd,$firsttime=false) {
		$status = "" ;
		$mesg = "" ;
		$data = "" ;
		$id = "" ;
		$orgid = -1 ;
		$row = $this->clsUser->getRecordByName(0,$username);
		if (is_null($row) || count($row) == 0) {
			$status = Status::Error ;
			$mesg = "Invalid user name.";
		} else {
			
			$id = $row[UserTable::C_ID];
			$cnt = $row[UserTable::C_FAIL_COUNT] ;
			$group = $row[UserTable::C_GROUP] ;
			$name = $row[UserTable::C_FULL_NAME] ;
			$orgid = $row[UserTable::C_ORG_ID] ;
			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()) {
					$status = Status::Error;
					$mesg = "You can only login after " . date('Y-m-d',$row[UserTable::C_START_DATE]) ;
				} 
			}
			if ($status == "") {
				$dte = date_create($row[UserTable::C_EXPIRY_DATE]) ;
				if ($dte != date_create(MAX_DATE)) {
					if ($row[UserTable::C_EXPIRY_DATE] > time()) {
						$status = Status::Error ;
						$mesg = "Yours account have already expired. Please contact your system administrator for assistance.";
					}
				}
			}
		}
		if ($status == "") {
			if ($firsttime) {
				$this->clsUser->changePassword($id,$pwd) ;
			} else {
				// 5ef27ddc3a25a0242096718cb7d10071  : 12345 pwd
				if ($this->clsUser->encryptPwd1($pwd) != $row[UserTable::C_PWD1]) {
					$status = Status::Error ;
					$mesg = "Invalid password. Please try again." ;
					$this->clsUser->updateFailCount($id,$cnt + 1) ;
				}
			}
		}
		if ($status == "") {
			$status = Status::Ok ;
			$this->clsUser->updateLogin($id) ;
			$this->setLogin($id,$username,$name,$group,$orgid) ;
			$data = "index.pzx?c=" . Util::convertLink("MobileHome");
		} else {
			
		}
		$this->sendJsonResponse($status,$mesg,$data);
	}
	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 processQuery($username) {
		$status = "" ;
		$mesg = "" ;
		$data = "" ;
		$id = "" ;
		$chngpwd = false ;
		$key = "" ;
		$row = $this->clsUser->getRecordByName(0,$username);
		if (is_null($row) || count($row) == 0) {
			$status = Status::Error ;
			$mesg = "Invalid user name.";
		} else {
			$id = $row[UserTable::C_ID];
			$cnt = $row[UserTable::C_FAIL_COUNT] ;
			$chngpwd = $row[UserTable::C_CHANGE_PWD] ;
			if ($cnt > 2) {
				$status = Status::Error;
				$mesg = "You account have been disabled. Please contact your system administrator for assistance.";
			}
			if ($status == "") {
				if ($row[UserTable::C_START_DATE] > time()) {
					$status = Status::Error;
					$mesg = "You can only login after " . date('Y-m-d',$row[UserTable::C_START_DATE]) ;
				} 
			}
			if ($status == "") {
				$dte = date_create($row[UserTable::C_EXPIRY_DATE]) ;
				
				if ($dte != date_create(MAX_DATE)) {
					if ($row[UserTable::C_EXPIRY_DATE] > time()) {
						$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 == 1) {
				$status = Status::Info ;
			} else {
				$status = Status::Confirm ;
			}
		}

		$this->sendJsonResponse($status,$mesg,$data);
	}
	private function processLogout($params) {
		$this->setLogin("","",-1) ;
		$_SESSION[SE_USERKEY] = "" ;
		$this->sendJsonResponse(Status::Ok,"","index.pzx") ;
	}
	private function setLogin($userid,$username,$fullname,$usergroup,$orgid) {
		$_SESSION[SE_USERID] = $userid ;
		$_SESSION[SE_USERNAME] = $username ;
		$_SESSION[SE_USERGROUP] = $usergroup ;
		$_SESSION[SE_FULLNAME] = $fullname ;
		$_SESSION[SE_MENU] = "";
		$_SESSION[SE_ORGID] = $orgid ;
		$_SESSION[SE_ORGNAME] = "";
	}
	private function processView() {
		ob_start() ;
		include (PATH_VIEWS . "mobile/MobileSignInView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}
	
	private function loadOrganizationName(){
		$clsOrg		= new OrganizationClass($this->db);
		$row 		= $clsOrg->getTable() ;
		
		if (count($row)>0 && !is_null($row)) {
			foreach($row as $org) {
				$opt = new OrganizationOptions() ;
				$opt->loadXml($org[OrganizationTable::C_OPTIONS]) ;
				$op = $opt->getOption() ;
				$_SESSION[SE_ORGNAME] = $op[OrganizationOptions::C_CONTACT][OrganizationOptions::C_CONT_NAME1] ;
				$_SESSION[SE_ORGCODE] = $org[OrganizationTable::C_CODE] ;
				unset($opt) ;
			}
		}
		else {
			$_SESSION[SE_ORGNAME] = "Default Company" ;
			$_SESSION[SE_ORGCODE] = "" ;
		}
		unset($row) ;
	}
	
	private function getOrganizationName(){
		return $_SESSION[SE_ORGNAME];
	}
}
?>
