<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/TaxesTypeClass.php") ;
require_once (PATH_MODELS . "activity/TaxesTypePercentageClass.php") ;

class TaxesType 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_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()) ;
		}
	}
    
	public function addRecord($params) {
		$cls 		= new TaxesTypeClass($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(TaxesTypeTable::C_CODE,$this->getParam($params,'code',"")) ;
		$datas[] = $this->db->fieldValue(TaxesTypeTable::C_GL_CODE,$this->getParam($params,'gl_code',"")) ;
		$datas[] = $this->db->fieldValue(TaxesTypeTable::C_DESC,$this->getParam($params,'desc',"")) ;
		$datas[] = $this->db->fieldValue(TaxesTypeTable::C_DEFAULT_PERCENTAGE,$this->getParam($params,'default_percentage',"0.00")) ;
		$datas[] = $this->db->fieldValue(TaxesTypeTable::C_ORG_ID,$orgid) ;
		$datas[] = $this->db->fieldValue(TaxesTypeTable::C_WS_ID,$ws) ;
		$datas[] = $this->db->fieldValue(TaxesTypeTable::C_MODIFY_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(TaxesTypeTable::C_CREATE_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(TaxesTypeTable::C_MODIFY_DATE,$modifydate) ;
		$datas[] = $this->db->fieldValue(TaxesTypeTable::C_CREATE_DATE,$modifydate) ;
		
		try {
			$id = $cls->addRecord($datas) ;
			if ($id > 0) {
                $this->addTaxesTypesPercentage($id, $this->getParam($params,'percentages',""));
				$this->sendJsonResponse(Status::Ok,"Tax type successfully added to the system.",$id,$this->type);
			} else {
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding new tax type to the system.",$id, $this->type) ;
			}
		} catch (Exception $e) {
			Log::write('[TaxesType]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
	}
	private function updateRecord($params) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new TaxesTypeClass($this->db) ;
            $clsPercentage = new TaxesTypePercentageClass($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(TaxesTypeTable::C_CODE,$this->getParam($params,'code',"")) ;
				$datas[] = $this->db->fieldValue(TaxesTypeTable::C_GL_CODE,$this->getParam($params,'gl_code',"")) ;
				$datas[] = $this->db->fieldValue(TaxesTypeTable::C_DESC,$this->getParam($params,'desc',"")) ;
				$datas[] = $this->db->fieldValue(TaxesTypeTable::C_DEFAULT_PERCENTAGE,$this->getParam($params,'default_percentage',"0.00")) ;
                $datas[] = $this->db->fieldValue(TaxesTypeTable::C_WS_ID,$ws) ;
                $datas[] = $this->db->fieldValue(TaxesTypeTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(TaxesTypeTable::C_MODIFY_DATE,$modifydate) ;
                
				$cls->updateRecord($id,$datas) ;
                
                $clsPercentage->deleteRecord($id);
                $this->addTaxesTypesPercentage($id, $this->getParam($params,'percentages',""));
                
				$this->sendJsonResponse(Status::Ok,"Tax type detail successfully updated to the system.",$id,$this->type) ;
			} catch (Exception $e) {
				Log::write('[TaxesType]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating tax type detail to the system.","",$this->type) ;
			}
			unset($cls) ;
            unset($clsPercentage);
		}else {
			$this->sendJsonResponse(Status::Error,"You must supply the Claim tax type id you wish to update. Please try again.","",$this->type);
		}
	}
	private function deleteRecord($params) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new TaxesTypeClass($this->db) ;
            $clsPercentage = new TaxesTypePercentageClass($this->db);
			try {
				$cls->deleteRecord($id) ; 
                $clsPercentage->deleteRecord($id);
				$this->sendJsonResponse(Status::Ok,"Tax type successfully deleted from the system.","",$this->type);
			} catch (Exception $e) {
				Log::write('[TaxesType]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting tax type record from the system.","",$this->type) ;
			}
			unset($cls) ;
            unset($clsPercentage);
		} else {
			$this->sendJsonResponse(Status::Error,"You must supply the tax type id you wish to delete. Please try again.","",$this->type);
		}
	}
	private function getList($datas=null) {
		// $cls = new TaxesTypeClass($this->db) ;
  //       $clsPercentage = new TaxesTypePercentageClass($this->db);
		// $filter = $this->db->fieldParam(TaxesTypeTable::C_ORG_ID) ;
		// $params = array() ;
		// $params[] = $this->db->valueParam(TaxesTypeTable::C_ORG_ID,$_SESSION[SE_ORGID]) ;
		// $rows = $cls->getTable($filter,TaxesTypeTable::C_DESC,$params) ;
		// $list = "" ;
		// foreach ($rows as $row) {
		// 	$id = $row[TaxesTypeTable::C_ID] ;
		// 	$list .= "<tr>" ;
		// 	$list .= "<td>" . $id . "</td>" ;
		// 	$list .= "<td>" . $row[TaxesTypeTable::C_CODE] . "</td>" ;
		// 	$list .= "<td>" . $row[TaxesTypeTable::C_DESC] . "</td>" ;
		// 	$list .= "<td>" . number_format($row[TaxesTypeTable::C_DEFAULT_PERCENTAGE], 2) . "</td>" ;
            
		// 	$list .= "<td style='text-align:center'><a href='javascript:' onclick='editTaxesType(" . $id . ",this)'><img src='image/edit_16.png' title='Edit'></img></a></td>" ;
		// 	$list .= "<td style='text-align:center'><a href='javascript:' onclick='deleteTaxesType(" . $id . ",this)'><img src='image/delete_16.png' title='Delete'></img></a></td>" ;
		// 	$list .= "</tr>" ;
		// }
		
		// unset($rows) ;
		// unset($cls) ;
  //       unset($clsPercentage);
		// return $list ;

		//=====================================================================

		$cls = new TaxesTypeClass($this->db) ;
        $clsPercentage = new TaxesTypePercentageClass($this->db);

		$filter = $this->db->fieldParam(TaxesTypeTable::C_ORG_ID) ;
		$params = array() ;
		$params[] = $this->db->valueParam(TaxesTypeTable::C_ORG_ID,$_SESSION[SE_ORGID]) ;
		$rows = $cls->getTable($filter,TaxesTypeTable::C_DESC,$params) ;
		$arrList = [];
		foreach ($rows as $i => $row) {
			$arrList[$i]["id"] = $row[TaxesTypeTable::C_ID];
			$arrList[$i]["code"] = $row[TaxesTypeTable::C_CODE];	
			$arrList[$i]["desc"] = $row[TaxesTypeTable::C_DESC];	
			$arrList[$i]["default"] = number_format($row[TaxesTypeTable::C_DEFAULT_PERCENTAGE], 2);	
			$arrList[$i]["actions"] = '<a onclick="javascript:editTaxesType('. $row[TaxesTypeTable::C_ID] .',this);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="Edit details">
									  	<i class="fa fa-edit"></i>
									  </a>
									  <a onclick="javascript:deleteTaxesType('. $row[TaxesTypeTable::C_ID] .',this);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="Delete">
									  	<i class="fa fa-trash"></i>
									  </a>';	
		}

		$this->sendJsonResponse(Status::Ok,"",$arrList,$this->type);
		
		unset($rows) ;
		unset($cls) ;
	}
	private function getRecord($params=null) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new TaxesTypeClass($this->db) ;
            $clsPercentage = new TaxesTypePercentageClass($this->db);
			$row = $cls->getRecord($id) ;
			if (is_null($row)) {
				$this->sendJsonResponse(Status::Error,"Invalid tax type id. Please try again.",$id,$this->type);
			} else {
				$datas = array() ;
				$datas['id'] = $id ;
				$datas['code'] = $row[TaxesTypeTable::C_CODE];
				$datas['gl_code'] = $row[TaxesTypeTable::C_GL_CODE];
				$datas['desc'] = $row[TaxesTypeTable::C_DESC];
				$datas['default_percentage'] = number_format($row[TaxesTypeTable::C_DEFAULT_PERCENTAGE], 2) ;
            
                $rows_percentage = $clsPercentage->getPercentages($id);
                if(!is_null($rows_percentage) && count($rows_percentage) > 0){
                    $result = "";
                    foreach($rows_percentage as $row_percentage){
                        $dte = new DateTime($row_percentage[TaxesTypePercentageTable::C_START_DATE]);
                        $result .= number_format($row_percentage[TaxesTypePercentageTable::C_PERCENTAGE], 2) . "~" . 
                                    $dte->format("d/m/Y") . "|";
                    }
                    $datas['percentages'] = $result;
                } else {
                    $datas['percentages'] = "";
                }
                
				$this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
			}
			unset($cls) ;
			unset($clsPercentage) ;
		} else {
			$this->sendJsonResponse(Status::Error,"Missing tax type id. Please try again.","",$this->type);
		}
	}
	private function getView() {
		ob_start() ;
		include (PATH_VIEWS . "activity/TaxesTypeView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}
	private function getReport($params=null) {
		require_once(PATH_LIB . 'ListPdf.php');
	
		$cls = new TaxesTypeClass($this->db) ;
		$filter = $this->db->fieldParam(TaxesTypeTable::C_ORG_ID) ;
		$params = array() ;
		$params[] = $this->db->valueParam(TaxesTypeTable::C_ORG_ID,$_SESSION[SE_ORGID]) ;
		$rows = $cls->getTable($filter,TaxesTypeTable::C_ID,$params) ;
	
		$i = 'items';
		$nr = 'newrow';
		$datas = array() ;
		foreach ($rows as $row) {
			$items = array() ;
			$items[$i][] = $this->createPdfItem($row[TaxesTypeTable::C_ID],30) ;
			$items[$i][] = $this->createPdfItem($row[TaxesTypeTable::C_DESC],200) ;
			$items[$nr] = "1";
			$datas[] = $items ;
		}
		$cols = array() ;
		$cols[] = $this->createPdfItem("ID",30,0,"C","B");
		$cols[] = $this->createPdfItem("Description",200,0,"C","B") ;
		$pdf = new ListPdf('P');
		$pdf->setCompanyName($_SESSION[SE_ORGNAME]) ;
		$pdf->setReportTitle("TaxesType Listing") ;
		$pdf->setColumnsHeader($cols) ;
		$pdf->render($datas) ;
		$pdf->Output('TaxesType.pdf', 'I');
		unset($rows) ;
		unset($cls) ;
		unset($datas) ;
		unset($params) ;
		unset($items) ;
		unset($cols) ;
	}
    
    private function addTaxesTypesPercentage($id, $percentages){
		$cls = new TaxesTypePercentageClass($this->db) ;
		if ($percentages != "") {
			$lines = explode("|",$percentages) ;
			for ($i= 0;$i < count($lines) ;$i++) {
				$line = explode("~",$lines[$i]) ;
				if (count($line) == 2) {
					if (is_numeric($line[1])) {
						
						$datas = array() ;
						$datas[] = $this->db->fieldValue(TaxesTypePercentageTable::C_ID,$id);
						$datas[] = $this->db->fieldValue(TaxesTypePercentageTable::C_PERCENTAGE,$line[1]) ;
                        
                        $dte = explode("/", $line[0]);
                        if (count($dte) == 3) {
                            $d = $dte[0] ;
                            $m = $dte[1] ;
                            $y = $dte[2] ;
                            if (checkdate($m,$d,$y)){
                                $datas[] = $this->db->fieldValue(TaxesTypePercentageTable::C_START_DATE,$y . "-" . $m . "-" . $d ) ;
                            }
                        }
						
						$cls->addRecord($datas) ;
					}
				}
			}
		}
		unset($cls) ;
    }
}
?>