<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/TaskPlanClass.php");
require_once (PATH_MODELS . "activity/TaskPlanParticipantClass.php");
require_once (PATH_MODELS . "activity/TaskPlanScheduleClass.php");
require_once (PATH_MODELS . "activity/TaskScheduleClass.php");
require_once (PATH_MODELS . "activity/JobCentreClass.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');
require_once (PATH_MODELS . "activity/CustomerLocationClass.php");
require_once (PATH_MODELS . "activity/CustomerLocationAssetClass.php");
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/CustomerContactClass.php");
require_once (PATH_MODELS . "activity/JobCentreListEquipmentClass.php");
require_once (PATH_MODELS . "activity/BrandClass.php");
require_once (PATH_MODELS . "activity/ModelClass.php");
require_once (PATH_MODELS . "activity/ProductClass.php");
class PortalPlan extends ActivityBase {

	function __construct() {
		$this->db 		= $_SESSION[SE_DB] ;
        $this->dbsun    = $_SESSION[SE_DB_SUN];
		$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::PortalPlan:
                    $this->processProjectInfo() ;
                    break ;
                case Command::PortalPlanFilter:
                    $this->processPlanFilter($params);
                    break;
                case Command::PortalPlanAddView:
                    $this->processViewPlanAdd();
                    break;
                case Command::PortalGeneratePlanSchedule:
                    $this->processGeneratePlanSchedule($params);
                    break;
                case Command::PortalPlanGetUser:
                    $this->processPlanGetUser($params);
                    break;
                case REQ_ADD:
                    $this->addRecord($params) ;
                    break ;
                 case REQ_DELETE:
                    $this->processPlanDelete($params);
                    break;
                case Command::PortalPlanUpdateView:
                    $this->processPlanUpdateView($params);
                    break;
                case REQ_UPDATE:
                    $this->updateRecord($params) ;
                    break ;
                case "SHOW_PLAN":
                    $this->generateShowPlan($params) ;
                    break ;
                case "C_JOB_DETAIL_VIEW":
                    $this->generateShowJobDetail($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 generateShowJobDetail($params){
        ob_start() ;
        $cls     = new JobCentreClass($this->db) ;
        $custCls = new CustomerClass($this->db) ;
        $custLocCls = new CustomerLocationClass($this->db) ;

        include (PATH_VIEWS . "portal/PlanJobCentreDetailView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']        =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']          =  "Job Detail" ;

        $id                               = $params['id'];
        $row                              = $cls->getRecord($id);

        $dataReturn['bu']                 = $row[JobCentreTable::C_COY_ID];
        $dataReturn['cust']               = $custCls->getRecord($row[JobCentreTable::C_CUST_ID])[CustomerTable::C_CODE];
        $dataReturn['coyname']            = $custCls->getRecord($row[JobCentreTable::C_CUST_ID])[CustomerTable::C_NAME];
        $dataReturn['loc']                = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CODE];
        $dataReturn['contactname']        = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CONTACT_NAME];
        $dataReturn['contactphone']       = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CONTACT_PHONE];
        $dataReturn['contactemail']       = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CONTACT_EMAIL];
        $dataReturn['address']            = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_ADDRESS];
        $dataReturn['status']             = $row[JobCentreTable::C_STATUS];
        $dataReturn['jobnumber']          = $row[JobCentreTable::C_JOB_NUMBER];
        $dataReturn['jobname']            = $row[JobCentreTable::C_JOB_NAME];
        $confirmdte   = new DateTime($row[JobCentreTable::C_JOB_CONFIRM_DATE]); 
        $dataReturn['jobconfirmdate']     = $confirmdte->format('d/m/Y');
        $startdte   = new DateTime($row[JobCentreTable::C_JOB_START_DATE]); 
        $dataReturn['jobstartdate']       = $startdte->format('d/m/Y');
        $jobtype = '';
        if($row[JobCentreTable::C_JOB_TYPE] == JobType::Project){
            $jobtype = 'Project';
        }else if($row[JobCentreTable::C_JOB_TYPE] == JobType::Contract){
            $jobtype = 'Contract';
        }else if($row[JobCentreTable::C_JOB_TYPE] == JobType::Service){
            $jobtype = 'Service';
        }else if($row[JobCentreTable::C_JOB_TYPE] == JobType::OnSiteVisit){
            $jobtype = 'On-site Visit';
        }else{
            $jobtype = '';
        }
        $dataReturn['jobtype']            = $jobtype;
        $dataReturn['totalmandays']       = number_format($row[JobCentreTable::C_TOTAL_MANDAYS], 2, ".", '');

        $dataReturn['jobcentre_list_equipment']  = $this->getJobCentreListEquipment($id);

        $this->sendJsonResponse(Status::Ok,"Show Job Detail",$dataReturn,$this->type);
    }
    private function getJobCentreListEquipment($id) {
        $cls = new JobCentreListEquipmentClass($this->db) ;
        $productCls = new ProductClass($this->db) ;
        $brandCls = new BrandClass($this->db) ;
        $modelCls = new ModelClass($this->db) ;
        if($id==0)return "";

        $html ="";
        $rows = $cls->getJobCentreListEquipment($id) ;
        
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                 
                $html .='<tr>';
                $html .= '<td style=display:none;">'.$row[JobCentreListEquipmentTable::C_PRODUCT].'</td>';
                $html .= '<td style=display:none;">'.$row[JobCentreListEquipmentTable::C_BRAND_ID].'</td>';
                $html .= '<td style=display:none;">'.$row[JobCentreListEquipmentTable::C_MODEL_ID].'</td>';
                $html .= '<td>'.$productCls->getRecord($row[JobCentreListEquipmentTable::C_PRODUCT])[ProductTable::C_DESC].'</td>';
                $html .= '<td>'.$brandCls->getRecord($row[JobCentreListEquipmentTable::C_BRAND_ID])[BrandTable::C_DESC].'</td>';
                $html .= '<td>'.$modelCls->getRecord($row[JobCentreListEquipmentTable::C_MODEL_ID])[ModelTable::C_DESC].'</td>';
                $html .= '<td>'.$row[JobCentreListEquipmentTable::C_SERIAL_NUMBER].'</td>';
                $html .= '<td>'.date_create($row[JobCentreListEquipmentTable::C_WARRANTY])->format('d/m/Y').'</td>';
                $html .= '<td>'.date_create($row[JobCentreListEquipmentTable::C_WARRANTY_END])->format('d/m/Y').'</td>';
                
                $html .= '<td>'.($row[JobCentreListEquipmentTable::C_EXT_WARRANTY] ? date_create($row[JobCentreListEquipmentTable::C_EXT_WARRANTY])->format('d/m/Y'):'').'</td>';
                $html .= '<td>'.($row[JobCentreListEquipmentTable::C_EXT_WARRANTY_END] ? date_create($row[JobCentreListEquipmentTable::C_EXT_WARRANTY_END])->format('d/m/Y'):'').'</td>';
           }
        }
        unset($cls) ;
        return $html ;
    }
    private function generateShowPlan($params){
        $cls            = new TaskScheduleClass($this->db);
        
        $date_start     = str_replace('/', '-',  $params['start_date']);
        $date_end       = str_replace('/', '-',  $params['end_date']);
/*
        $start_date     = date_create($date_start)->format('m-d-Y');
        $end_date       = date_create($date_end)->format('m-d-Y');*/

        $id             = $params['id'];

        // if($id=='Auto') {
        //     $id = 0;
        // }

        $time_format    = date_create($params['time'])->format('H:i:s') ;
        $schedule_type  = $params['schedule_type'];
        $schedule       = $params['schedule'];
        $participant    = $params['participant'];
        $html = "";
        $html .=    '<div class="row"><div class="form-group">
                        <label style="text-align:left;padding-left: 50px;width:170px;" for="txtJobNumber" class="col-sm-2 control-label">Job Number</label>
                        <div class="col-sm-2">
                            <p>'.$this->getParam($params,'jobnumberval','').'</p>
                        </div>
                    </div>';
        $html .=    '<br><div class="form-group">
                        <label style="text-align:left;padding-left: 50px;width:170px;" for="txtdescr" class="col-sm-2 control-label">Description</label>
                        <div class="col-sm-5">
                            <p>'.$this->getParam($params,'desc','').'</p>
                        </div>
                    </div></div>';
      
        $html .= "<table class='table'>";
        $html .= "<thead>";
        $html .= "<th width='20%'>Plan Date</th>";
        $html .= "<th width='22%'>Plan Time</th>";
        $html .= "<th width='40%'>Agent</th>";
        $html .= "<th width='10%'></th>";
        $html .= "</thead><tbody>";
        $index = 0; 

        // $getSchedule = $cls->getSchedulebyPlanId($id);

        // if(count($getSchedule) > 0) {
        //     foreach ($getSchedule as $row) {
        //         $html .= '<tr id="trSchedule'.$index.'">';
        //         $html .= '<td><input id="txtDate'.$index.'" class="form-control" onkeydown="return false" value="'.date_create($row[TaskScheduleTable::C_TIME])->format('d/m/Y').'"></td>';
                
        //         $html.= '<td><div class="input-group bootstrap-timepicker timepicker">
        //                     <input id="txtPlanTime'.$index.'" type="text" class="form-control input-small" value="'.date_create($row[TaskScheduleTable::C_TIME])->format('h:i A').'">
        //                 <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
        //                 </div></td>';
        //         $agent  = "";
        //         $sept   = "";
        //         if ($participant != "") {
                    
        //             $lines = explode("|",$participant) ;
                    
        //             for ($i= 0;$i < count($lines) ;$i++) {
        //                 $line = explode("~",$lines[$i]) ;
                                                        
        //                 $agent .= $sept." ".$line[3];
        //                 $sept = ",";
        //             }

        //         }
        //         $html .= '<td>'.$agent.'</td>';   
        //         $html .= '<td><a href="javascript:" onclick="removePlanSchedule('.$index.')"><span class="glyphicon glyphicon-trash"></span></a></td>';

        //         $html .= '<tr>';
        //         $index++;
        //     }
        // } else {
            if ($schedule!="" || $schedule_type==0) {
                $arr_schedule   = explode('~',$schedule);
                //Loop Date
                $begin = new DateTime($date_start);
                if($schedule_type==0) {
                    $end = new DateTime($date_end. " + 1 day");
                }else {
                    $end = new DateTime($date_end);
                }
                $interval = DateInterval::createFromDateString('1 day');
                $period = new DatePeriod($begin, $interval, $end);
    
                //Limit Time
                $timestamp = strtotime($params['time']) + 60*60*2;
                $time_cal = date('h:i A', $timestamp);
                $time_cal_format =  date_create($time_cal)->format('H:i:s') ;
                //====
                
                foreach ($period as $dt) {
    
                    $date_time_schedule = $dt->format('d/m/Y')." ".$time_format;
                    $date_time_limit = $dt->format('d/m/Y')." ".$time_cal_format;
    
                    if ($schedule_type==0) {
                        
                        $html .= '<tr id="trSchedule'.$index.'">';
                        $html .= '<td><input id="txtDate'.$index.'" class="form-control" onkeydown="return false" value="'.$dt->format('d/m/Y').'"></td>';
                        
                        $html.= '<td><div class="input-group bootstrap-timepicker timepicker">
                                    <input id="txtPlanTime'.$index.'" type="text" class="form-control input-small" value="'.$time_format.'">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                                </div></td>';
                        $agent  = "";
                        $sept   = "";
                        if ($participant != "") {
                            
                            $lines = explode("|",$participant) ;
                            
                            for ($i= 0;$i < count($lines) ;$i++) {
                                $line = explode("~",$lines[$i]) ;
                                                                
                                $agent .= $sept." ".$line[3];
                                $sept = ",";
    
                            }
                            
                        }
                        $html .= '<td>'.$agent.'</td>';   
                        $html .= '<td><a href="javascript:" onclick="removePlanSchedule('.$index.')"><span class="glyphicon glyphicon-trash"></span></a></td>';                 
                        $html .= '<tr>';
                        $index++;
                            
                    }else if ($schedule_type==1) {
                        $day = $dt->format("l");
                        $day_integer = date('N', strtotime($day));
                        
                        if (in_array($day_integer, $arr_schedule)) {
                            
                            $html .= '<tr id="trSchedule'.$index.'">';
                            $html .= '<td><input id="txtDate'.$index.'" class="form-control" onkeydown="return false" value="'.$dt->format('d/m/Y').'"></td>';
                            
                            $html.= '<td><div class="input-group bootstrap-timepicker timepicker">
                                        <input id="txtPlanTime'.$index.'" type="text" class="form-control input-small" value="'.$time_format.'">
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                                    </div></td>';
                            $agent = "";
                            $sept  = "";
                            if ($participant != "") {
                                $lines = explode("|",$participant) ;
                                
                                for ($i= 0;$i < count($lines) ;$i++) {
                                    $line = explode("~",$lines[$i]) ;
                                                                   
                                    $agent .= $sept." ".$line[3];
                                    $sept = ",";
                                }
                                
                            }
                            $html .= '<td>'.$agent.'</td>';
                            $html .= '<td><a href="javascript:" onclick="removePlanSchedule('.$index.')"><span class="glyphicon glyphicon-trash"></span></a></td>';
                            $html .= '<tr>';
                            $index++;
                        }
                        
                    }else if ($schedule_type==2){
                        $day = $dt->format("j");
                        
                        if (in_array($day, $arr_schedule)) {
                            $html .= '<tr id="trSchedule'.$index.'">';
                            $html .= '<td><input id="txtDate'.$index.'" class="form-control" onkeydown="return false" value="'.$dt->format('d/m/Y').'"></td>';
                            
                            $html.= '<td><div class="input-group bootstrap-timepicker timepicker">
                                        <input id="txtPlanTime'.$index.'" type="text" class="form-control input-small" value="'.$time_format.'">
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                                    </div></td>';
                            $agent = "";
                            $sept  = "";
                            if ($participant != "") {
                                $lines = explode("|",$participant) ;
                                
                                for ($i= 0;$i < count($lines) ;$i++) {
                                    $line = explode("~",$lines[$i]) ;
                                                                  
                                    $agent .= $sept." ".$line[3];
                                    $sept = ",";
                                }
                                
                            }
                            $html .= '<td>'.$agent.'</td>';
                            $html .= '<td><a href="javascript:" onclick="removePlanSchedule('.$index.')"><span class="glyphicon glyphicon-trash"></span></a></td>';
                            $html .= '<tr>';
                            $index++;  
                        }
                        
                    } 
                }

                if ($schedule_type==3){
                    // $day = $dt->format("j");

                    $quarter = $this->get_quarters($date_start, $date_end, $arr_schedule);

                    // if (in_array($day, $arr_schedule)) {
                    foreach ($quarter as $qtr) {
                        $date = new DateTime($qtr);

                        $html .= '<tr id="trSchedule'.$index.'">';
                        $html .= '<td><input id="txtDate'.$index.'" class="form-control" onkeydown="return false" value="'.$date->format('d/m/Y').'"></td>';
                        
                        $html.= '<td><div class="input-group bootstrap-timepicker timepicker">
                                    <input id="txtPlanTime'.$index.'" type="text" class="form-control input-small" value="'.$time_format.'">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                                </div></td>';
                        $agent = "";
                        $sept  = "";
                        if ($participant != "") {
                            $lines = explode("|",$participant) ;
                            
                            for ($i= 0;$i < count($lines) ;$i++) {
                                $line = explode("~",$lines[$i]) ;                       
                                
                                $agent .= $sept." ".$line[3];
                                $sept = ",";
                                
                            }
                            
                        }
                        $html .= '<td>'.$agent.'</td>';
                        $html .= '<td><a href="javascript:" onclick="removePlanSchedule('.$index.')"><span class="glyphicon glyphicon-trash"></span></a></td>';
                        $html .= '<tr>';
                        $index++;
                    }
                    // }
                    
                }else{
                
                }
            }
        // }

        $html .= "</tbody>";
        $html .= "</table>";
        $dataReturn = array();
        $dataReturn['htmlContent']  =  $html ;
        $dataReturn['headTitle']    =  "My Plan" ;
        $dataReturn['countIndex']   =  $index ;
        $dataReturn['is_update']    =  $this->getParam($params,'is_update','') ;
        $this->sendJsonResponse(Status::Ok,"Load Home Info",$dataReturn,$this->type);

    }

    // get month name from number
    function month_name($month_number){
        return date('F', mktime(0, 0, 0, $month_number, 10));
    }
    
    
    // get get last date of given month (of year)
    function month_end_date($year, $month_number){
        return date("t", strtotime("$year-$month_number-1"));
    }
    
    // return two digit month or day, e.g. 04 - April
    function zero_pad($number){
        if($number < 10)
            return "0$number";
        
        return "$number";
    }

    function get_quarters($start_date, $end_date, $schedule){    
        $quarters = array();
        
        $start_month = date( 'm', strtotime($start_date) );
        $start_year = date( 'Y', strtotime($start_date) );
        
        $end_month = date( 'm', strtotime($end_date) );
        $end_year = date( 'Y', strtotime($end_date) );
        
        $start_quarter = ceil($start_month/3);
        $end_quarter = ceil($end_month/3);
    
        $quarter = $start_quarter; // variable to track current quarter
        
        // Loop over years and quarters to create array
        for($y = $start_year; $y <= $end_year; $y++ ){
            if($y == $end_year)
                $max_qtr = $end_quarter;
            else
                $max_qtr = 4;
            
            for($q=$quarter; $q<=$max_qtr; $q++){
                
                $current_quarter = new stdClass();
                
                $end_month_num = $this->zero_pad($q * 3);
                $start_month_num = ($end_month_num - 2);
    
                $q_start_month = $this->month_name($start_month_num);
                $q_end_month = $this->month_name($end_month_num);
                
                foreach ($schedule as $sched) {
                    $current_quarter = "$y-$start_month_num-$sched"; // yyyy-mm-dd    
                    $quarters[] = $current_quarter;
                    unset($current_quarter);
                }

            }
    
            $quarter = 1; // reset to 1 for next year
        }
        
        return $quarters;
        
    }

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


    private function processPlanFilter($params) {

        $cls         = new TaskPlanClass($this->db);
        $centreCls   = new JobCentreClass($this->db);

        $rows        = $cls->getTaskPlanList($params['status']);
        
        $htmlStr     = "<thead>" .
                            "<tr>" .
                                "<th width='15%'>Job Number</th>" .
                                "<th width='30%'>Description</th>" .
                                "<th width='15%'>Schedule Type</th>" .
                                "<th width='10%'>Start Date</th>" .
                                "<th width='10%'>End Date</th>" .
                                "<th width='10%'>Time</th>" .
                                "<th width='15%'>&nbsp</th>" .
                            "</tr>" .
                        "</thead> <tbody> <tr></tr>";


        if(!is_null($rows) && count($rows) > 0){

            foreach ($rows as $row) {

                $btnStr  = "<button  title=\"View\" onclick=\"return showEditPlan(". $row[TaskPlanTable::C_ID] .", this);\" id=\"btnEdit\" data-toggle=\"modal\" class=\"btn btn-primary glyphicon glyphicon-edit btn-sm\"></button>"; 
                $btnStr  .= "<button title=\"Delete\" onclick=\"javascript: popupDeletePlan(" . $row[TaskPlanTable::C_ID] .", this);\" id=\"btnDelete\" data-toggle=\"modal\" class=\"btn btn-danger glyphicon glyphicon-trash btn-sm\"></button>";

            
               $htmlStr .= "<tr  id=\"plan-rows-" . $row[TaskPlanTable::C_ID] . "\">" .
                                "<td style='display:none'>" . $row[TaskPlanTable::C_ID] . "</td>" . 
                                "<td>" . $centreCls->getRecord($row[TaskPlanTable::C_JOB_ID])[JobCentreTable::C_JOB_NUMBER] . "</td>" .
                                "<td>" . $row[TaskPlanTable::C_DESC] . "</td>" .
                                "<td>" . $this->getScheduleType($row[TaskPlanTable::C_SCHEDULE_TYPE]) . "</td>" .
                                "<td>" . date_create($row[TaskPlanTable::C_START_TIME])->format('d/m/Y') . "</td>" .
                                "<td>" . date_create($row[TaskPlanTable::C_END_TIME])->format('d/m/Y') . "</td>" .
                                "<td>" . date_create($row[TaskPlanTable::C_START_TIME])->format('h:i A') . "</td>" .
                                "<td><div>" . $btnStr . "</div></td>".
                            "</tr>";
            }
            
        }
		
        $htmlStr .="</tbody>";
        
        $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);

        unset($cls);
        
    }


    private function processViewPlanAdd() {
        ob_start() ;
        
        include (PATH_VIEWS . "portal/PlanAddView.php") ;
        $addHeaderContent= array() ;
        $addHeaderContent["all"] =  Util::minifyHtml(ob_get_clean()) ;
        
        $this->sendJsonResponse(Status::Ok,"Plan Add Content",$addHeaderContent,$this->type);
    }

    private function processGeneratePlanSchedule($params) {
        $id_plan  = $params['id_plan'];
        $schedule_type  = $params['schedule_type'];
        $schedule_max   = 0;
        $schedule_label   = "";
        if ($schedule_type==1) {
            $schedule_max   = 7;
            $schedule_label   = "Weekly";
        }
        if ($schedule_type==2) {
            $schedule_max   = 31;
            $schedule_label   = "Monthly";
        } else if($schedule_type==3){
            $schedule_max   = 31;
            $schedule_label   = "Quarterly";
        }
        
        if($schedule_max > 0 && $schedule_label != "") {
            $htmlStr     = "<label for=\"txtPlanSchedule\" style=\"text-align:left;padding-left: 50px;width:170px;\" class=\"col-sm-2 control-label\">".$schedule_label."</label>
                        <div class=\"col-sm-10\">";

            for ($i=1; $i <= $schedule_max ; $i++) { 
    
                $htmlStr     .= "<label class=\"checkbox-inline\"><input type=\"checkbox\" id=\"cbkSchedule-".$i."\" value=\"".$i."\">".$i."</label>";
            }
            $htmlStr     .= "</div>";
        }


         $datas = array();
         if($schedule_type==0) {
            $datas['schedule']     = "";
         } else {
            $datas['schedule']     = $htmlStr;
         }
         $datas['count']        = $schedule_max;
         if ($id_plan!='Auto') {
            $datas['schedule_val']      = $this->getSchedule($id_plan);
         }else{
            $datas['schedule_val']      = 0;
         }

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

    private function getSchedule($id) {
        $cls     = new TaskPlanScheduleClass($this->db) ;
        $rows     = $cls->getTaskPlanSchedule($id);
        $lines = "" ;
        $sp = "" ;
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $lines .= $sp.$row[TaskPlanScheduleTable::C_TIME];
                $sp = "~";
            }                           
        }
        unset($cls) ;
        return $lines ;
    }

    private function processPlanGetUser($params) {
        if (isset($params['user_id']) && $params['user_id']!="") {
            $id  = $params['user_id'];

            $cls = new UserClass($this->db);

            $row =$cls->getRecord($id);

            $datas = array();
            $datas['user_id']= $id;
            $datas['name']= $row[UserTable::C_FULL_NAME];
            $datas['email']= $row[UserTable::C_EMAIL];

            $this->sendJsonResponse(Status::Ok,"",$datas,$this->type);
        }else{
            $this->sendJsonResponse(Status::Error,"You must supply the user id you wish to update. Please try again.","",$this->type);
        }
        
    }


    private function addRecord($params) {
		$cls        = new TaskPlanClass($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];

        $date_start = str_replace('/', '-',  $params['start_date']);
        $date_end = str_replace('/', '-',  $params['end_date']);

        $start_time = $date_start." ".$params['time'];
        $end_time = $date_end." ".$params['time'];

        $combined_start_time = DateTime::createFromFormat('d-m-Y h:i A',$start_time)->format('Y-m-d H:i:s');
        $combined_end_time = DateTime::createFromFormat('d-m-Y h:i A',$end_time)->format('Y-m-d H:i:s');
        //Log::Write(print_r($combined_end_time,true));die(); 
       
        $datas[] = $this->db->fieldValue(TaskPlanTable::C_JOB_ID,$this->getParamInt($params,'jobnumber',0)) ;
		$datas[] = $this->db->fieldValue(TaskPlanTable::C_DESC,$this->getParam($params,'desc',"")) ;
		$datas[] = $this->db->fieldValue(TaskPlanTable::C_SCHEDULE_TYPE,$this->getParam($params,'schedule_type',"")) ;
		$datas[] = $this->db->fieldValue(TaskPlanTable::C_START_TIME,$combined_start_time) ;
		$datas[] = $this->db->fieldValue(TaskPlanTable::C_END_TIME,$combined_end_time) ;
		$datas[] = $this->db->fieldValue(TaskPlanTable::C_ORG_ID,$orgid) ;
		$datas[] = $this->db->fieldValue(TaskPlanTable::C_WS_ID,$ws) ;
		$datas[] = $this->db->fieldValue(TaskPlanTable::C_MODIFY_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(TaskPlanTable::C_CREATE_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(TaskPlanTable::C_MODIFY_DATE,$modifydate) ;
		$datas[] = $this->db->fieldValue(TaskPlanTable::C_CREATE_DATE,$modifydate) ;

        $schedule = $params['schedule'];
		$participant = $params['participant'];
       	//Log::Write(print_r($datas,true));die();	
		try {
			$id = $cls->addRecord($datas) ;
			if ($id > 0) {
                $this->addPlanSchedule($id,$schedule) ;
                $this->addPlanParticipant($id,$participant) ;
				//$this->generateTaskSchedule($id,$params) ;
                $this->generatePlanTaskSchedule($id,$params) ;
				$this->sendJsonResponse(Status::Ok,"Plan 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 generateTaskSchedule($id, $params) {
//         $cls            = new TaskScheduleClass($this->db);
//         $id             = $id;

//         $date_start     = str_replace('/', '-',  $params['start_date']);
//         $date_end       = str_replace('/', '-',  $params['end_date']);
// /*
//         $start_date     = date_create($date_start)->format('m-d-Y');
//         $end_date       = date_create($date_end)->format('m-d-Y');*/

//         $time_format    = date_create($params['time'])->format('H:i:s') ;
//         $schedule_type  = $params['schedule_type'];
//         $schedule       = $params['schedule'];

//         if ($schedule!="" || $schedule_type==0) {
//             $arr_schedule   = explode('~',$schedule);
//             //Loop Date
//             $begin = new DateTime($date_start);
//             if($schedule_type==0) {
//                 $end = new DateTime($date_end. " + 1 day");
//             }else {
//                 $end = new DateTime($date_end);
//             }
//             $interval = DateInterval::createFromDateString('1 day');
//             $period = new DatePeriod($begin, $interval, $end);

//             //Limit Time
//             $timestamp = strtotime($params['time']) + 60*60*2;
//             $time_cal = date('h:i A', $timestamp);
//             $time_cal_format =  date_create($time_cal)->format('H:i:s') ;
//             //====

//             foreach ($period as $dt) {

//                 $date_time_schedule = $dt->format('Y-m-d')." ".$time_format;
//                 $date_time_limit = $dt->format('Y-m-d')." ".$time_cal_format;

//                 if ($schedule_type==0) {
//                         $datas   = array() ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ID,$id) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_TIME,$date_time_schedule) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_LIMIT_TIME,$date_time_limit) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_START_TIME,$date_time_schedule) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_END_TIME,$date_time_limit) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_MODIFY_BY,$_SESSION[SE_USERID]) ;

//                         $cls->addRecord($datas) ;
//                 }else if ($schedule_type==1) {
//                     $day = $dt->format("l");
//                     $day_integer = date('N', strtotime($day));

//                     if (in_array($day_integer, $arr_schedule)) {
//                         $datas   = array() ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ID,$id) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_TIME,$date_time_schedule) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_LIMIT_TIME,$date_time_limit) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_START_TIME,$date_time_schedule) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_END_TIME,$date_time_limit) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_MODIFY_BY,$_SESSION[SE_USERID]) ;
                       
//                         $cls->addRecord($datas) ;

//                     }
//                 }else if ($schedule_type==2){
//                     $day = $dt->format("j");
//                     if (in_array($day, $arr_schedule)) {
//                         $datas   = array() ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ID,$id) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_TIME,$date_time_schedule) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_LIMIT_TIME,$date_time_limit) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_START_TIME,$date_time_schedule) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_END_TIME,$date_time_limit) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_MODIFY_BY,$_SESSION[SE_USERID]) ;

//                         $cls->addRecord($datas) ;
//                     }
//                 } else if ($schedule_type==3){
//                     $day = $dt->format("j");
//                     if (in_array($day, $arr_schedule)) {
//                         $datas   = array() ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ID,$id) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_TIME,$date_time_schedule) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_LIMIT_TIME,$date_time_limit) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_START_TIME,$date_time_schedule) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_END_TIME,$date_time_limit) ;
//                         $datas[] = $this->db->fieldValue(TaskScheduleTable::C_MODIFY_BY,$_SESSION[SE_USERID]) ;

//                         $cls->addRecord($datas) ;
//                     }
//                 }else{

//                 }
//             }

//         }
        
//     }

    private function generatePlanTaskSchedule($id, $params) {
        $cls            = new TaskScheduleClass($this->db);
        $id             = $id;

        $schedule       = $params['planschedule'];
        if($schedule != ''){
            $arr_schedule   = explode('~',$schedule);
        
            foreach ($arr_schedule as $dt) {
                $date_time   = explode('|',$dt);

                if($date_time[0]!='undefined' && $date_time[1]!='undefined') {
                    $date_time_schedule = $date_time[0]." ".$date_time[1];
                    //$date_time_limit = $date_time[0]." ".$date_time[1];
                    $date_time_schedule     = str_replace('/', '-',  $date_time_schedule);
                    
                    $date = date_create($date_time_schedule);
                    $datas   = array() ;
                    $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ID,$id) ;
                    $datas[] = $this->db->fieldValue(TaskScheduleTable::C_TIME,$date->format('Y-m-d H:i:s')) ;
                    $datas[] = $this->db->fieldValue(TaskScheduleTable::C_LIMIT_TIME,$date->format('Y-m-d H:i:s')) ;
                    $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_START_TIME,$date->format('Y-m-d H:i:s')) ;
                    $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_END_TIME,$date->format('Y-m-d H:i:s')) ;
                    $datas[] = $this->db->fieldValue(TaskScheduleTable::C_MODIFY_BY,$_SESSION[SE_USERID]) ;
                    // Log::write(print_r($datas,true));
        
                    $cls->addRecord($datas) ;
                }       
            }
            // die();
        }
        

        
    }

	private function addPlanSchedule($id, $schedule) {
		$cls = new TaskPlanScheduleClass($this->db) ;
		if ($schedule != "") {
            $time = explode("~",$schedule) ;
            for ($i=0; $i <count($time) ; $i++) { 
                $datas = array() ;
                $datas[] = $this->db->fieldValue(TaskPlanScheduleTable::C_ID,$id);
                $datas[] = $this->db->fieldValue(TaskPlanScheduleTable::C_TIME,$time[$i]) ;
                $cls->addRecord($datas) ;
            }
				
		}
		unset($cls) ;
	}

    private function addPlanParticipant($id, $participant) {
        $cls = new TaskPlanParticipantClass($this->db) ;
        if ($participant != "") {
            $lines = explode("|",$participant) ;
            for ($i= 0;$i < count($lines) ;$i++) {
                $line = explode("~",$lines[$i]) ;
                $datas = array() ;
                $datas[] = $this->db->fieldValue(TaskPlanParticipantTable::C_ID,$id);
                $datas[] = $this->db->fieldValue(TaskPlanParticipantTable::C_PARTICIPANT_TYPE,$line[1]) ;
                $datas[] = $this->db->fieldValue(TaskPlanParticipantTable::C_USER_ID,$line[2]) ;
                $datas[] = $this->db->fieldValue(TaskPlanParticipantTable::C_PARTICIPANT_NAME,$line[3]) ;
                $datas[] = $this->db->fieldValue(TaskPlanParticipantTable::C_PARTICIPANT_EMAIL,$line[4]) ;
                $cls->addRecord($datas) ;
            }
        }
        unset($cls) ;
    }

    private function processPlanUpdateView($params) {
        ob_start() ;
        $id= $params['id'];
        $cls             = new TaskPlanClass($this->db) ;

        $rowPlan         = $cls->getRecord($id);

        $datas = array();
        
        include (PATH_VIEWS . "portal/PlanAddView.php") ;
        
        $editHeaderContent = array();

        $editHeaderContent["all"]       =  Util::minifyHtml(ob_get_clean()) ;

        $datas['id']                    = $rowPlan[TaskPlanTable::C_ID];
        $datas['jobnumber']             = $rowPlan[TaskPlanTable::C_JOB_ID];
        $datas['desc']                  = $rowPlan[TaskPlanTable::C_DESC];
        $datas['schedule_type']         = $rowPlan[TaskPlanTable::C_SCHEDULE_TYPE];
        $datas['start_time']            = date_create($rowPlan[TaskPlanTable::C_START_TIME])->format('d/m/Y');
        $datas['end_time']              = date_create($rowPlan[TaskPlanTable::C_END_TIME])->format('d/m/Y');
        $datas['time']                  = date_create($rowPlan[TaskPlanTable::C_START_TIME])->format('h:i A');

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

      private function getParticipant($id) {
        $cls  = new TaskPlanParticipantClass($this->db) ;
        $clsUser  = new UserClass($this->db) ;
        $rows = $cls->getTaskPlanParticipant($id) ;
        $lines = "" ;
        $sp = "" ;
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {

                $user_detail = $clsUser->getRecord($row[TaskPlanParticipantTable::C_USER_ID])[UserTable::C_NAME];

                $lines .= $sp.$row[TaskPlanParticipantTable::C_ID] . "~" . 
                    $row[TaskPlanParticipantTable::C_PARTICIPANT_TYPE] . "~" . 
                    $row[TaskPlanParticipantTable::C_USER_ID] . "~" . 
                    $row[TaskPlanParticipantTable::C_PARTICIPANT_NAME] . "~" . 
                    $row[TaskPlanParticipantTable::C_PARTICIPANT_EMAIL] . "~" . 
                    $user_detail;
                $sp = "|" ;
            }                           
        }
        unset($cls) ;
        return $lines ;
    }


    private function updateRecord($params) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls        = new TaskPlanClass($this->db) ;
            $clsSchedule = new TaskPlanScheduleClass($this->db) ;
            $clsParticipant = new TaskPlanParticipantClass($this->db) ;
            $clsTask            = new TaskScheduleClass($this->db);
			try {

				$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];

                $date_start = str_replace('/', '-',  $params['start_date']);
                $date_end = str_replace('/', '-',  $params['end_date']);

                $start_time = $date_start." ".$params['time'];
                $end_time = $date_end." ".$params['time'];

                $combined_start_time = DateTime::createFromFormat('d-m-Y h:i A',$start_time)->format('Y-m-d H:i:s');
                $combined_end_time = DateTime::createFromFormat('d-m-Y h:i A',$end_time)->format('Y-m-d H:i:s');
		          
                $datas[] = $this->db->fieldValue(TaskPlanTable::C_JOB_ID,$this->getParamInt($params,'jobnumber',0)) ;
                $datas[] = $this->db->fieldValue(TaskPlanTable::C_DESC,$this->getParam($params,'desc',"")) ;
                $datas[] = $this->db->fieldValue(TaskPlanTable::C_SCHEDULE_TYPE,$this->getParam($params,'schedule_type',"")) ;
                $datas[] = $this->db->fieldValue(TaskPlanTable::C_START_TIME,$combined_start_time) ;
                $datas[] = $this->db->fieldValue(TaskPlanTable::C_END_TIME,$combined_end_time) ;
                $datas[] = $this->db->fieldValue(TaskPlanTable::C_ORG_ID,$orgid) ;
                $datas[] = $this->db->fieldValue(TaskPlanTable::C_WS_ID,$ws) ;
                $datas[] = $this->db->fieldValue(TaskPlanTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(TaskPlanTable::C_MODIFY_DATE,$modifydate) ;
                $datas[] = $this->db->fieldValue(TaskPlanTable::C_CREATE_DATE,$modifydate) ;

                $schedule = $params['schedule'];
                $participant = $params['participant'];
                
                $clsSchedule->deleteTaskPlanSchedule($id);
                $this->addPlanSchedule($id,$schedule) ;
                $clsParticipant->deleteTaskPlanParticipant($id);
                $this->addPlanParticipant($id,$participant) ;
                $clsTask->deleteTaskSchedule($id,0,0);
                //$this->generateTaskSchedule($id,$params) ;

                $this->generatePlanTaskSchedule($id,$params) ;
				$cls->updateRecord($id,$datas) ;

				$this->sendJsonResponse(Status::Ok,"Plan  successfully updated to the system.",$datas,$this->type) ;
			} catch (Exception $e) {
				Log::write('[Plan]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating Plan 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 processPlanDelete($params) {
        if (isset($params['id']) && $params['id']!= "") {

			$id = $params['id'] ;
			$cls             = new TaskPlanClass($this->db) ;
            $clsSchedule     = new TaskPlanScheduleClass($this->db) ;
			$clsParticipant  = new TaskPlanParticipantClass($this->db) ;
            $clsTaskSchedule = new TaskScheduleClass($this->db);

			try {
				$cls->deleteRecord($id) ; 
                $clsSchedule->deleteTaskPlanSchedule($id);
                $clsParticipant->deleteTaskPlanParticipant($id);
               	$clsTaskSchedule->deleteTaskSchedule($id);
				$this->sendJsonResponse(Status::Ok,"Plan successfully deleted from the system.",$id,$this->type);
			} catch (Exception $e) {
				Log::write('[Plan]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting Project record from the system.","",$this->type) ;
			}
			unset($cls) ;
            unset($clsSchedule) ;
			unset($clsParticipant) ;
        } 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));
    }

    private function getStatusFilterComboBox(){
        $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 getScheduleType($id){
        if ($id==0) {
            return "Daily";
        }else if($id==1){
            return "Weekly";
        }else if($id==2){
            return "Monthly";
        }else if($id==3){
            return "Quarterly";
        }else{
            return "";
        }
        
    }

    private function getParticipantOpt(){
        $arr = array() ;
        $arr[] = array ('code'=>ParticipantType::Assign,'desc'=>"Assign" );
        $arr[] = array ('code'=>ParticipantType::Done,'desc'=>"Done" );
        $arr[] = array ('code'=>ParticipantType::NotDone,'desc'=>"Not Done" );
        return Util::createOptionValue($arr) ;
        
    }

    private function getUserOpt() {
        $cls = new UserClass($this->db) ;

        $sql = "SELECT * FROM " . UserTable::C_TABLE;
        $sql .= " WHERE " . UserTable::C_DESIGNATION . " = " . UserType::Agent;
        $rows = $this->db->getTable($sql);

        $vls = array() ;
        $vls[] = array ('code'=>'0','desc'=>'Other' ) ;

        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[UserTable::C_ID],'desc'=>$row[UserTable::C_NAME]) ;
            }
        }
        return Util::createOptionValue($vls) ;
    }

    private function getJobNumberOption(){
        $centreCls = new JobCentreClass($this->db);

        $sql = "SELECT * FROM " . JobCentreTable::C_TABLE;
        $sql .= " WHERE " . JobCentreTable::C_JOB_TYPE . " = " . JobType::Contract ;
        $sql .= " AND " . JobCentreTable::C_STATUS . " = 0";
        $rows = $this->db->getTable($sql);
        
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select a Job Number --") ;
        
        if(!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $job_title = (strlen($row[JobCentreTable::C_JOB_NAME]) > 15 ? substr($row[JobCentreTable::C_JOB_NAME], 0, 15).'..' : $row[JobCentreTable::C_JOB_NAME]);
                $vls[] = array ('code'=>$row[JobCentreTable::C_ID],'desc'=>$row[JobCentreTable::C_JOB_NUMBER]." - ".$job_title) ;
            }           
        }
        return Util::createOptionValue($vls) ;
    }
}
?>