<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/ProjectPhaseClass.php") ;
require_once (PATH_MODELS . "activity/ProjectPhaseUserClass.php") ;
require_once (PATH_MODELS . "activity/ProjectPhaseUserRightsClass.php") ;
require_once (PATH_MODELS . "activity/ProjectClass.php") ;
require_once (PATH_MODELS . "admin/UserClass.php") ;
require_once (PATH_MODELS . "general/ContactInfoClass.php") ;

class ProjectPhase extends ActivityBase {
	private $type = "" ;
	
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
		$this->orgid = $_SESSION[SE_ORGID] ;
		$this->fldorg = ProjectPhaseTable::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_ADD:
					$this->addRecord($params) ;
					break ;
				case REQ_UPDATE:
					$this->updateRecord($params) ;
					break ;
				case REQ_DELETE:
					$this->deleteRecord($params) ;
					break ;
				case REQ_GET:
					$this->getRecord($params) ;
					break ;
				case REQ_GET . '_HEAD':
				case REQ_GET . '_USER':
					$this->getUser($params) ;
					break ;
				case REQ_LIST:
					$this->getList() ;
					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 addRecord($params) {
		$cls 		= new ProjectPhaseClass($this->db) ;
		$datas 		= array() ;
		$orgid 		= $_SESSION[SE_ORGID] ;
		$modifyby 	= $_SESSION[SE_USERID] ;
		$modifydate = date_create('now')->format('Y-m-d H:i:s') ;
        $ws             = $_SESSION[SE_REMOTE_IP] ;

		$datas[] = $this->db->fieldValue(ProjectPhaseTable::C_DESC,$this->getParam($params,'desc',"")) ;
		$datas[] = $this->db->fieldValue(ProjectPhaseTable::C_REF,$this->getParam($params,'ref',"")) ;
		$datas[] = $this->db->fieldValue(ProjectPhaseTable::C_PROJECT_ID,$this->getParamInt($params,'project_id',0)) ;
		$datas[] = $this->db->fieldValue(ProjectPhaseTable::C_COY_ID,$orgid) ;
		$datas[] = $this->db->fieldValue(ProjectPhaseTable::C_ORG_ID,$orgid) ;
        $datas[] = $this->db->fieldValue(ProjectPhaseTable::C_WS_ID,$ws) ;
		$datas[] = $this->db->fieldValue(ProjectPhaseTable::C_MODIFY_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(ProjectPhaseTable::C_MODIFY_DATE,$modifydate) ;
		$datas[] = $this->db->fieldValue(ProjectPhaseTable::C_CREATE_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(ProjectPhaseTable::C_CREATE_DATE,$modifydate) ;
		
		$userList = $this->getParam($params,'user',""); 
		$userRightsList = $this->getParam($params,'rights',""); 
		try {
			$this->db->beginTran() ;
			$projectPhaseId = $cls->addRecord($datas) ;
			
			$this->addProjectPhaseUser($projectPhaseId, $userList) ;
			$this->addProjectPhaseUserRights($projectPhaseId, $userRightsList);
			
			$this->db->commitTran() ;
			$this->sendJsonResponse(Status::Ok,"Project Phase successfully added to the system.",$projectPhaseId,$this->type);
		
		} catch (Exception $e) {
			$this->db->rollbackTran() ;
			Log::write('[Project Phase] ' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, we are unable to process your request as there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
	}
    
    
	private function updateRecord($params) {
		if (isset($params['project_phase_id'])) {
			$datas          = array() ;
			$projectPhaseId = $this->getParamInt($params,'project_phase_id',0);
			$userList       = $this->getParam($params,'user',""); 
			$userRightsList = $this->getParam($params,'rights',"");
			$orgid          = $_SESSION[SE_ORGID] ;
			$modifyby       = $_SESSION[SE_USERID] ;
			$modifydate     = date_create('now')->format('Y-m-d H:i:s') ;
            $ws             = $_SESSION[SE_REMOTE_IP] ;
			
			$cls = new ProjectPhaseClass($this->db) ;			
			try {
				$this->db->beginTran();
				
                $datas[] = $this->db->fieldValue(ProjectPhaseTable::C_DESC,$this->getParam($params,'desc',"")) ;
                $datas[] = $this->db->fieldValue(ProjectPhaseTable::C_REF,$this->getParam($params,'ref',"")) ;
                $datas[] = $this->db->fieldValue(ProjectPhaseTable::C_PROJECT_ID,$this->getParamInt($params,'project_id',0)) ;
                $datas[] = $this->db->fieldValue(ProjectPhaseTable::C_COY_ID,$orgid) ;
                $datas[] = $this->db->fieldValue(ProjectPhaseTable::C_ORG_ID,$orgid) ;
                $datas[] = $this->db->fieldValue(ProjectPhaseTable::C_WS_ID,$ws) ;
                $datas[] = $this->db->fieldValue(ProjectPhaseTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(ProjectPhaseTable::C_MODIFY_DATE,$modifydate) ;
                $datas[] = $this->db->fieldValue(ProjectPhaseTable::C_CREATE_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(ProjectPhaseTable::C_CREATE_DATE,$modifydate) ;

				$cls->updateRecord($projectPhaseId, $datas);
				
				$this->deleteProjectPhaseUser($projectPhaseId) ;
				$this->addProjectPhaseUser($projectPhaseId, $userList) ;
				
				$this->deleteProjectPhaseUserRights($projectPhaseId) ;
				$this->addProjectPhaseUserRights($projectPhaseId, $userRightsList) ;
				
				$this->db->commitTran() ;
				$this->sendJsonResponse(Status::Ok,"Project Phase successfully updated to the system.",$projectPhaseId,$this->type) ;
			} catch (Exception $e) {
				$this->db->rollbackTran() ;	
				Log::write('[Project Phase] ' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating Request Approval Group to the system.","",$this->type) ;
			}
			unset($cls) ;
		} else {
			$this->sendJsonResponse(Status::Error,"You must supply the Request Approcal Group id you wish to update. Please try again.","",$this->type);
		}
	}
	private function deleteRecord($params) {
		if (isset($params['project_phase_id'])) {
			$projectPhaseId    = $params['project_phase_id'] ;
			$cls        	   = new ProjectPhaseClass($this->db) ;
			try {
                    $this->db->beginTran() ;

                    $cls->deleteRecord($projectPhaseId);
                    $this->deleteProjectPhaseUser($projectPhaseId) ;
                    $this->deleteProjectPhaseUserRights($projectPhaseId) ;

                    $this->db->commitTran() ;
                    $this->sendJsonResponse(Status::Ok,"Project Phase successfully deleted from the system.",$projectPhaseId,$this->type);
			} catch (Exception $e) {
				$this->db->rollbackTran() ;
				$this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting Request Approval Group from the system.","",$this->type) ;
			}
			unset($cls) ;
		} else {
			$this->sendJsonResponse(Status::Error,"You must supply the Request Approval Group id if you wish to delete. Please try again.","",$this->type);
		}
	}

	private function getList() {
		$cls            = new ProjectPhaseClass($this->db) ;
		$userCls        = new ProjectPhaseUserClass($this->db);
		$userRightsCls    = new ProjectPhaseUserRightsClass($this->db);	
		
		$list = "";
        
        try {
            $rows = $cls->getTable() ;

            if (!is_null($rows) || count($rows) > 0) {
            foreach($rows as $row){
              
                    $list .= "<tr id='request-project-phase-rows'>"; 
                    $list .= "<td>" . $row[ProjectPhaseTable::C_ID] . "</td>";
                    $list .= "<td>" . $row[ProjectPhaseTable::C_DESC] . "</td>";
                    $list .= "<td>" . $row[ProjectPhaseTable::C_REF] . "</td>";
                    $list .= "<td style='text-align:center'><a href='javascript:' onclick='editProjectPhase(" . $row[ProjectPhaseTable::C_ID] . ", this)'><img src='image/edit_16.png' title='Edit'></img></a></td>";
                    $list .= "<td style='text-align:center'><a href='javascript:' onclick='deleteProjectPhase(" . $row[ProjectPhaseTable::C_ID] . ", this)'><img src='image/delete_16.png' title='Delete'></img></a></td>";

                    $list .= "</tr>";
      
            }
        }
            unset($rows) ;
        } catch (Exception $exc) {
			Log::write('[Project Phase] ' . $exc->getMessage());
        }
		unset($cls) ;
		unset($headCls);
		unset($preparerCls);
		return $list ;
	}
	private function getRecord($params=null) {
		if (isset($params['project_phase_id'])) {
			$project_phase_id 	= $params['project_phase_id'] ;
			$cls        = new ProjectPhaseClass($this->db);
			
			$row        = $cls->getRecord($project_phase_id);
			
			if (is_null($row) || count($row) == 0) {
				$this->sendJsonResponse(Status::Error,"Invalid Project Phase id. Please try again.",$project_phase_id,$this->type);
			} else {
				$datas = array() ;
				$datas['id']                = $row[ProjectPhaseTable::C_ID];
				$datas['desc']              = $row[ProjectPhaseTable::C_DESC];
				$datas['ref']               = $row[ProjectPhaseTable::C_REF];
				$datas['project_id']  		= $row[ProjectPhaseTable::C_PROJECT_ID];
				$datas['user']              = $this->getProjectPhaseUser($project_phase_id);
				$datas['rights']          	= $this->getProjectPhaseUserRights($project_phase_id);
				$this->sendJsonResponse(Status::Ok,"",$datas,$this->type);
			}
			unset($cls) ;
		} else {
			$this->sendJsonResponse(Status::Error,"Missing Project Phase id. Please try again.","",$this->type);
		}
	}
	private function getView() {
		ob_start() ;
		include (PATH_VIEWS . "activity/ProjectPhaseView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}

	private function getEmpGroup() {
		$filter = array();
		$filter[] = array('field'=>$this->fldorg,'value'=>$this->orgid) ;
		$vls = $this->getValueList(EmployeeTable::C_TABLE, EmployeeTable::C_ID, EmployeeTable::C_NAME ,array('code'=>'','desc'=>'--- Select Emp. ---'),$filter) ;
		return Util::createOptionValue($vls) ;
	}
	
	/**
	 * Structure of limits : employee , workflow_id | employee , workflow_id | employee , workflow_id..   
	 * 							=> workflow_step is step1, step2, ane etc in company setting => from there we can know corresponding workflow_id of that step
	 * @param  $id    		claim group id
	 * @param  $subprojectPhaseId  claim sub group id
	 * @param  $limits		employee and workflow that the employee take responsible to approve
	 */
	private function addProjectPhaseUser($projectPhaseId, $userList) {
		$cls 		= new ProjectPhaseUserClass($this->db);
		if ($userList != "") {
			$lines 	= explode("|",$userList) ;
			$l = array();
			foreach($lines as $line){
				$l[] = explode('~', $line);
			}
			
			//shifting
			for($i = 0; $i < count($l) - 1 ; $i++){
				for($j = 0; $j < count($l) - 1 - $i; $j++){
					if(intval($l[$j][0]) > intval($l[$j+1][0])){
						$temp = $l[$j];
						$l[$j] = $l[$j+1];
						$l[$j+1] = $temp;
					}
				}
			}
			
			for ($i= 0;$i < count($l) ;$i++) {
				$datas = array() ;
				$datas[] = $this->db->fieldValue(ProjectPhaseUserTable::C_ID ,$projectPhaseId);
				$datas[] = $this->db->fieldValue(ProjectPhaseUserTable::C_USER ,$l[$i][0]) ;
				$datas[] = $this->db->fieldValue(ProjectPhaseUserTable::C_ORDER ,$i);
				$cls->addRecord($datas) ;
			}
		}
        unset($cls);
	}
	
	private function addProjectPhaseUserRights($projectPhaseId, $userRightsList) {
		$cls 		= new ProjectPhaseUserRightsClass($this->db);
		if ($userRightsList != "") {
			$lines 	= explode("|",$userRightsList) ;
			
			$l = array();
			foreach($lines as $line){
				$l[] = explode('~', $line);
			}
			
			//shifting
			for($i = 0; $i < count($l) - 1 ; $i++){
				for($j = 0; $j < count($l) - 1 - $i; $j++){
					if(intval($l[$j][0]) > intval($l[$j+1][0])){
						$temp = $l[$j];
						$l[$j] = $l[$j+1];
						$l[$j+1] = $temp;
					}
				}
			}
			
			for ($i= 0;$i < count($l) ;$i++) {
				$datas = array() ;
				$datas[] = $this->db->fieldValue(ProjectPhaseUserRightsTable::C_ID ,$projectPhaseId);
				$datas[] = $this->db->fieldValue(ProjectPhaseUserRightsTable::C_USER ,$l[$i][0]) ;
				$datas[] = $this->db->fieldValue(ProjectPhaseUserRightsTable::C_ORDER ,$i);
				$cls->addRecord($datas) ;
			}
		}
        unset($cls);
	}
	
	private function deleteProjectPhaseUser($id) {
		$cls = new ProjectPhaseUserClass($this->db) ;
		try {
			$cls->deleteRecord($id);
		} catch (Exception $e) {
			Log::write('[Project Phase User] ' . $e->getMessage());
		}
        unset($cls);
	}
	
	
	private function deleteProjectPhaseUserRights($id) {
		$cls = new ProjectPhaseUserRightsClass($this->db) ;
		try {
			$cls->deleteRecord($id); 
		} catch (Exception $e) {
			Log::write('[Project Phase User Rights] ' . $e->getMessage());
		}
        unset($cls);
	}
	

	
	
	private function getProjectPhaseUser($id) {
		$cls 		= new ProjectPhaseUserClass($this->db) ;
		$clsUser 	= new UserClass($this->db);
		$rows 		= $cls->getProjectPhaseUser($id) ;
		$lines 		= "" ;
		
		if (!is_null($rows) || count($rows) > 0) {
			
			foreach ($rows as $row) {
				$rowUser=$clsUser->getRecord($row[ProjectPhaseUserTable::C_USER])[UserTable::C_NAME];
				if (strlen($lines) > 0)
					$lines .= "|" ;
				
				$lines 	   .= $row[ProjectPhaseUserTable::C_USER] . "~" . $rowUser;
			}
		}
		
		unset($rows) ;
		unset($cls) ;
		return $lines;
	}
	
	private function getProjectPhaseUserRights($id) {
		$cls 	= new ProjectPhaseUserRightsClass($this->db);
		$clsUser = new UserClass($this->db);
		$rows = $cls->getProjectPhaseUserRights($id);
		$lines = "" ;
		if (!is_null($rows) || count($rows) > 0) {
			foreach ($rows as $row) {
				$rowUser=$clsUser->getRecord($row[ProjectPhaseUserRightsTable::C_USER])[UserTable::C_NAME];
				if (strlen($lines) > 0)
					$lines .= "|" ;
                
				$lines .= $row[ProjectPhaseUserRightsTable::C_USER] . "~" . $rowUser ;
			}
		}
		
		unset($rows) ;
		unset($list) ;
		unset($cls) ;
        
		return $lines;
	}
	

/*	private function getUser() {
		$vls = $this->getValueList(UserTable::C_TABLE, UserTable::C_ID, UserTable::C_NAME,array('code'=>'0','desc'=>'--- Select a User ---')) ;
		return Util::createOptionValue($vls) ;
	}*/

	private function getProject() {
		$vls = $this->getValueList(ProjectTable::C_TABLE, ProjectTable::C_ID, ProjectTable::C_TITLE,array('code'=>'0','desc'=>'--- Select a Project ---')) ;
		return Util::createOptionValue($vls) ;
	}
}
?>