<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/ProjectClass.php") ;
require_once (PATH_MODELS . "activity/JobCentreClass.php") ;
require_once (PATH_MODELS . "admin/UserClass.php") ;
require_once (PATH_MODELS . "activity/ActivityConsultantClass.php") ;

class ActivityConsultant extends ControllerBase {
	private $type = "" ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
	}
	function __destruct() {
		unset($this->db) ;
	}
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		
		try {
			$this->db->open() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			switch ($this->type) {
				case REQ_ADD:
					$this->addRecord($params) ;
					break ;
				case REQ_UPDATE:
					$this->updateRecord($params) ;
					break ;
				case REQ_DELETE:
					$this->deleteRecord($params) ;
					break ;
				case REQ_GET:
					$this->getRecord($params) ;
					break ;
				case REQ_LIST:
					$this->getList($params) ;
					break ;
				case REQ_REPORT:
					$this->getReport($params) ;
					break ;
				case REQ_EXPORT:
					$this->getExport($params) ;
					break ;
				case REQ_VIEW:
					$this->getView() ;
					break ;
				default:
					$this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
					break ;
			}
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
	}
	
	private function getList($conditions=null) {
		$cls = new ActivityConsultantClass($this->db) ;
		$clsProject = new ProjectClass($this->db) ;
		$clsUser = new UserClass($this->db) ;
		$filter = "";
		$cond = " AND ";
		$params = array() ;
		
		
		if (!is_null($conditions) && count($conditions) > 0) {
			
			if (isset($conditions['consultant']) && $conditions['consultant'] != "" && $conditions['consultant'] != 0) {
				$filter .= $cond .'h.'.ActivityHeaderTable::C_MODIFY_BY . " = " . $conditions['consultant'];
				$cond = " AND " ;
			}
			if (isset($conditions['project']) && $conditions['project'] != "" && $conditions['project'] != 0) {
				$filter .= $cond .'h.'. ActivityHeaderTable::C_JOB_ID . " = " .$conditions['project']."";
				$cond = " AND " ;
			}
			if ((isset($conditions['fromdate']) && $conditions['fromdate'] != "" && $conditions['todate'] == "") || 
				(isset($conditions['todate']) && $conditions['todate'] != "") ) {
				$filter .= $cond . " h.".ActivityHeaderTable::C_DATE . " BETWEEN '" .$this->getParamDate($conditions, 'fromdate',NULL_DATE)."'".
									" AND '" . $this->getParamDate($conditions, 'todate',MAX_DATE) ."'";
							
			}
			
		}

		//$rows = $cls->getTable($filter,ActivityConsultantTable::C_ID,$params) ;
		$rowstest = $cls->getConsultantList($filter);
		$list = "" ;
		$arrList = [];
		foreach ($rowstest as $i => $row) {
		
		
			// $list .= "<tr>" ;
			// $list .= "<td>" . "". "</td>" ;
			// $list .= "<td>" . $row[UserTable::C_NAME]. "</td>" ;
			// $list .= "<td>" . $row[JobCentreTable::C_JOB_NAME] . "</td>" ;
			// $list .= "<td>" .  number_format($row['billable'],2) . "</td>" ;
			// $list .= "<td>" .  number_format($row['nonbillable'],2) . "</td>" ;
			
			// $list .= "</tr>" ;

			//=====================================
			$arrList[$i]["name"] = $row[UserTable::C_NAME];
			$arrList[$i]["jobnumber"] = $row[JobCentreTable::C_JOB_NUMBER];	
			$arrList[$i]["jobname"] = $row[JobCentreTable::C_JOB_NAME];	
			$arrList[$i]["billable"] = number_format($row['billable'],2);
			$arrList[$i]["nonbillable"] = number_format($row['nonbillable'],2);
			$arrList[$i]["actions"] = "";
		}
		
		// Log::write(print_r($arrList,true));
		$this->sendJsonResponse(Status::Ok,"",$arrList,$this->type) ;
		
		unset($clsProject) ;
		unset($clsUser) ;
		unset($rows) ;
		unset($cls) ;
	}

	private function getView() {
        Log::write("Expense Item " . $this->getWebPageURL());
		ob_start() ;
		include (PATH_VIEWS . "activity/ActivityConsultantView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}
	private function getReport($params=null) {
		require_once(PATH_LIB . 'ListPdf.php');
		$cls = new ActivityConsultantClass($this->db) ;
		$filter = "";
		$cond = " AND ";
		
		
		if (!is_null($params) && count($params) > 0) {
			
			if (isset($params['empIdBegin']) && $params['empIdBegin'] != "" && $params['empIdBegin'] != 0) {
				$filter .= $cond .'h.'.ActivityHeaderTable::C_MODIFY_BY . " = " . $params['empIdBegin'];
				$cond = " AND " ;
			}
			if (isset($params['pr']) && $params['pr'] != "" && $params['pr'] != 0) {
				$filter .= $cond .'h.'. ActivityHeaderTable::C_JOB_ID . " = " .$params['pr']."";
				$cond = " AND " ;
			}
			if ((isset($params['date']) && $params['date'] != "" && $params['dateend'] == "") || 
				(isset($params['dateend']) && $params['dateend'] != "") ) {
				$filter .= $cond . " h.".ActivityHeaderTable::C_DATE . " BETWEEN '" .$this->getParamDate($params, 'date',NULL_DATE)."'".
									" AND '" . $this->getParamDate($params, 'dateend',MAX_DATE) ."'";
							
			}
			
		}
	
		$rows = $cls->getConsultantList($filter);
	
		$i = 'items';
		$nr = 'newrow';
		$datas = array() ;
		foreach ($rows as $row) {
			$items = array() ;
			$items[$i][] = $this->createPdfItem($row[UserTable::C_NAME],100) ;
			$items[$i][] = $this->createPdfItem($row[JobCentreTable::C_JOB_NUMBER],100) ;
			$items[$i][] = $this->createPdfItem($row[JobCentreTable::C_JOB_NAME],220) ;
			$items[$i][] = $this->createPdfItem(number_format($row['billable'],2),100) ;
			$items[$i][] = $this->createPdfItem(number_format($row['nonbillable'],2),100) ;
			$items[$nr] = "1";
			$datas[] = $items ;
		}
		$cols = array() ;
		$cols[] = $this->createPdfItem("Consultant",100,0,"C","B");
		$cols[] = $this->createPdfItem("Job Number",100,0,"C","B") ;
		$cols[] = $this->createPdfItem("Job Name",220,0,"C","B") ;
		$cols[] = $this->createPdfItem("Billable Hour",100,0,"C","B") ;
		$cols[] = $this->createPdfItem("None Billable Hour",100,0,"C","B") ;
		$pdf = new ListPdf('P');
		$pdf->setCompanyName($_SESSION[SE_ORGNAME]) ;
		$pdf->setReportTitle("Consultant Activity") ;
		$pdf->setColumnsHeader($cols) ;
		$pdf->render($datas) ;
		$pdf->Output('expense_item.pdf', 'I');
		unset($rows) ;
		unset($cls) ;
		unset($datas) ;
		unset($params) ;
		unset($items) ;
		unset($cols) ;
	}
	private function getExport($params=null){
		$cls = new ActivityConsultantClass($this->db) ;
		$filter = "";
		$cond = " AND ";
		
		
		if (!is_null($params) && count($params) > 0) {
			
			if (isset($params['empIdBegin']) && $params['empIdBegin'] != "" && $params['empIdBegin'] != 0) {
				$filter .= $cond .'h.'.ActivityHeaderTable::C_MODIFY_BY . " = " . $params['empIdBegin'];
				$cond = " AND " ;
			}
			if (isset($params['pr']) && $params['pr'] != "" && $params['pr'] != 0) {
				$filter .= $cond .'h.'. ActivityHeaderTable::C_JOB_ID . " = " .$params['pr']."";
				$cond = " AND " ;
			}
			if ((isset($params['date']) && $params['date'] != "" && $params['dateend'] == "") || 
				(isset($params['dateend']) && $params['dateend'] != "") ) {
				$filter .= $cond . " h.".ActivityHeaderTable::C_DATE . " BETWEEN '" .$this->getParamDate($params, 'date',NULL_DATE)."'".
									" AND '" . $this->getParamDate($params, 'dateend',MAX_DATE) ."'";
							
			}
			
		}
	
		$rows = $cls->getConsultantList($filter);

		$excel = new PHPExcel();
		$colno = array();
		$colno[0] = "A" ;
		$colno[1] = "B" ;
		$colno[2] = "C" ;
		$colno[3] = "D" ;
		
		$excel = new PHPExcel();
		$excel->getProperties()->setCreator("")
							->setLastModifiedBy("")
							->setTitle("")
							->setSubject("")
							->setDescription("")
							->setKeywords("")
							->setCategory("");

		 $excel->setActiveSheetIndex(0)
				->setCellValue('A1',$_SESSION[SE_COYNAME]) 
				->setCellValue('A2', "Consultant Activity");

		$excel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
		$excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
		$excel->getActiveSheet()->mergeCells('A1:'.$colno[count($colno)-1].'1');
		$excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			
		$excel->getActiveSheet()->getStyle('A2')->getFont()->setSize(16);
		$excel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
		$excel->getActiveSheet()->mergeCells('A2:'.$colno[count($colno)-1].'2');
		$excel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

		$rowidx = 7;
		$excel->getActiveSheet()
				->setCellValue("A".$rowidx, "Consultant")
				->setCellValue("B".$rowidx, "Job Number")
				->setCellValue("B".$rowidx, "Job Name")
				->setCellValue("C".$rowidx, "Billable Hour")
				->setCellValue("D".$rowidx, "None Billable Hour");

		for ($i=0 ;$i < count($colno);$i++) {
			$cellidx = $colno[$i].$rowidx ;
			$excel->getActiveSheet()->getStyle($cellidx)->getFont()->setBold(true);
			$excel->getActiveSheet()->getStyle($cellidx)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		}
		$rowidx++;
		
		if (count($rows) > 0) {
			$expfile = "";
			foreach ($rows as $row) {
				
				
				$excel->getActiveSheet()
						->setCellValue("A".$rowidx, $row[UserTable::C_NAME]) 
						->setCellValue("B".$rowidx, $row[JobCentreTable::C_JOB_NUMBER]) 
						->setCellValue("C".$rowidx, $row[JobCentreTable::C_JOB_NAME]) 
						->setCellValue("D".$rowidx, number_format($row['billable']))
						->setCellValue("E".$rowidx, number_format($row['nonbillable']));
	
				$excel->getActiveSheet()->getStyle("C".$rowidx)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
				$excel->getActiveSheet()->getStyle("D".$rowidx)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
				$excel->getActiveSheet()->getStyle("A".$rowidx.":D".$rowidx)->getAlignment()->setWrapText(true);
				$excel->getActiveSheet()->getStyle("A".$rowidx.":D".$rowidx)->getAlignment()->setVertical(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
				$rowidx++;
			
				
			}
			for ($i=0;$i < count($colno);$i++) {
				$excel->getActiveSheet()->getColumnDimension($colno[$i])->setAutoSize(true);
			}
			$excel->getActiveSheet()->setTitle("Consultant Activity");
			$excel->setActiveSheetIndex(0);
			
			if ($expfile == "")
				$expfile = "ConsultantActivity_" . date('YmdHis') . ".xlsx" ;
				
			header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8');
			header('Content-Disposition: attachment;filename=' . $expfile);
			header('Cache-Control: max-age=0');
			header('Content-Transfer-Encoding: binary');  
			ob_end_clean(); 
			$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
			$objWriter->save('php://output');	
			} else {
				echo "<tr><td colspan='7'>Consultant activity not found.</td></tr>" ;
				return;
			}
			
			unset($rows) ;
			unset($cls) ;
			
		
	}
	private function getConsultantName() {
		$vls = $this->getValueList(UserTable::C_TABLE, UserTable::C_ID, UserTable::C_NAME,array('code'=>'0','desc'=>'--- Select a Consultant ---')) ;
		return Util::createOptionValue($vls) ;
	}

	private function getJobOption() {
		$vls = $this->getValueList(JobCentreTable::C_TABLE, JobCentreTable::C_ID, JobCentreTable::C_JOB_NAME,array('code'=>'0','desc'=>'--- Select a Job ---')) ;
		return Util::createOptionValue($vls) ;
	}
}
?>