<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/CustomerClass.php") ;
require_once (PATH_MODELS . "activity/CustomerContactClass.php") ;

class Customer extends ActivityBase {
	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()) ;
		}
	}
	private function addRecord($params) {
		$cls 		= 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(CustomerTable::C_NAME,$this->getParam($params,'name',"")) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_CODE,$this->getParam($params,'code',"")) ;
		// $datas[] = $this->db->fieldValue(CustomerTable::C_EMAIL,$this->getParam($params,'email',"")) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_FAX,$this->getParam($params,'fax',"")) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_TELEPHONE,$this->getParam($params,'telephone',"")) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_WEB,$this->getParam($params,'web',"")) ;
		// $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_LINE_1,$this->getParam($params,'address_line_1',"")) ;
		// $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_LINE_2,$this->getParam($params,'address_line_2',"")) ;
		// $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_LINE_3,$this->getParam($params,'address_line_3',"")) ;
		// $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_LINE_4,$this->getParam($params,'address_line_4',"")) ;
		// $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_LINE_5,$this->getParam($params,'address_line_5',"")) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_ORG_ID,$orgid) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_WS_ID,$ws) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_MODIFY_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_CREATE_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_MODIFY_DATE,$modifydate) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_CREATE_DATE,$modifydate) ;

		$customerContacts = $this->getParam($params,'customer_contact',"") ;
       		
		try {
			$id = $cls->addRecord($datas) ;
			if ($id > 0) {
				$this->addCustomerContacts($id,$customerContacts) ;
				$this->sendJsonResponse(Status::Ok,"Customer successfully added to the system.",$id,$this->type);
			} else {
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding new customer 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 updateRecord($params) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new CustomerClass($this->db) ;
			$clsContact = new CustomerContactClass($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(CustomerTable::C_NAME,$this->getParam($params,'name',"")) ;
                $datas[] = $this->db->fieldValue(CustomerTable::C_CODE,$this->getParam($params,'code',"")) ;
                // $datas[] = $this->db->fieldValue(CustomerTable::C_EMAIL,$this->getParam($params,'email',"")) ;
                $datas[] = $this->db->fieldValue(CustomerTable::C_FAX,$this->getParam($params,'fax',"")) ;
                $datas[] = $this->db->fieldValue(CustomerTable::C_TELEPHONE,$this->getParam($params,'telephone',"")) ;
                $datas[] = $this->db->fieldValue(CustomerTable::C_WEB,$this->getParam($params,'web',"")) ;
                // $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_LINE_1,$this->getParam($params,'address_line_1',"")) ;
                // $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_LINE_2,$this->getParam($params,'address_line_2',"")) ;
                // $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_LINE_3,$this->getParam($params,'address_line_3',"")) ;
                // $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_LINE_4,$this->getParam($params,'address_line_4',"")) ;
                // $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_LINE_5,$this->getParam($params,'address_line_5',"")) ;
                $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) ;
                
				$customerContacts = $this->getParam($params,'customer_contact',"") ;
				$clsContact->deleteRecord($id);
				$this->addCustomerContacts($id,$customerContacts) ;
                
				$cls->updateRecord($id,$datas) ;
              
				$this->sendJsonResponse(Status::Ok,"Customer detail successfully updated to the system.",$id,$this->type) ;
			} catch (Exception $e) {
				Log::write('[Customer]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating customer detail to the system.","",$this->type) ;
			}
			unset($cls) ;
			unset($clsContact) ;
            unset($clsItem);
		}else {
			$this->sendJsonResponse(Status::Error,"You must supply the customer id you wish to update. Please try again.","",$this->type);
		}
	}
	private function deleteRecord($params) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new CustomerClass($this->db) ;
			$clsContact = new CustomerContactClass($this->db);

           
			try {
				$cls->deleteRecord($id) ; 
               	$clsContact->deleteRecord($id);
				$this->sendJsonResponse(Status::Ok,"Customer successfully deleted from the system.","",$this->type);
			} catch (Exception $e) {
				Log::write('[Customer]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting Customer record from the system.","",$this->type) ;
			}
			unset($cls) ;
			unset($clsContact) ;
		} else {
			$this->sendJsonResponse(Status::Error,"You must supply the customer id you wish to delete. Please try again.","",$this->type);
		}
	}
	private function getList($datas=null) {
		$cls = new CustomerClass($this->db) ;
        
		$filter = $this->db->fieldParam(CustomerTable::C_ORG_ID) ;
		$params = array() ;
		$params[] = $this->db->valueParam(CustomerTable::C_ORG_ID,$_SESSION[SE_ORGID]) ;
		$rows = $cls->getTable($filter,CustomerTable::C_CODE,$params) ;
		$list = "" ;
		foreach ($rows as $row) {
			$id = $row[CustomerTable::C_ID] ;
			$list .= "<tr>" ;
			$list .= "<td>" . $id . "</td>" ;
			$list .= "<td>" . trim($row[CustomerTable::C_CODE]) . "</td>" ;
			$list .= "<td>" . trim($row[CustomerTable::C_NAME]) . "</td>" ;
			$list .= "<td style='text-align:center'><a href='javascript:' onclick='editCustomer(" . $id . ",this)'><img src='image/edit_16.png' title='Edit'></img></a></td>" ;
			$list .= "<td style='text-align:center'><a href='javascript:' onclick='deleteCustomer(" . $id . ",this)'><img src='image/delete_16.png' title='Delete'></img></a></td>" ;
			$list .= "</tr>" ;
		}
		
		unset($rows) ;
		unset($cls) ;
		return $list ;
	}
	private function getRecord($params=null) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new CustomerClass($this->db) ;
			$row = $cls->getRecord($id) ;
			if (is_null($row)) {
				$this->sendJsonResponse(Status::Error,"Invalid Customer id. Please try again.",$id,$this->type);
			} else {
				$datas = array() ;
                
				$datas['id'] = $id ;
				$datas['name'] = $row[CustomerTable::C_NAME];
				$datas['code'] = $row[CustomerTable::C_CODE];
				// $datas['email'] = $row[CustomerTable::C_EMAIL];
				$datas['fax'] = $row[CustomerTable::C_FAX];
				$datas['telephone'] = $row[CustomerTable::C_TELEPHONE];
				$datas['web'] = $row[CustomerTable::C_WEB];
				// $datas['address_line_1'] = $row[CustomerTable::C_ADDRESS_LINE_1];
				// $datas['address_line_2'] = $row[CustomerTable::C_ADDRESS_LINE_2];
				// $datas['address_line_3'] = $row[CustomerTable::C_ADDRESS_LINE_3];
				// $datas['address_line_4'] = $row[CustomerTable::C_ADDRESS_LINE_4];
				// $datas['address_line_5'] = $row[CustomerTable::C_ADDRESS_LINE_5];

				$datas['customer_contact'] = $this->getCustomerContacts($id);
                                
				$this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
			}
			unset($cls) ;
		} else {
			$this->sendJsonResponse(Status::Error,"Missing Customer id. Please try again.","",$this->type);
		}
	}
	private function getView() {
		ob_start() ;
		include (PATH_VIEWS . "activity/CustomerView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}
    
    
	private function getReport($params=null) {
		require_once(PATH_LIB . 'ListPdf.php');
	
		$cls = new CustomerClass($this->db) ;
		$filter = $this->db->fieldParam(CustomerTable::C_ORG_ID) ;
		$params = array() ;
		$params[] = $this->db->valueParam(CustomerTable::C_ORG_ID,$_SESSION[SE_ORGID]) ;
		$rows = $cls->getTable($filter,CustomerTable::C_ID,$params) ;
	
		$i = 'items';
		$nr = 'newrow';
		$datas = array() ;
		foreach ($rows as $row) {
			$items = array() ;
			$items[$i][] = $this->createPdfItem($row[CustomerTable::C_ID],30) ;
			$items[$i][] = $this->createPdfItem($row[CustomerTable::C_CODE],100) ;
			$items[$i][] = $this->createPdfItem($row[CustomerTable::C_NAME],200) ;
			$items[$nr] = "1";
			$datas[] = $items ;
		}
		$cols = array() ;
		$cols[] = $this->createPdfItem("ID",30,0,"C","B");
		$cols[] = $this->createPdfItem("Code",100,0,"C","B") ;
		$cols[] = $this->createPdfItem("Name",200,0,"C","B") ;
		$pdf = new ListPdf('P');
		$pdf->setCompanyName($_SESSION[SE_ORGNAME]) ;
		$pdf->setReportTitle("Customer Listing") ;
		$pdf->setColumnsHeader($cols) ;
		$pdf->render($datas) ;
		$pdf->Output('Customer.pdf', 'I');
		unset($rows) ;
		unset($cls) ;
		unset($datas) ;
		unset($params) ;
		unset($items) ;
		unset($cols) ;
	}

	private function addCustomerContacts($id, $customerContacts) {
		$cls = new CustomerContactClass($this->db) ;
		if ($customerContacts != "") {
			$lines = explode("|",$customerContacts) ;
			for ($i= 0;$i < count($lines) ;$i++) {
				$line = explode("~",$lines[$i]) ;
				if (count($line) == 4) {
                    $datas = array() ;
                    $datas[] = $this->db->fieldValue(CustomerContactTable::C_ID,$id);
                    $datas[] = $this->db->fieldValue(CustomerContactTable::C_NAME,$line[0]) ;
                    // $datas[] = $this->db->fieldValue(CustomerContactTable::C_EMAIL,$line[1]) ;
                    $datas[] = $this->db->fieldValue(CustomerContactTable::C_TELEPHONE,$line[2]);
                    $datas[] = $this->db->fieldValue(CustomerContactTable::C_FAX,$line[3]);

                    $cls->addRecord($datas) ;
				}
			}
		}
		unset($cls) ;
	}

	private function getCustomerContacts($id) {
		$cls = new CustomerContactClass($this->db) ;
		$rows = $cls->getCustomerContact($id) ;
		$lines = "" ;
		if (!is_null($rows) || count($rows) > 0) {
			foreach ($rows as $row) {
                
                if (strlen($lines) > 0){
					$lines .= "|" ;
                }
				$lines .= $row[CustomerContactTable::C_NAME] . "~" . 
                            // $row[CustomerContactTable::C_EMAIL] . "~" . 
                            $row[CustomerContactTable::C_TELEPHONE] . "~" . 
                            $row[CustomerContactTable::C_FAX] ;
			}							
        }
		unset($cls) ;
		return $lines ;
	}
	
}
?>