<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "admin/UserClass.php");

class UserApi extends ControllerBase {
	private $type = "" ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
		$this->orgid = $_SESSION[SE_ORGID] ;
	}
	function __destruct() {
		unset($this->db) ;
	}
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		
		try {
			$this->db->open() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			switch ($this->type) {
				case REQ_SIGNIN:
					$this->processLogin($params) ;
					break ;
				default:
					$this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
					break ;
			}
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
	}

	private function processLogin($params) {
		$status 	= "" ;
		$mesg 		= "" ;
		$data 		= "" ;
		$id 		= "" ;
		$username 	= $params['username'];
		$pwd 		= $params['password'];
		$cls 		= new UserClass($this->db) ;


		$row = $cls->getRecordApiByName($username);
		// Log::Write(print_r($row, 1));
		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] ;
			if ($cnt > 2) {
				$status = Status::Error;
				$mesg = "Your account have been disabled. Please contact your system administrator for assistance.";
			}
		}
		if ($status == "") {
			//5ef27ddc3a25a0242096718cb7d10071  : 12345 pwd
			if ($cls->encryptPwd1($pwd) != $row[UserTable::C_PWD1]) {
				$status = Status::Error ;
				$mesg = "Invalid password. Please try again." ;
				$cls->updateFailCount($id,$cnt + 1) ;
			}else{
				$status 	= Status::Ok ;
				$mesg 		= "Login Success" ;
				$data 		= $row ;
			}
			
		}

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

}

?>