<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "hr/EmployeeClass.php") ;
require_once (PATH_MODELS . "hr/EmployeePasswordClass.php") ;
require_once (PATH_MODELS . "general/ContactInfoClass.php") ;
require_once (PATH_MODELS . "hr/DepartmentClass.php") ;
require_once (PATH_TABLES . "hr/EmployeeTypeTable.php") ;
require_once (PATH_TABLES . "hr/NationalityTable.php") ;
require_once (PATH_TABLES . "hr/RaceTable.php") ;
require_once (PATH_TABLES . "hr/WorkPermitTable.php") ;
require_once (PATH_TABLES . "hr/JobTitleTable.php") ;
require_once (PATH_MODELS . "admin/CompanyClass.php") ;
require_once (PATH_MODELS . "claims/ClaimHeaderClass.php") ;
require_once (PATH_MODELS . "claims/ClaimDetailClass.php") ;
require_once (PATH_MODELS . "claims/ClaimDocumentClass.php") ;
require_once (PATH_MODELS . "claims/ClaimHeaderMsgClass.php") ;
require_once (PATH_MODELS . "portal/ClaimFlowClass.php") ;

class TransactionPurge extends HrmsBase {
	private $type = "" ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
		$this->orgid = $_SESSION[SE_ORGID] ;
		$this->fldorg = ClaimHeaderTable::C_ORG_ID ;
	}
	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_UPDATE:
					$this->updateRecord($params) ;
					break ;
				case REQ_GET:
					$this->getRecord($params) ;
					break ;
				case "TRANS_PURGE":
					$this->purgeTransaction($params) ;
					break ;
				case "GET_EMP":
					$this->getEmpList($params) ;
					break ;
				case REQ_LIST:
					echo $this->getList($params) ;
					break ;
				case REQ_VIEW:
					$this->getView() ;
					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 getRecord($params=null) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new EmployeeClass($this->db) ;
			$pwdCls = new EmployeePasswordClass($this->db);
			$row = $cls->getRecord($id) ;
			$row_pwd = $pwdCls->getRecord($id);
			if (is_null($row)) {
				$this->sendJsonResponse(Status::Error,"Invalid employee id. Please try again.",$id,$this->type);
			} else {
				$datas = array() ;
				$datas['id'] = $id ;
				$datas['name'] = $row[EmployeeTable::C_NAME];
				$datas['code'] = $row[EmployeeTable::C_CODE] ;
				$dte = date_create($row_pwd[EmployeePasswordTable::C_LAST_LOGIN]) ;
				if ($dte == date_create(NULL_DATE))
					$datas['login'] = "" ;
				else
					$datas['login'] = date_format($dte,'d-M-Y H:i:s') ;
				$this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
			}
			unset($cls) ;
		} else {
			$this->sendJsonResponse(Status::Error,"Missing employee id. Please try again.","",$this->type);
		}
	}
	private function updateRecord($params) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls_p = new EmployeePasswordClass($this->db) ;
			try {
				$this->db->beginTran() ;
				$cls_p->resetPassword($id) ; 
				$this->db->commitTran() ;
				$this->sendJsonResponse(Status::Ok,"Employee password is successfully reset from the system.","",$this->type);
			} catch (Exception $e) {
				$this->db->rollbackTran() ;
				Log::write('[Employee Password]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a problem in resetting employee password from the system.","",$this->type) ;
			}
			unset($cls) ;
			unset($cls_p) ;
			
		} else {
			$this->sendJsonResponse(Status::Error,"You must supply the employee id whose password you wish to reset. Please try again.","",$this->type);
		}
	}
	
	private function purgeTransaction($params){
		
		$empCls				= new EmployeeClass($this->db);
		$claimCls 			= new ClaimHeaderClass($this->db);
		$claimDetailCls 	= new ClaimDetailClass($this->db);
		$claimDocumentCls 	= new ClaimDocumentClass($this->db);
		$claimMsgCls 		= new ClaimHeaderMsgClass($this->db);
		$claimFlowCls 		= new ClaimFlowClass($this->db);
		
		$dteStart = new DateTime($this->getParamDate($params, 'date_from', NULL_DATE));
		$dteEnd = new DateTime($this->getParamDate($params, 'date_to', MAX_DATE));
		
		$sql	= "SELECT * ";
		$sql	.= "FROM " . ClaimHeaderTable::C_TABLE . " ";
		$sql	.= "WHERE " . ClaimHeaderTable::C_DATE_SUBMISSION . " >= '" . $dteStart->format('Y-m-d') . " 00:00:00.000' ";
		$sql	.= "AND " . ClaimHeaderTable::C_DATE_SUBMISSION . " <= '" . $dteEnd->format('Y-m-d') . " 23:59:59.999' ";
		$sql 	.= "AND (" . ClaimHeaderTable::C_WORKFLOW_STATUS . " = " . ClaimStatus::Rejected . " or " . ClaimHeaderTable::C_WORKFLOW_STATUS . " = " . ClaimStatus::Approved . ") ";
		if(trim($params['emp_ids']) != ""){
			$sql	.= "AND " . ClaimHeaderTable::C_EMP . " in (" . $params['emp_ids'] . ") ";
		}
		
		$rows = $this->db->getTable($sql);
		if(!is_null($rows) && count($rows) > 0){
			foreach($rows as $row){
				$claimCls->deleteRecord($row[ClaimHeaderTable::C_ID]) ; 
				$claimDetailCls->deleteRecordsPerId($row[ClaimHeaderTable::C_ID]);
				$claimDocumentCls->deleteRecordsPerId($row[ClaimHeaderTable::C_ID]);
				$claimMsgCls->deleteRecord($row[ClaimHeaderTable::C_ID]) ; 
				$claimFlowCls->deleteRecordsByClaimId($row[ClaimHeaderTable::C_ID]) ; 
			}
		}
		
		/*
		$emp_ids = explode(",", $params['emp_ids']);
		if(!is_null($emp_ids) && count($emp_ids) > 0){
			foreach($emp_ids as $emp_id){
				$claim_rows = $claimCls->getClaimList($emp_id, "", "", 0, false, "", false, "1");
				
				if(!is_null($claim_rows) && count($claim_rows) > 0){
					foreach($claim_rows as $claim_row){
						$claimCls->deleteRecord($claim_row['id']) ; 
						$claimDetailCls->deleteRecordsPerId($claim_row['id']);
						$claimDocumentCls->deleteRecordsPerId($claim_row['id']);
						$claimMsgCls->deleteRecord($claim_row['id']) ; 
						$claimFlowCls->deleteRecordsByClaimId($claim_row['id']) ; 
					}
				}
				
				$empCls->deleteRecord($emp_id);
			}
		}*/
		$this->sendJsonResponse(Status::Ok,"Transaction records has been purged","",$this->type);
		
		unset($empCls);
		unset($claimCls);
		unset($claimDetailCls);
		unset($claimDocumentCls);
		unset($claimMsgCls);
		unset($claimFlowCls);
	}
	private function getList($conditions=null) {
		$cls 	= new EmployeeClass($this->db) ;
		$coy 	= new CompanyClass($this->db) ;
		$dept 	= new DepartmentClass($this->db) ;
		$params = array() ;
		
		$filter 	= $this->db->fieldParam(EmployeeTable::C_ORG_ID) ;
		$params[] 	= $this->db->valueParam(EmployeeTable::C_ORG_ID,$_SESSION[SE_ORGID]) ;
		
		if(isset($conditions['company'])  && $conditions['company'] != "") {
			$filter 	.= ' AND ' . $this->db->fieldParam(EmployeeTable::C_COY_ID) ;
			$params[] 	= $this->db->valueParam(EmployeeTable::C_COY_ID,$conditions['company']) ;
		}
		
		if(isset($conditions['department']) && $conditions['department'] != "") {
			$filter 	.= ' AND ' . $this->db->fieldParam(EmployeeTable::C_DEPT) ;
			$params[] 	= $this->db->valueParam(EmployeeTable::C_DEPT,$conditions['department']) ;
		}
		
		if($conditions['resign'] == '0'){
			$dte = new DateTime();
			$filter 	.= ' AND ' . EmployeeTable::C_RESIGN . " <= '" . $dte->format('Y-m-d H:i:s') . "'";
		}
		
		$rows = $cls->getTable($filter,EmployeeTable::C_NAME,$params) ;
		
		$list = "" ;
		
		$claimCls = new ClaimHeaderClass($this->db);
		foreach ($rows as $row) {
			$id = $row[EmployeeTable::C_ID] ;
			$list .= "<tr>" ;
		
			$claim_rows = $claimCls->getClaimList($id, "", "", 0, false, "", false, "2");
			
			$check = "";
			if(is_null($claim_rows) || count($claim_rows) == 0){
				$check .= "<td><input type='checkbox' id='chkEmpPurge" . $id . "'/></td>" ;
				$check .= "<td style='display:none'></td>" ;
				$check .= "<td id='tableOutstanding" . $id . "' style='display:none'></td>" ;
			} else {
				$str = "<table class='data'>";
					$str .= "<tr class='ui-widget-header'>";
					$str .= "<th>Claim Code</th>";
					$str .= "<th>Submission Date</th>";
					$str .= "<th>Status</th>";
					$str .= "</tr>";
				foreach($claim_rows as $claim_row){
					$str .= "<tr>";
					$str .= "<td>" . $claim_row['code'] . "</td>";
					$str .= "<td>" . $claim_row['date_s'] . "</td>";
					$str .= "<td>" . $claim_row['status'] . "</td>";
					$str .= "</tr>";
				}
				$str .= "</table>";
				
				$check .= "<td style='display:none'><input type='checkbox' id='chkEmpPurge" . $id . "'/></td>" ;
				$check .= "<td style='text-align:center'><a href='javascript:' onclick='showOutstanding(" . $id . ")'><img src='image/changepwd_20.png' title='show'></img></a></td>" ;
				$check .= "<td id='tableOutstanding" . $id . "' style='display:none'>" . $str . "</td>" ;
			}
			$list .= $check;
			
			$list .= "<td>" . $id . "</td>" ;
			$list .= "<td>" . $row[EmployeeTable::C_CODE] . "</td>" ;
			$list .= "<td>" . $row[EmployeeTable::C_NAME] . "</td>" ;
			$list .= "<td>" . $coy->getDescription($row[EmployeeTable::C_COY_ID]) . "</td>" ;
			$list .= "<td>" . $dept->getDescription($row[EmployeeTable::C_DEPT]) . "</td>" ;
			$list .= "</tr>" ;
		}
		unset($rows) ;
		unset($cls) ;
		unset($dept) ;
		unset($coy) ;
		
		return $list ;
	}
	

	private function getEmpList($params) {
		$deptId 	= $params['dept_id'] ;
		$companyId	= $params['company_id'];
		
		$cls 	= new EmployeeClass($this->db) ;
		$datas	= array() ;
		$filter = $this->db->fieldParam(EmployeeTable::C_DEPT) ;
		$datas[]= $this->db->valueParam(EmployeeTable::C_DEPT,$deptId) ;
		$filter .= " AND " .$this->db->fieldParam(EmployeeTable::C_COY_ID) ;
		$datas[]= $this->db->valueParam(EmployeeTable::C_COY_ID,$companyId) ;
		
		if($params['resign'] == "0"){
			$dte = new DateTime();
			$filter 	.= ' AND ' . EmployeeTable::C_RESIGN . " <= '" . $dte->format('Y-m-d H:i:s') . "'";
		}
		
		$rows 	= $cls->getTable($filter,EmployeeTable::C_NAME,$datas) ;

		$vls = array() ;
		$vls[] = array ('code'=>"",'desc'=>"----- Select a Employee -----") ;
		if (!is_null($rows) && count($rows) > 0) {
			foreach ($rows as $row) {
				$vls[] = array ('code'=>$row[EmployeeTable::C_ID],'desc'=>$row[EmployeeTable::C_NAME]) ;
			}
		}
		
		$datas = array() ;
		$datas['empList'] =  Util::createOptionValue($vls) ;
		
		$this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
		unset($rows) ;
		unset($list) ;
		unset($cls) ;
	}
	
	private function getResign(){
		$arr = array() ;
		$arr[] = array ('code'=>'0','desc'=>'Resigned Employees' );
		$arr[] = array ('code'=>'1','desc'=>'All Employees' ) ;
		return Util::createOptionValue($arr) ;
	}
	private function getView() {
		ob_start() ;
		include (PATH_VIEWS . "hr/TransactionPurgeView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}
}
?>