<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "admin/UserClass.php");
require_once (PATH_MODELS . "admin/CompanyClass.php");
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/CustomerContactClass.php");
require_once (PATH_MODELS . "activity/LocationClass.php");
require_once (PATH_MODELS . "activity/ProjectClass.php");
require_once (PATH_MODELS . "activity/ActivityStatusClass.php");
require_once (PATH_MODELS . "activity/ActivityHeaderClass.php");
require_once (PATH_MODELS . "activity/ActivityTimingDetailClass.php");


class HeaderApi 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_GET:
					$this->getRecord($params);
					break;
				case Command::ApiGetItemDetail:
					$this->getRecordDetail($params);
					break;
				case Command::ApiGetInputHeader:
					$this->getInputHeader() ;
					break;
				case REQ_DELETE:
					$this->getDeleteRecord($params) ;
					break;
				case REQ_ADD:
					$this->saveRecord($params) ;
					break;
				// case Command::ApiGetCompany:
				// 	$this->getCompanyList() ;
				// 	break;
				// case Command::ApiGetCustomer:
				// 	$this->getCustomerList() ;
				// 	break;
				// case Command::ApiGetProject:
				// 	$this->getProjectList() ;
				// 	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_user'])){
			$this->sendJsonResponse(Status::Error,"Missing User id. Please try again.",0,$this->type);
			return false;
		}
		
		$cls = new ActivityHeaderClass($this->db);
		$rows = $cls->getActivityApi($params['id_user']);


		if(count($rows)==0)
			$this->sendJsonResponse(Status::Error,"No Data.",$rows,$this->type);
		else
			$this->sendJsonResponse(Status::Ok,"Success",$rows,$this->type) ;
	}

	private function getRecordDetail($params=null) {
		if (!isset($params['id_activity'])){
			$this->sendJsonResponse(Status::Error,"Missing Service id. Please try again.",0,$this->type);
			return false;
		}
		

        //Get Time Tracker Data
        $clsTiming   = new ActivityTimingDetailClass($this->db) ;
        $data = array();
        $data['TIME_TRACKER'] = $clsTiming->getTimingListItem($params['id_activity'],'',true);


		if(count($data)==0)
			$this->sendJsonResponse(Status::Error,"No Data.",$data,$this->type);
		else
			$this->sendJsonResponse(Status::Ok,"Success",$data,$this->type) ;
	}

	private function getInputHeader() {
		$clsUser = new UserClass($this->db) ;
		$clsCoy = new CompanyClass($this->db) ;
		$clsPrj = new ProjectClass($this->db) ;
		$clsSts = new ActivityStatusClass($this->db) ;

		$UserRows = $clsUser->getRecordApi();
		$CoyRows = $clsCoy->getRecordApi();
		$PrjRows = $clsPrj->getRecordApi();
		$CusRows = $this->getCustomerRecordApi() ;
		$StsRows = $clsSts->getRecordApi() ;

		$datas = array() ;
		$datas['USER'] = $UserRows;
		$datas['COMPANY'] = $CoyRows;
		$datas['PROJECT'] = $PrjRows;
		$datas['CUSTOMER'] = $CusRows;
		$datas['STATUS'] = $StsRows;

		$this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
		unset($cls) ;
	}


	function getCustomerRecordApi() {
		$cls = new CustomerClass($this->db) ;
        $clsCon = new CustomerContactClass($this->db) ;
        $clsLoc = new LocationClass($this->db) ;
        $rows = $cls->getCustomerList() ;
        $datas = array();

        if (is_null($rows) || count($rows) == 0)
            return null ;
        else 
            foreach ($rows as $row) {
                    $item = array() ;
                    $item[CustomerTable::C_ID] = $row[CustomerTable::C_ID];
                    $item[CustomerTable::C_NAME] = $row[CustomerTable::C_NAME];
                    $item['CONTACT'] = $clsCon->getCustomerContact($row[CustomerTable::C_ID],true);
                    $item['LOCATION'] = $clsLoc->getLocationByCusId($row[CustomerTable::C_ID],true);
                    $datas[]=$item;
                } 
        return $datas;
    }

    private function getDeleteRecord($params) {
		if (isset($params['id_activity'])) {

            $cls      = new ActivityHeaderClass($this->db) ;
            $clsTime  = new ActivityTimingDetailClass($this->db) ;
	        try {

                $this->db->beginTran() ;

                $cls->deleteRecord($params['id_activity']);
                $clsTime->deleteRecord($params['id_activity']);

                $this->db->commitTran() ;
                $this->sendJsonResponse(Status::Ok,"Service successfully deleted from the system.",$params['id_activity'],$this->type);

	        } catch (Exception $e) {
	            $this->db->rollbackTran() ;
	            $this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting System Service from the system.","",$this->type) ;
	        }
	        unset($cls) ;
        } else {
            $this->sendJsonResponse(Status::Error,"You must supply the Service id if you wish to delete. Please try again.","",$this->type);
        }
	}

	private function saveRecord($params) {

	        $paramsHeader  = json_decode($params["header"], true);
	        $paramsTime  = json_decode($params["time_tracker"], true);

	        //print_r($paramsHeader);die();

            $datas          = array() ;
            $orgid          =  $paramsHeader[ActivityHeaderTable::C_ORG_ID];
            $modifyby       =  $paramsHeader[ActivityHeaderTable::C_CREATE_BY];
            $modifydate     = date_create('now')->format('Y-m-d H:i:s') ;
            $ws             =  $paramsHeader[ActivityHeaderTable::C_WS_ID];
            $cls            = new ActivityHeaderClass($this->db) ;
            $mesg           = "Service successfully save to the system.";
            $status         = $paramsHeader[ActivityHeaderTable::C_STATUS] ;
            $date     		= Datetime::createFromFormat('d/m/Y', $paramsHeader[ActivityHeaderTable::C_DATE])->format('Y-m-d H:i:s') ;
            $update 		= false;

            if (isset($paramsHeader[ActivityHeaderTable::C_ID])) {
	        	$update = true;
	        	$id             = $paramsHeader[ActivityHeaderTable::C_ID];
	        	$mesg           = "Service successfully update to the system.";
	        }
       
            try {
                $this->db->beginTran();
            	
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TITLE,$paramsHeader[ActivityHeaderTable::C_TITLE]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DATE,$date) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DESC,$paramsHeader[ActivityHeaderTable::C_DESC]) ;
                //$datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TYPE,$paramsHeader[ActivityHeaderTable::C_TYPE]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_BILL,$paramsHeader[ActivityHeaderTable::C_BILL]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SITE,$paramsHeader[ActivityHeaderTable::C_SITE]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_JOB_ID,$paramsHeader[ActivityHeaderTable::C_JOB_ID]);
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_PROJECT_STATUS,$paramsHeader[ActivityHeaderTable::C_PROJECT_STATUS]);
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_STATUS,$paramsHeader[ActivityHeaderTable::C_STATUS]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CODE,$paramsHeader[ActivityHeaderTable::C_CODE]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_USER_ID,$paramsHeader[ActivityHeaderTable::C_USER_ID]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DEDUCT,$paramsHeader[ActivityHeaderTable::C_DEDUCT]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_PROJECT_ID,$paramsHeader[ActivityHeaderTable::C_PROJECT_ID]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CONTACT_ID,$paramsHeader[ActivityHeaderTable::C_CONTACT_ID]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CUSTOMER_ID,$paramsHeader[ActivityHeaderTable::C_CUSTOMER_ID]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_LOCATION_ID,$paramsHeader[ActivityHeaderTable::C_LOCATION_ID]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TT_TOTAL,$paramsHeader[ActivityHeaderTable::C_TT_TOTAL]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TT_TOTAL_OVERRIDE,$paramsHeader[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED,$paramsHeader[ActivityHeaderTable::C_SIGNED]) ;
                //$datas[] = $this->db->fieldValue(ActivityHeaderTable::C_ET_TOTAL,$paramsHeader[ActivityHeaderTable::C_ET_TOTAL]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_COY_ID,$paramsHeader[ActivityHeaderTable::C_COY_ID]) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_ORG_ID,$orgid) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_WS_ID,$ws) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_MODIFY_DATE,$modifydate) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CREATE_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CREATE_DATE,$modifydate) ; 


                if ($update) {
                	$cls->updateRecord($id, $datas);
                	$this->deleteItemTimeTracker($id);
                	$this->addItemTimeTracker($id,$paramsTime) ;
                } else {
                	$id = $cls->addRecord($datas) ;
                	$this->addItemTimeTracker($id , $paramsTime) ;
                }

               $this->db->commitTran() ;

                // if ($status==ActStatus::Confirm){
                    
                //     //create PDF File
                //     $params = array();
                //     $params['type'] = Command::PortalActivityPrintPreview;
                //     $params['id'] = $id;
                //     $params['outputType'] = 'save';
                //     $portalAct = new PortalActivity();
                //     $portalAct->processRequest($params);
                //     //send to customer
                //      if(!$this->executeSendEmailActConfirm($id)){
                //         $mesg .= " Error in sending mail.";
                //     }
                // }

                $this->sendJsonResponse(Status::Ok,$mesg,$id,$this->type) ;
            } catch (Exception $e) {
                $this->db->rollbackTran() ; 
                Log::write('[Service Header API] ' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating Service to the system.","",$this->type) ;
            }
    }


    private function deleteItemTimeTracker($id) {
        $clsTime  = new ActivityTimingDetailClass($this->db) ;
        try {
            $clsTime->deleteRecord($id);
        } catch (Exception $e) {
            Log::write('[TimeTracker Api] ' . $e->getMessage());
        }
        unset($clsTime);
    }



    private function addItemTimeTracker($ActId, $lists) {
        $cls        = new ActivityTimingDetailClass($this->db);
        $line 		= 1000;

        if ($lists) {

	        foreach ($lists as $list) {
	        	$datas = array() ;
	                
	                $date= Datetime::createFromFormat('d/m/Y', $list[ActivityTimingDetailTable::C_DATE])->format('Y-m-d h:i:s'); 
	                $end_date= Datetime::createFromFormat('d/m/Y', $list[ActivityTimingDetailTable::C_END_DATE])->format('Y-m-d h:i:s'); 

	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_ID ,$ActId);
	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_LINE ,$line) ;
	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_DESC ,$list[ActivityTimingDetailTable::C_DESC]);
	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_START ,$list[ActivityTimingDetailTable::C_START]) ;
	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_END ,$list[ActivityTimingDetailTable::C_END]);
	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_TIME ,$list[ActivityTimingDetailTable::C_TOTAL_TIME]);
	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_BREAK ,$list[ActivityTimingDetailTable::C_BREAK]);
	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_AFT_BREAK ,$list[ActivityTimingDetailTable::C_TOTAL_AFT_BREAK]);
	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_PHASE ,$list[ActivityTimingDetailTable::C_PHASE]);
	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_DATE ,$date);
	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_END_DATE ,$end_date);
	                $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_OVERRIDE ,$list[ActivityTimingDetailTable::C_TOTAL_OVERRIDE]);

	                $cls->addRecord($datas) ;
	                $line +=1;
	        }

    	}

        unset($cls);
    }

}

?>