<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/ActivityHeaderClass.php");
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/CustomerContactClass.php");
require_once (PATH_MODELS . "activity/ProjectClass.php");
require_once (PATH_MODELS . "activity/ProjectMandaysBillClass.php");
require_once (PATH_MODELS . "activity/ActivityHeaderClass.php");
require_once (PATH_MODELS . "activity/ActivityTimingDetailClass.php");
require_once (PATH_MODELS . "hr/DepartmentClass.php");
require_once (PATH_MODELS . "admin/CompanyClass.php");
require_once (PATH_MODELS . "admin/UserClass.php");
require_once (PATH_MODELS . "admin/UserGroupClass.php") ;
require_once (PATH_MODELS . "admin/UserRight.php") ;
require_once (PATH_MODELS . "general/ContactInfoClass.php") ;
require_once (PATH_LIB    . 'ImageResize.php');


class PortalProject extends ActivityBase {

	function __construct() {
		$this->db 		= $_SESSION[SE_DB] ;
        $this->dbsun    = $_SESSION[SE_DB_SUN];
		$this->fldorg 	= CustomerTable::C_ORG_ID ;
		$this->orgid 	= $_SESSION[SE_ORGID] ;
	}
	
	function __destruct() {
		unset($this->db) ;
	}
	
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
            $this->dbsun->open() ;
			$this->loadSetting() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			switch ($this->type) {
                case Command::PortalProject:
                    $this->processProjectInfo() ;
                    break ;
                case Command::PortalProjectFilter:
                    $this->processProjectFilter($params);
                    break;
                case Command::PortalProjectAddView:
                    $this->processViewProjectAdd();
                    break;
                case REQ_ADD:
                    $this->addRecord($params) ;
                    break ;
                case Command::PortalProjectUpdateView:
                    $this->processProjectUpdateView($params);
                    break;
                case REQ_UPDATE:
                    $this->updateRecord($params) ;
                    break ;
                case Command::PortalProjectDelete:
                    $this->processProjectDelete($params);
                    break;
                case Command::PortalActivitySelectCustomer:
                    $this->processActivitySelectCustomer($params);
                    break;
                case Command::PortalActivitySelectDeduct:
                    $this->processActivitySelectDeduct($params);
                    break;
                case Command::PortalProjectReportUtilization:
                    $this->processProjectReportUtilization($params);
                    break;
                case Command::PortalProjectReportUtilizationPrint:
                    $this->processProjectReportUtilizationPrintPreview($params);
                    break;
                //========================================
				default:
					$this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
					break ;
			}
			$this->db->close() ;
            $this->dbsun->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			$this->dbsun->close() ;
			die ($e->getMessage()) ;
		}
	}

    private function getCustomerOption($mandatory = true){
        $customerCls    = new CustomerClass($this->db);
        
        $rows           = $customerCls->getTable();
        
		$vls 			= array() ;
		
		if(is_null($rows) || count($rows) == 0)
			return null;
		
        if(!$mandatory){
			$vls[] 		= array ('code'=>0,'desc'=>'-- Select Customer -- ') ;
        }
        
		foreach ($rows as $row) {
			$vls[] 		= array ('code'=>$row[CustomerTable::C_ID],'desc'=>$row[CustomerTable::C_NAME] . " - " . $row[CustomerTable::C_CODE]) ;
		}
		return Util::createOptionValue($vls, "") ;
    }

    private function processProjectInfo() {
        ob_start() ;
 
        include (PATH_VIEWS . "portal/ProjectInfoView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']  =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "My Project" ;
        $this->sendJsonResponse(Status::Ok,"Load Home Info",$dataReturn,$this->type);
    }


    private function processProjectFilter($params) {
        $projectCls         = new ProjectClass($this->db);
        $projectMandaysCls  = new ProjectMandaysBillClass($this->db);
        $customerCls        = new CustomerClass($this->db);
        $activityCls        = new ActivityHeaderClass($this->db);
        $rows               = $projectCls->getProjectList($params['title'], $params['cust'], $params['status']);
        
        $htmlStr = "";
        if(is_null($rows) || count($rows) == 0){
            
        } else {
            $itemLen = count($rows);

            $htmlStr .= "<thead>" .
                        "<tr>" .
                            "<th width='10%'>Job No.</th>" .
                            "<th width='25%'>Name</th>" .
                            "<th width='20%'>Customer</th>" .
                            "<th width='10%'>Status</th>" .
                            "<th width='25%'>Bill</th>" .
                            "<th width='10%'>&nbsp</th>" .
                        "</tr>" .
                    "</thead> <tbody> <tr></tr>";

            for($i = 0; $i < $itemLen; $i++) {
                $reqInfo = $rows[$i];
                
                $rowsTotal = $projectMandaysCls->getTotalBillPaid($reqInfo[ProjectTable::C_ID]);
                
                $totalMandaysActivity       = $activityCls->getTotalMandaysActivityByProject($reqInfo[ProjectTable::C_ID]);
                
                $btnStatusStr = "Invoices : " . number_format($rowsTotal[0]['NO_INVOICE']) . ", Total Billed : " . number_format($rowsTotal[0]['BILLED'], 2, ".", "") . ", Total Paid : " . number_format($rowsTotal[0]['PAID'], 2, ".", "") . " , Total Mandays : " . number_format($totalMandaysActivity, 2, ".", "");
                
                $rowCust = $customerCls->getRecord($reqInfo[ProjectTable::C_CUSTOMER_ID]);
                
                $btnStr  = "<button  title=\"View\" onclick=\"return showEditProject(". $reqInfo[ProjectTable::C_ID] .", this);\" id=\"btnEdit\" data-toggle=\"modal\" class=\"btn btn-primary glyphicon glyphicon-edit btn-sm\"></button>"; 
                $btnStr  .= "<button title=\"Delete\" onclick=\"javascript: popupDeleteProject(" . $reqInfo[ProjectTable::C_ID] .", this);\" id=\"btnDelete\" data-toggle=\"modal\" class=\"btn btn-danger glyphicon glyphicon-trash btn-sm\"></button>";
                $btnStr  .= "<button title=\"Print Preview\" onclick=\"return showProjectReportUtilization(". $reqInfo[ProjectTable::C_ID] .");\" id=\"btnPrintPreview\" class=\"btn btn-default glyphicon glyphicon-print btn-sm\"></button>";

            
                $styleColor = "";
                if($totalMandaysActivity > $rowsTotal[0]['PAID']){
                    $styleColor = "style='background-color:#F09C9C'";
                } else if($totalMandaysActivity > ($rowsTotal[0]['PAID'] * 0.80)){
                    $styleColor = "style='background-color:#ECC46C'";
                } else if($totalMandaysActivity > ($rowsTotal[0]['PAID'] * 0.60)){
                    $styleColor = "style='background-color:#F9E974'";
                }
                
                $htmlStr .= "<tr " . $styleColor . " id=\"project-rows-" . $reqInfo[ProjectTable::C_ID] . "\">" .
                                "<td style='display:none'>" . $reqInfo[ProjectTable::C_ID] . "</td>" . 
                                "<td>" . $reqInfo[ProjectTable::C_CODE] . "</td>" .
                                "<td>" . $reqInfo[ProjectTable::C_TITLE] . "</td>" .
                                "<td>" . $rowCust[CustomerTable::C_NAME] . " (" . $rowCust[CustomerTable::C_CODE] . ")" . "</td>" .
                                "<td>" . ($reqInfo[ProjectTable::C_STATUS] == 1 ? 'Active (' . number_format($reqInfo[ProjectTable::C_TOTAL_MANDAYS], 2) . ' manday(s))' : 'Non-active') . "</td>" . 
                                "<td>" . $btnStatusStr . "</td>" . 
                                "<td><div>" . $btnStr . "</div></td>".
                            "</tr>";
            }
            $htmlStr .="</tbody>";
        }
		
        
        $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
        
    }


    private function processViewProjectAdd() {
        ob_start() ;

        $userCls= new UserClass($this->db);
        
        include (PATH_VIEWS . "portal/ProjectAddView.php") ;
        $addHeaderContent= array() ;
        $addHeaderContent["all"] =  Util::minifyHtml(ob_get_clean()) ;
        
        $this->sendJsonResponse(Status::Ok,"Project Add Content",$addHeaderContent,$this->type);
        unset($cls);
    }

    private function addRecord($params) {
		$cls        = new ProjectClass($this->db) ;
        $projectMandaysCls  = new ProjectMandaysBillClass($this->db);
		$custCls    = new CustomerClass($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(ProjectTable::C_TITLE,$this->getParam($params,'title',"")) ;
		$datas[] = $this->db->fieldValue(ProjectTable::C_CODE,$this->getParam($params,'code',"")) ;
		$datas[] = $this->db->fieldValue(ProjectTable::C_DESC,$this->getParam($params,'desc',"")) ;
		$datas[] = $this->db->fieldValue(ProjectTable::C_TOTAL_MANDAYS,floatval($this->getParam($params,'total_mandays',"0.00"))) ;
		$datas[] = $this->db->fieldValue(ProjectTable::C_CUSTOMER_ID,$this->getParamInt($params,'cust',0)) ;
		$datas[] = $this->db->fieldValue(ProjectTable::C_STATUS,$this->getParamInt($params,'active',1)) ;
		$datas[] = $this->db->fieldValue(ProjectTable::C_ORG_ID,$orgid) ;
		$datas[] = $this->db->fieldValue(ProjectTable::C_WS_ID,$ws) ;
		$datas[] = $this->db->fieldValue(ProjectTable::C_MODIFY_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(ProjectTable::C_CREATE_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(ProjectTable::C_MODIFY_DATE,$modifydate) ;
		$datas[] = $this->db->fieldValue(ProjectTable::C_CREATE_DATE,$modifydate) ;

		$projectInvoice = $this->getParam($params,'invoice',"") ;
       		
		try {
			$id = $cls->addRecord($datas) ;
			if ($id > 0) {
				$this->addProjectInvoices($id,$projectInvoice) ;
                
                $datas = array();
                
                $rowProject = $cls->getRecord($id);
                $rowCust    = $custCls->getRecord($rowProject[ProjectTable::C_CUSTOMER_ID]);
                
                $rowsTotal = $projectMandaysCls->getTotalBillPaid($rowProject[ProjectTable::C_ID]);
                $btnStatusStr = "Invoices : " . number_format($rowsTotal[0]['NO_INVOICE']) . ", Total Billed : " . number_format($rowsTotal[0]['BILLED'], 2, ".", "") . ", Total Paid : " . number_format($rowsTotal[0]['PAID'], 2, ".", "") . " ";
                
                $datas['id'] = $id;
                $datas['code'] = $rowProject[ProjectTable::C_CODE];
                $datas['title'] = $rowProject[ProjectTable::C_TITLE];
                $datas['cust'] = $rowCust[CustomerTable::C_NAME] . " (" . $rowCust[CustomerTable::C_CODE] . ")";
                $datas['status'] = ($rowProject[ProjectTable::C_STATUS] == 1 ? 'Active (' . number_format($rowProject[ProjectTable::C_TOTAL_MANDAYS], 2) . ' manday(s))' : 'Non-active');
                $datas['bill'] = $btnStatusStr;
                
				$this->sendJsonResponse(Status::Ok,"Project successfully added to the system.",$datas,$this->type);
			} else {
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding new project to the system.",$id, $this->type) ;
			}
		} catch (Exception $e) {
			Log::write('[Customer]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
    }
    
    

	private function addProjectInvoices($id, $projectInvoices) {
		$cls = new ProjectMandaysBillClass($this->db) ;
		if ($projectInvoices != "") {
			$lines = explode("|",$projectInvoices) ;
			for ($i= 0;$i < count($lines) ;$i++) {
				$line = explode("~",$lines[$i]) ;
				if (count($line) == 3) {
                    $datas = array() ;
                    $datas[] = $this->db->fieldValue(ProjectMandaysBillTable::C_ID,$id);
                    $datas[] = $this->db->fieldValue(ProjectMandaysBillTable::C_INVOICE_NO,$line[0]) ;
                    $datas[] = $this->db->fieldValue(ProjectMandaysBillTable::C_INVOICE_BILLED,floatval($line[1])) ;
                    $datas[] = $this->db->fieldValue(ProjectMandaysBillTable::C_INVOICE_PAID,floatval($line[2])) ;
                    $cls->addRecord($datas) ;
				}
			}
		}
		unset($cls) ;
	}

	private function getProjectInvoices($id) {
		$cls = new ProjectMandaysBillClass($this->db) ;
		$rows = $cls->getMandaysBill($id) ;
		$lines = "" ;
		if (!is_null($rows) || count($rows) > 0) {
			foreach ($rows as $row) {
                
                if (strlen($lines) > 0){
					$lines .= "|" ;
                }
				$lines .= $row[ProjectMandaysBillTable::C_INVOICE_NO] . "~" . 
                    number_format($row[ProjectMandaysBillTable::C_INVOICE_BILLED], 2, ".", '') . "~" . 
                    number_format($row[ProjectMandaysBillTable::C_INVOICE_PAID], 2, ".", '');
			}							
        }
		unset($cls) ;
		return $lines ;
	}

    private function processProjectUpdateView($params) {
        ob_start() ;
        $id= $params['id'];
        $cls                = new ProjectClass($this->db) ;
        $row                = $cls->getRecord($id);
        $datas = array();
        
        include (PATH_VIEWS . "portal/ProjectAddView.php") ;
        
        $editHeaderContent = array();
        $editHeaderContent["all"]       =  Util::minifyHtml(ob_get_clean()) ;

        $datas['id']                    = $row[ProjectTable::C_ID];
        $datas['code']                  = $row[ProjectTable::C_CODE];
        $datas['title']                 = $row[ProjectTable::C_TITLE];
        $datas['desc']                  = $row[ProjectTable::C_DESC];
        $datas['cust']                  = $row[ProjectTable::C_CUSTOMER_ID];
        $datas['total_mandays']         = number_format($row[ProjectTable::C_TOTAL_MANDAYS], 2, ".", '');
        $datas['status']                = $row[ProjectTable::C_STATUS];

        $datas['project_invoices']      = $this->getProjectInvoices($id);
       
        $editHeaderContent["headerData"] =  $datas ;
        
        $this->sendJsonResponse(Status::Ok,"Project Edit Content",$editHeaderContent,$this->type);
        unset($cls);
        unset($row);
    }


    private function updateRecord($params) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new ProjectClass($this->db);
            $projectMandaysCls  = new ProjectMandaysBillClass($this->db);
            $custCls    = new CustomerClass($this->db) ;
			try {
				$datas = array() ;
                
                $modifyby 	= $_SESSION[SE_USERID] ;
                $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
                $ws = $_SESSION[SE_REMOTE_IP] ;
		
                $datas[] = $this->db->fieldValue(ProjectTable::C_TITLE,$this->getParam($params,'title',"")) ;
                $datas[] = $this->db->fieldValue(ProjectTable::C_CODE,$this->getParam($params,'code',"")) ;
                $datas[] = $this->db->fieldValue(ProjectTable::C_DESC,$this->getParam($params,'desc',"")) ;
                $datas[] = $this->db->fieldValue(ProjectTable::C_TOTAL_MANDAYS,floatval($this->getParam($params,'total_mandays',"0.00"))) ;
                $datas[] = $this->db->fieldValue(ProjectTable::C_CUSTOMER_ID,$this->getParamInt($params,'cust',0)) ;
                $datas[] = $this->db->fieldValue(ProjectTable::C_STATUS,$this->getParamInt($params,'active',1)) ;
                $datas[] = $this->db->fieldValue(CustomerTable::C_WS_ID,$ws) ;
                $datas[] = $this->db->fieldValue(CustomerTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(CustomerTable::C_MODIFY_DATE,$modifydate) ;
                
                $projectInvoice = $this->getParam($params,'invoice',"") ;
                $projectMandaysCls->deleteRecord($id);
				$this->addProjectInvoices($id,$projectInvoice) ;
                
				$cls->updateRecord($id,$datas) ;
                
                $datas = array();
                
                $rowProject = $cls->getRecord($id);
                $rowCust    = $custCls->getRecord($rowProject[ProjectTable::C_CUSTOMER_ID]);
                
                $rowsTotal = $projectMandaysCls->getTotalBillPaid($rowProject[ProjectTable::C_ID]);
                $btnStatusStr = "Invoices : " . number_format($rowsTotal[0]['NO_INVOICE']) . ", Total Billed : " . number_format($rowsTotal[0]['BILLED'], 2, ".", "") . ", Total Paid : " . number_format($rowsTotal[0]['PAID'], 2, ".", "") . " ";
                
                $datas['id'] = $id;
                $datas['code'] = $rowProject[ProjectTable::C_CODE];
                $datas['title'] = $rowProject[ProjectTable::C_TITLE];
                $datas['cust'] = $rowCust[CustomerTable::C_NAME] . " (" . $rowCust[CustomerTable::C_CODE] . ")";
                $datas['status'] = ($rowProject[ProjectTable::C_STATUS] == 1 ? 'Active (' . number_format($rowProject[ProjectTable::C_TOTAL_MANDAYS], 2) . ' manday(s))' : 'Non-active');
                $datas['bill'] = $btnStatusStr;
              
				$this->sendJsonResponse(Status::Ok,"Project detail successfully updated to the system.",$datas,$this->type) ;
			} catch (Exception $e) {
				Log::write('[Project]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating project detail to the system.","",$this->type) ;
			}
			unset($cls) ;
			unset($clsContact) ;
		}else {
			$this->sendJsonResponse(Status::Error,"You must supply the project id you wish to update. Please try again.","",$this->type);
		}
    }



    private function processProjectDelete($params) {
        if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new ProjectClass($this->db) ;
			$clsMandays = new ProjectMandaysBillClass($this->db);
			try {
				$cls->deleteRecord($id) ; 
               	$clsMandays->deleteRecord($id);
				$this->sendJsonResponse(Status::Ok,"Project successfully deleted from the system.",$id,$this->type);
			} catch (Exception $e) {
				Log::write('[Project]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting Project record from the system.","",$this->type) ;
			}
			unset($cls) ;
			unset($clsMandays) ;
        } else {
            $this->sendJsonResponse(Status::Error,"You must supply the Project id if you wish to delete. Please try again.","",$this->type);
        }
    }

 private function convertNumeric($val){
    return str_replace(',', '', number_format($val,2));
 }
//`ACTIVITY
  
    private function getReportProjectUtilizationMandaysTable($projectId){
        $projectMandaysCls  = new ProjectMandaysBillClass($this->db);
        $activityCls        = new ActivityHeaderClass($this->db);
        $rowsProjectMandays = $projectMandaysCls->getMandaysBill($projectId);
                
        $totalMandaysActivity       = $activityCls->getTotalMandaysActivityByProject($projectId);
        
        $tblProjectMandays = "<table class='table table-striped'>";
        
        $totalBilled = 0;
        $totalPaid = 0;
        
        if(!is_null($rowsProjectMandays) && count($rowsProjectMandays) > 0){
            $tblProjectMandays .= "<thead><tr><th>Invoice No</th><th style='text-align:right'>Billed</th><th style='text-align:right'>Paid</th></tr></thead><tbody>";
            foreach($rowsProjectMandays as $rowProjectMandays){
                $tblProjectMandays .= "<tr><td>" . $rowProjectMandays[ProjectMandaysBillTable::C_INVOICE_NO] . "</td>" . 
                                            "<td style='text-align:right'>" . number_format($rowProjectMandays[ProjectMandaysBillTable::C_INVOICE_BILLED], 2) . "</td>" . 
                                            "<td style='text-align:right'>" . number_format($rowProjectMandays[ProjectMandaysBillTable::C_INVOICE_PAID], 2) . "</td></tr>";
                $totalBilled += $rowProjectMandays[ProjectMandaysBillTable::C_INVOICE_BILLED];
                $totalPaid += $rowProjectMandays[ProjectMandaysBillTable::C_INVOICE_PAID];
            }
            
            $tblProjectMandays .= "<tr><td style='text-align:right'><h4>Total</h4></td>" . 
                                        "<td style='text-align:right'><h4>" . number_format($totalBilled, 2) . "</h4></td>" . 
                                        "<td style='text-align:right'><h4>" . number_format($totalPaid, 2) . "</h4></td></tr>";
            $tblProjectMandays .= "<tr><td style='text-align:right'></td>" . 
                                        "<td style='text-align:right'>Days not paid</td>" . 
                                        "<td style='text-align:right'>" . number_format($totalBilled - $totalPaid, 2) . "</td></tr>";
            $tblProjectMandays .= "<tr><td style='text-align:right'></td>" . 
                                        "<td style='text-align:right'>Days used but not paid</td>" . 
                                        "<td style='text-align:right'>" . number_format($totalMandaysActivity - $totalPaid, 2) . "</td></tr>";
            $tblProjectMandays .= "</tbody>";
        } else {
            $tblProjectMandays .= "<h4>NO RECORD.</h4>";
        }
        
        $tblProjectMandays .= "</table>";
        
        $datas = array();
        $datas['html'] = $tblProjectMandays;
        $datas['totalBilled'] = $totalBilled;
        $datas['totalPaid'] = $totalPaid;
        
        return $datas;
    }
    
    private function getReportProjectUtilizationActivityTable($projectId, $totalPaid){
        $activityCls        = new ActivityHeaderClass($this->db);
        $userCls            = new UserClass($this->db);
        $activityTimingCls  = new ActivityTimingDetailClass($this->db);
        $projectCls         = new ProjectClass($this->db);
        $rowsActivity       = $activityCls->getActivityByProject($projectId);
        $rowProject         = $projectCls->getRecord($projectId);
        
        $tblProjectActivity = "<table class='table table-bordered'>";
        
        $totalActual = 0;
        $totalBilled = 0;
        
        if(!is_null($rowsActivity) && count($rowsActivity) > 0){
            $tblProjectActivity .= "<thead><tr><th>No</th>" . 
                                                "<th>Phase</th>" . 
                                                "<th>Ref. No</th>" . 
                                                "<th>Description</th><th>Dates</th><th style='text-align:right'>Actual Days</th><th style='text-align:right'>Billing Days</th><th>Consultant</th><th>Signed</th></tr></thead><tbody>";
            $counter = 1;
            foreach($rowsActivity as $rowActivity){
                
                $rowsActivityTiming = $activityTimingCls->getTimingListItem($rowActivity[ActivityHeaderTable::C_ID]);
                $firstTiming = true;
                $totalOverride = ($rowActivity[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE] != 0.00 ? $rowActivity[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE] : $rowActivity[ActivityHeaderTable::C_TT_TOTAL]) / 8;
                if(!is_null($rowsActivityTiming) && count($rowsActivityTiming) > 0){
                    $totalTiming = count($rowsActivityTiming);
                    foreach($rowsActivityTiming as $rowActivityTiming){
                        $date = (new DateTime($rowActivityTiming[ActivityTimingDetailTable::C_DATE]))->format('d/m/y');
                        if((new DateTime($rowActivityTiming[ActivityTimingDetailTable::C_DATE]))->format('d/m/y') != (new DateTime($rowActivityTiming[ActivityTimingDetailTable::C_END_DATE]))->format('d/m/y')){
                            $date .= " - " . (new DateTime($rowActivityTiming[ActivityTimingDetailTable::C_END_DATE]))->format('d/m/y');
                        }
                        
                        $tblProjectActivity .= "<tr><td>" . $counter . "</td>" . 
                                                "<td>" . $rowActivityTiming[ActivityTimingDetailTable::C_PHASE] . "</td>" . 
                                                "<td>" . $rowActivity[ActivityHeaderTable::C_REF] . "</td>" . 
                                                "<td>" . $rowActivityTiming[ActivityTimingDetailTable::C_DESC] . "</td>" . 
                                                "<td>" . $date . "</td>" . 
                                                "<td style='text-align:right'>" . number_format($rowActivityTiming[ActivityTimingDetailTable::C_TOTAL_AFT_BREAK] / 8, 2) . "</td>" . 
                                                ($firstTiming ? "<td rowspan='" . $totalTiming . "' style='text-align:right'>" . number_format($totalOverride, 2) . "</td>" : "" ) . 
                                                ($firstTiming ? "<td rowspan='" . $totalTiming . "'>" . $userCls->getRecord($rowActivity[ActivityHeaderTable::C_USER_ID])[UserTable::C_NAME] . "</td>" : "") . 
                                                ($firstTiming ? "<td rowspan='" . $totalTiming . "'>" . ($rowActivity[ActivityHeaderTable::C_SIGNED] == 0 ? "NO" : "YES") . "</td>" : "" ) . "</tr>";
                        $firstTiming = false;
                        $counter += 1;
                    }
                    
                }
                $totalBilled += $totalOverride;
                $totalActual += $rowActivity[ActivityHeaderTable::C_TT_TOTAL] / 8;
            }
            
            $styleColor = "";
            if($totalBilled > $totalPaid){
                $styleColor = "style='background-color:#F02C2C'";
            } else if($totalBilled > ($totalPaid * 0.80)){
                $styleColor = "style='background-color:#EC942C'";
            } else if($totalBilled > ($totalPaid * 0.60)){
                $styleColor = "style='background-color:#F9E154'";
            }
            
            $tblProjectActivity .= "<tr " . $styleColor . "><td style='text-align:right' colspan='5'><h4>Total</h4></td>" . 
                                        "<td style='text-align:right'><h4>" . number_format($totalActual, 2) . "</h4></td>" . 
                                        "<td style='text-align:right'><h4>" . number_format($totalBilled, 2) . "</h4></td>" . 
                                        "<td colspan='2'></td></tr>";
            $tblProjectActivity .= "<tr><td style='text-align:right' colspan='5'><h4>Balance Day</h4></td>" . 
                                        "<td style='text-align:right'></td>" . 
                                        "<td style='text-align:right'><h4>" . number_format($rowProject[ProjectTable::C_TOTAL_MANDAYS] - $totalBilled, 2) . "</h4></td>" . 
                                        "<td colspan='2'></td></tr>";
            $tblProjectActivity .= "</tbody>";
        } else {
            $tblProjectActivity .= "<h4>NO RECORD.</h4>";
        }
        
        $tblProjectActivity .= "</table>";
        
        return $tblProjectActivity;
    }
    private function processProjectReportUtilization($params){
        $projectId          = $params['id'];
        $cls                = new ProjectClass($this->db) ;
        $customerCls        = new CustomerClass($this->db);
        
        $row                = $cls->getRecord($projectId);
        $rowCust            = $customerCls->getRecord($row[ProjectTable::C_CUSTOMER_ID]);
        
        $dataMandays  = $this->getReportProjectUtilizationMandaysTable($projectId);
        $tblProjectActivity = $this->getReportProjectUtilizationActivityTable($projectId, $dataMandays['totalPaid']);
        
        $tblProjectMandays = $dataMandays['html'];
        
        ob_start();
        include (PATH_VIEWS . "portal/ProjectReportUtilizationView.php") ;
        
        $datas = array();
        $datas["all"]       =  Util::minifyHtml(ob_get_clean()) ;
        $datas["id"]        =  $projectId;
        
        $this->sendJsonResponse(Status::Ok,"Project Report Utilization",$datas,$this->type);
        unset($cls);
    }

    public function processProjectReportUtilizationPrintPreview($params){
        
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdfN.php');

        // create new PDF document
        $pdf = new RequestPdf('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->setPrintHeader(false);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        // set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 10, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        // set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        // set some language-dependent strings (optional)
        if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
            require_once(dirname(__FILE__).'/lang/eng.php');
            $pdf->setLanguageArray($l);
        }

        // ---------------------------------------------------------

        // set font
        //$pdf->SetFont('calibri', '', 10);

        // add a page
        $pdf->AddPage();

        // set cell padding
        $pdf->setCellPaddings(1, 1, 1, 1);

        // set cell margins
        //$pdf->setCellMargins(1, 1, 1, 1);

        // set color for background
        $pdf->SetFillColor(255, 255, 255);

        $id = $params['id'];
        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }
        
        
        $projectId          = $params['id'];
        $cls                = new ProjectClass($this->db) ;
        $customerCls        = new CustomerClass($this->db);

        $row                = $cls->getRecord($projectId);
        $rowCust            = $customerCls->getRecord($row[ProjectTable::C_CUSTOMER_ID]);


        $projectMandaysCls  = new ProjectMandaysBillClass($this->db);
        $activityCls        = new ActivityHeaderClass($this->db);
        $rowsProjectMandays = $projectMandaysCls->getMandaysBill($projectId);       
        $totalMandaysActivity = $activityCls->getTotalMandaysActivityByProject($projectId);

        $totalBilled = 0;
        $totalPaid = 0;

    
       
        $pdf->SetFont('calibri', 'b', 13);
        $pdf->MultiCell(80, 5, $rowCust[CustomerTable::C_NAME], 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);
        $pdf->MultiCell(80, 5, $row[ProjectTable::C_TITLE] . " (" . $row[ProjectTable::C_CODE] . ")", 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(80, 5, "Generated on ".date_create('now')->format('d/m/Y'), 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);

    


        $columnSize = array(50, 20, 20);
        $pdf->SetFont('calibri', '', 10);
        $bottomHeight = $pdf->getPageHeight() - 30;
        $rowHeight = 3.409722;
        $count = 0;

        //Detail
            if(!is_null($rowsProjectMandays) && count($rowsProjectMandays) > 0){
            $first = true;
            //Header
            $pdf = $this->createHeaderMandays($pdf);
            $pdf->SetFont('calibri', '', 10);

            
            $page = 1;
            foreach($rowsProjectMandays as $rowProjectMandays){
                
    
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }
                
                $count ++;
                
                //$border = "LR";
                $border = "";

                $totalBilled += $rowProjectMandays[ProjectMandaysBillTable::C_INVOICE_BILLED];
                $totalPaid += $rowProjectMandays[ProjectMandaysBillTable::C_INVOICE_PAID];

                $pdf = $this->processStringLine($pdf, $columnSize, $rowHeight, $bottomHeight,
                                                    $rowProjectMandays[ProjectMandaysBillTable::C_INVOICE_NO],number_format($rowProjectMandays[ProjectMandaysBillTable::C_INVOICE_BILLED], 2),number_format($rowProjectMandays[ProjectMandaysBillTable::C_INVOICE_PAID], 2));
                

                
                $first = false;
                
            }
           // $pdf->MultiCell(65, 1, '', 'T', '', 1, 1, PDF_MARGIN_LEFT+110, '', true);
            $margin = $pdf->getPageWidth()-110;

            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize[0], 5, "Total ", 'T', 'R', 1, 0, $margin, '', true);
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell($columnSize[2], 4, number_format($totalBilled, 2), 'T', 'C', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize[2], 4, number_format($totalPaid, 2), 'T', 'C', 1, 1, '', '', true);


            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize[0]+$columnSize[1], 5, "Days not paid ", 0, 'R', 1, 0, $margin, '', true);
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell($columnSize[2], 4, number_format($totalBilled - $totalPaid, 2), 0, 'C', 1, 1, '', '', true);


            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize[0]+$columnSize[1], 5, "Days used but not paid ", 0, 'R', 1, 0, $margin, '', true);
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell($columnSize[2], 4, number_format($totalMandaysActivity - $totalPaid, 2), 0, 'C', 1, 1, '', '', true);
        }

        //$pdf->Ln(10);

        $userCls            = new UserClass($this->db);
        $activityTimingCls  = new ActivityTimingDetailClass($this->db);
        $projectCls         = new ProjectClass($this->db);
        $rowsActivity       = $activityCls->getActivityByProject($projectId);
        $rowProject         = $projectCls->getRecord($projectId);

        $totalActual = 0;
        $totalBilled = 0;


        $columnSize2 = array(10,30,30,75,40,15, 15,30,15);
        $pdf->SetFont('calibri', '', 10);
        $count = 0;
        $counter = 1;

            if(!is_null($rowsActivity) && count($rowsActivity) > 0){
            $first = true;
            //Header Utilzation
            $pdf = $this->createHeaderUtilzation($pdf);
            $pdf->SetFont('calibri', '', 10);
            
            $page = 1;
            foreach($rowsActivity as $rowActivity){
                
    
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }
                
                $count ++;
                
                //$border = "LR";
                $border = "";


                $rowsActivityTiming = $activityTimingCls->getTimingListItem($rowActivity[ActivityHeaderTable::C_ID]);
                $firstTiming = true;
                $totalOverride = ($rowActivity[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE] != 0.00 ? $rowActivity[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE] : $rowActivity[ActivityHeaderTable::C_TT_TOTAL]) / 8;
                if(!is_null($rowsActivityTiming) && count($rowsActivityTiming) > 0){
                    $totalTiming = count($rowsActivityTiming);

                    foreach($rowsActivityTiming as $rowActivityTiming){
                        $date = (new DateTime($rowActivityTiming[ActivityTimingDetailTable::C_DATE]))->format('d/m/y');
                        if((new DateTime($rowActivityTiming[ActivityTimingDetailTable::C_DATE]))->format('d/m/y') != (new DateTime($rowActivityTiming[ActivityTimingDetailTable::C_END_DATE]))->format('d/m/y')){
                            $date .= " - " . (new DateTime($rowActivityTiming[ActivityTimingDetailTable::C_END_DATE]))->format('d/m/y');
                        }

                        $siged = ($rowActivity[ActivityHeaderTable::C_SIGNED] == 0 ? "NO" : "YES");

                        $pdf = $this->processStringLineUtilzation($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $counter,$rowActivityTiming[ActivityTimingDetailTable::C_PHASE],$rowActivity[ActivityHeaderTable::C_REF],$rowActivityTiming[ActivityTimingDetailTable::C_DESC],$date,number_format($rowActivityTiming[ActivityTimingDetailTable::C_TOTAL_AFT_BREAK] / 8, 2),number_format($totalOverride, 2),$userCls->getRecord($rowActivity[ActivityHeaderTable::C_USER_ID])[UserTable::C_NAME],$siged,$firstTiming,$totalTiming);

                        $firstTiming = false;
                        $counter ++;
                    }
                    
                }
                $totalBilled += $totalOverride;
                $totalActual += $rowActivity[ActivityHeaderTable::C_TT_TOTAL] / 8;

                
                $first = false;
                
            }
            //$pdf->MultiCell(175, 5, '', 'T', '', 1, 1, '', '', true);

            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize2[0]+$columnSize2[1]+$columnSize2[2]+$columnSize2[3]+$columnSize2[4], 4, "Total ", 'T', 'R', 1, 0, '', '', true);
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell($columnSize2[5], 4, number_format($totalActual, 2), 'T', 'R', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[6], 4, number_format($totalBilled, 2), 'T', 'R', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[7]+$columnSize2[8], 4, '', 'T', 'R', 1, 1, '', '', true);


            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize2[0]+$columnSize2[1]+$columnSize2[2]+$columnSize2[3]+$columnSize2[4], 5, "Balance Day ", 0, 'R', 1, 0, '', '', true);
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell($columnSize2[5], 4, "", '', 'C', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[6], 4, number_format($rowProject[ProjectTable::C_TOTAL_MANDAYS] - $totalBilled, 2), 0, 'R', 1, 1, '', '', true);
        }


        $pdf->Ln(1);
    

        // move pointer to last page
        $pdf->lastPage();

        // ---------------------------------------------------------
        
        //Close and output PDF document
        if ($outputType == 'save'){
            if ($id != 0){
                $rowActHeader = $clsHeader->getRecord($id);
                $actCode = $rowActHeader[ActivityHeaderTable::C_CODE];

                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }
                $path .= "/" . $actCode . ".pdf";
                $pdf->Output($path, 'F');
            } else {
                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }
                $path .= "/activityresult.pdf";
                $pdf->Output($path, 'F');
            }
        } else {
            $pdf->Output('preview.pdf', 'I');
        }

        //============================================================+
        // END OF FILE
        //============================================================+
    }

    public function createHeaderMandays($pdf){
        
        // set font
         $counterPosY = 10;
        //COLUMN HEADER
        
        $pdf->SetY($counterPosY);
        $margin = $pdf->getPageWidth()-110;
        
        $columnSize = array(50, 20, 20);

        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize[0], 5, "Invoice No", $border, 'C', 1, 0, $margin, '', true);
        $pdf->MultiCell($columnSize[1], 5, 'Billed',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize[2], 5, 'Paid',  $border, 'C', 1, 1, '', '', true);
        //space
        //$pdf->MultiCell(1, 5, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }


    public function createHeaderUtilzation($pdf){

        $width = $pdf->getPageWidth();
        
        // set font
        $pdf->SetFont('calibri', 'b', 17);
        $pdf->MultiCell($width-40, 5, "UTILIZATION", 0, 'C', 1, 1, PDF_MARGIN_LEFT , "", true);


        $columnSize2 = array(10,30,30,75,40,15, 15,30,15);
        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize2[0], 12, "No", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 12, 'Phase',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 12, 'Ref No',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 12, 'Description',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 12, 'Dates',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], 12, 'Actualy Days',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], 12, 'Billing Days',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], 12, 'Consultant',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], 12, 'Signed',  $border, 'C', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }


    public function processStringLine($pdf, $columnSize, $rowHeight, $bottomHeight,
                                                    $inv_no,$billed,$paid){
        
       
        $border = "";
        $resStr = null;
        $newpage=false;

        $estimated = $pdf->getNumLines($paid, $columnSize[2]);

        if((($estimated * $rowHeight) + $pdf->GetY()) > $bottomHeight){
            //print_r((($estimated * $rowHeight) + $pdf->GetY()) .">". $bottomHeight);
            //$resStr = $this->getCutPrintStr($pdf, $columnSize, $rowHeight, $bottomHeight, $desc);
            //$leftoverStr = $resStr[0];
            $newpage=true;
        } /*else {
            $leftoverStr = $desc;
        }*/


        if ($newpage){ 
            //$pdf = $this->printBottomBorder($pdf, $columnSize, $rowHeight);
            $pdf->AddPage();

            $pdf = $this->createHeaderMandays($pdf,$customer,$project);

            $pdf = $this->processStringLine($pdf, $columnSize, $rowHeight, $bottomHeight,$inv_no,$billed,$paid);
        }else{

             $pdf = $this->writeLinePDF($pdf,$border, $columnSize, $rowHeight, $inv_no,$billed,$paid);

        }
                
        return $pdf;
    }



    public function processStringLineUtilzation($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $counter,$phase,$ref,$desc,$date,$actual,$billing,$consultant,$siged,$firsttiming,$totaltiming){
       
        $border = "";
        $resStr = null;
        $newpage=false;

        $estimated = $pdf->getNumLines($desc, $columnSize2[3]);
        //$estimated = $pdf->getStringHeight(75,$desc);
        $cal_estimate =($estimated * $rowHeight) + $pdf->GetY()+11;


        //print_r( $cal_estimate.">".$bottomHeight."-".$counter."</br>");

        if( $cal_estimate > $bottomHeight){
            //print_r((($estimated * $rowHeight) + $pdf->GetY()) .">". $bottomHeight);
            //$resStr = $this->getCutPrintStr($pdf, $columnSize, $rowHeight, $bottomHeight, $desc);
            //$leftoverStr = $resStr[0];
            $newpage=true;
        } /*else {
            $leftoverStr = $desc;
        }*/


        if ($newpage){ 
            //$pdf = $this->printBottomBorder($pdf, $columnSize, $rowHeight);
            $pdf->AddPage();

            $pdf = $this->createHeaderUtilzation($pdf);

            $pdf = $this->processStringLineUtilzation($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $counter,$phase,$ref,$desc,$date,$actual,$billing,$consultant,$siged,$firsttiming,$totaltiming);
        }else{

             $pdf = $this->writeLinePDFUtilzation($pdf,$border, $columnSize2, $rowHeight, $counter,$phase,$ref,$desc,$date,$actual,$billing,$consultant,$siged,$firsttiming,$totaltiming);

        }
                
        return $pdf;
    }

   

    public function writeLinePDF($pdf,$border, $columnSize, $rowHeight,$inv_no,$billed,$paid){
        
        //$estimated = $pdf->getStringHeight(10,$paid);
        $margin = $pdf->getPageWidth()-110;
 
        $pdf->MultiCell($columnSize[0], $rowHeight, $inv_no, $border, 'C'           , 1, 0, $margin, '', true);

        $pdf->MultiCell($columnSize[1], $rowHeight, $billed, $border, 'C'           , 1, 0, '', '', true);

        $pdf->MultiCell($columnSize[2], $rowHeight, $paid, $border, 'C'           , 1, 1, '', '', true);

        return $pdf;
    }


    public function writeLinePDFUtilzation($pdf,$border, $columnSize2, $rowHeight, $counter,$phase,$ref,$desc,$date,$actual,$billing,$consultant,$siged,$firsttiming,$totaltiming){
        
        $estimated = $pdf->getStringHeight(75,$desc);
        $pdf->SetFont('calibri', '', 10);

        if(!$firsttiming){
            $billing = "";
            $consultant = "";
            $siged="";
        }
                
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $counter, $border, 'C'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $phase, $border, 'C'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $ref, $border, 'L'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, $desc, $border, 'L'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, $date, $border, 'C'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, $actual, $border, 'R'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $billing, $border, 'R'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $consultant, $border, 'C'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, $siged, $border, 'C'           , 1, 1, '', '', true);


        return $pdf;
    }


    // public function printBottomBorder($pdf, $columnSize, $rowHeight){
        
    //     //$borderTemp = "LRB";
    //     $borderTemp = "";

    //     $pdf->MultiCell($columnSize[0], $rowHeight       , '', $borderTemp, 'C'           , 1, 0, '', '', true);
    //     $pdf->MultiCell($columnSize[1], $rowHeight       , '', $borderTemp, 'L'           , 1, 0, '', '', true);
    //     $pdf->MultiCell($columnSize[2], $rowHeight       , '', $borderTemp, 'L'           , 1, 1, '', '', true);
      
        
    //     return $pdf;
    // }

    private function executeSendEmailActConfirm($actId) {
        $this->db->open();
        $result = true;
        
        try{
            $actCls = new ActivityHeaderClass($this->db);
            $companyCls = new CompanyClass($this->db);
            $userCls = new UserClass($this->db);
            $cusCls = new CustomerClass($this->db);
            $cusContactCls = new CustomerContactClass($this->db);

            $actHeaderRow   = $actCls->getRecord($actId);
            $userId         = $actHeaderRow[ActivityHeaderTable::C_USER_ID];
            $company_id     = $actHeaderRow[ActivityHeaderTable::C_COY_ID];
            $row_com        = $companyCls->getRecord($company_id) ;
            $opt            = new CompanyOptions() ;
            $opt->loadXml($row_com[CompanyTable::C_OPTIONS]) ;
            $op         = $opt->getOption() ;

            $fromEmail = $op[CompanyOptions::C_EMAIL_SETTING][CompanyOptions::C_EMAIL_SETTING_SENDER];

            $userRow        = $userCls->getRecord($userId);
            //$user_email = $userRow[UserTable::C_EMAIL];

            //$nominatedSuppRow = $requestSuppDetailCls->getSuppliers($reqId, true)[0];

            $rowCust = $cusCls->getRecord($actHeaderRow[ActivityHeaderTable::C_CUSTOMER_ID]);
            $rowContact = $cusContactCls->getCustomerContactByContactId($actHeaderRow[ActivityHeaderTable::C_CUSTOMER_ID], $actHeaderRow[ActivityHeaderTable::C_CONTACT_ID]);
            $custEmail = "";
           /* Log::Write(print_r($rowContact,true));
            die();*/
            if(!is_null($rowContact)){
                $custEmail = $rowContact[CustomerContactTable::C_EMAIL];
            }
            if( trim($custEmail) == ""){
                return true;
            }


            $fromEmailStr = $fromEmail;
            //$ccEmailStr   = $user_email;
            $fromEmails   = explode(";", $fromEmailStr);
            /*$ccEmails = null;
            if(trim($ccEmailStr) != ""){
                $ccEmails     = explode(";", $ccEmailStr);
            }*/
            
            $actCode = $actHeaderRow[ActivityHeaderTable::C_CODE];

            $path = PATH_ACTIVITY_OUTPUT . $actId . "/" . $actCode . ".pdf";
            $attachmentList = array();
            $attachmentList[] = $path;

            
            $email_body = file_get_contents(PATH_LIB . "confirmActivityemail.txt");
            $email_header = $actHeaderRow[ActivityHeaderTable::C_TITLE] . " - " . $actCode;

            $email_body = str_replace("\r\n", "<br>", $email_body);
            $email_body = str_replace("{WEB_URL}", $this->getWebPageURL(), $email_body);
            $email_body = str_replace("{COMPANY_NAME}", trim($row_com[CompanyTable::C_DESC]), $email_body);
            $email_body = str_replace("{USER_NAME}", trim($userRow[UserTable::C_FULL_NAME]), $email_body);
            $email_body = str_replace("{CUSTOMER_NAME}", trim($rowCust[CustomerTable::C_NAME]), $email_body);
            $email_body = str_replace("{ACTIVITY_CODE}", $actHeaderRow[ActivityHeaderTable::C_CODE], $email_body);
            $email_body = str_replace("{ENTER}", "<br>", $email_body);

            $email_header = str_replace("\r\n", "<br>", $email_header);
            $email_header = str_replace("{WEB_URL}", $this->getWebPageURL(), $email_header);
            $email_header = str_replace("{COMPANY_NAME}", trim($row_com[CompanyTable::C_DESC]), $email_header);
            $email_header = str_replace("{USER_NAME}", $userRow[UserTable::C_FULL_NAME], $email_header);
            $email_header = str_replace("{ACTIVITY_CODE}", $actHeaderRow[ActivityHeaderTable::C_CODE], $email_header);
            $email_header = str_replace("{CUSTOMER_NAME}", trim($rowCust[CustomerTable::C_NAME]), $email_header);
            $email_header = str_replace("{ENTER}", "<br>", $email_header);


            //Log::write("Sending email to " . $userRow[UserTable::C_FULL_NAME] . " (" . $custEmail . ") about claim update (" . $actHeaderRow[ActivityHeaderTable::C_CODE] . ")");
            $result &=  $this->sendEmail($email_header, 
                                    $email_body,
                                    $fromEmails, 
                                    explode(";",$custEmail), 
                                    null,
                                    $attachmentList,
                                    $company_id,
                                    AppType::Activity,
                                    $actId);
            //Log::write("Sending email to " . $userRow[UserTable::C_FULL_NAME] . " (" . $user_email . ") about claim update (" . $actHeaderRow[ActivityHeaderTable::C_CODE] . ")");
            /*$result &=  $this->sendEmail($email_header, 
                                    $email_body,
                                    $fromEmails, 
                                    explode(";",$user_email), 
                                    null,
                                    $attachmentList,
                                    $company_id,
                                    AppType::Activity,
                                    $actId);*/
        } catch(Exception $e){
            Log::write("[SendEmailActivity]" . $e->getMessage());
        }
        return $result;
    }

    
   private function getStatusFilterComboBox(){
    
        $defaultLang = $this->getDefaultLang();
        
        $arr = array() ;
        $arr[] = array ('code'=>'0','desc'=>"All" );
        $arr[] = array ('code'=>'1','desc'=>"Draft" );
        $arr[] = array ('code'=>'2','desc'=>"Confirm" ) ;
        return Util::createOptionValue($arr) ;
        
    }

/*    private function secondsToTime($seconds) {
        $dtF = new DateTime("@0");
        $dtT = new DateTime("@$seconds");
        //return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
        return $dtF->diff($dtT)->format('%h hours %a days');
    }*/

  
}
?>