<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/goods/ItemClass.php") ;

class ItemExport extends ControllerBase {
	private $type = "" ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
		$this->dbrms = $_SESSION[SE_DB_RMS];
		
	}
	function __destruct() {
		unset($this->db) ;
		unset($this->dbrms) ;
	}
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		
		try {
			$this->db->open() ;
			$this->dbrms->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() ;
			$this->dbrms->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			$this->dbrms->close() ;
			die ($e->getMessage()) ;
		}
	}
	private function addRecord($params) {
		
		try {
			$this->db->beginTran() ;
			$lines = $this->getParam($params,'data','');
			if($lines!=''){
				$this->insertItems($lines);
			}
			
			$this->db->commitTran() ;
			$this->sendJsonResponse(Status::Ok,"Item successfully added to the system.","",$this->type);
		} catch (Exception $e) {
			$this->db->rollbackTran() ;
			Log::write('[Item]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
	}
	private function insertItems($data) {
		$cls 		= new ItemClass($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];

		$lines = explode("|",$data) ;
		
		foreach ($lines as $line) {
			$line_item 	= explode("~",$line) ;
			
			$check	= $cls->checkItemCode($line_item[0]);

			if(is_null($check)){
				$datas 		= array() ;
				$datas[] 	= $this->db->fieldValue(ItemTable::C_CODE ,$line_item[0]) ;
				$datas[] 	= $this->db->fieldValue(ItemTable::C_DESC ,$line_item[1]);
				$datas[] 	= $this->db->fieldValue(ItemTable::C_REF ,$line_item[2]);
				$datas[] 	= $this->db->fieldValue(ItemTable::C_BRAND ,$line_item[2]);
				$datas[] 	= $this->db->fieldValue(ItemTable::C_ORG_ID,$orgid) ;
				$datas[] 	= $this->db->fieldValue(ItemTable::C_WS_ID,$ws) ;
				$datas[] 	= $this->db->fieldValue(ItemTable::C_MODIFY_BY,$modifyby) ;
				$datas[] 	= $this->db->fieldValue(ItemTable::C_CREATE_BY,$modifyby) ;
				$datas[] 	= $this->db->fieldValue(ItemTable::C_MODIFY_DATE,$modifydate) ;
				$datas[] 	= $this->db->fieldValue(ItemTable::C_CREATE_DATE,$modifydate) ;
				$cls->addRecord($datas) ;

			}else{
				$datas 		= array() ;
				$datas[] 	= $this->db->fieldValue(ItemTable::C_CODE ,$line_item[0]) ;
				$datas[] 	= $this->db->fieldValue(ItemTable::C_DESC ,$line_item[1]);
				$datas[] 	= $this->db->fieldValue(ItemTable::C_REF ,$line_item[2]);
				$datas[] 	= $this->db->fieldValue(ItemTable::C_BRAND ,$line_item[2]);
				$datas[] 	= $this->db->fieldValue(ItemTable::C_WS_ID,$ws) ;
                $datas[] 	= $this->db->fieldValue(ItemTable::C_MODIFY_BY,$modifyby) ;
                $datas[] 	= $this->db->fieldValue(ItemTable::C_MODIFY_DATE,$modifydate) ;
				$cls->updateRecord($check,$datas) ;
			}
			
		}

		unset($cls) ;
	}

	private function getList($params=null) {
		

		$cls = new ItemClass($this->db, $this->dbrms) ;

		//$cls->refreshSupplierFromSun();
		$filterDesc  = $this->getParam($params,'desc','');
		$filterCode  = $this->getParam($params,'code','');
		$filterBrand = $this->getParam($params,'brand','');

		$rows = $cls->getItemList($filterDesc,$filterCode,$filterBrand);
		$arrList = [];
		if(!is_null($rows) && count($rows)>0){
			foreach ($rows as $i => $row) {
				$arrList[$i]["id"] = $row[ItemTable::C_ID];
				$arrList[$i]["code"] = $row[ItemTable::C_CODE];	
				$arrList[$i]["desc"] = $row[ItemTable::C_DESC];	
				$arrList[$i]["brand"] = $row[ItemTable::C_BRAND];	
				$arrList[$i]["actions"] = '';	
			}
		}

		$rowsRms = $cls->getItemListRms($filterDesc,$filterCode,$filterBrand);

		
		$arrListRms = [];
		if(!is_null($rowsRms) && count($rowsRms)>0){
			foreach ($rowsRms as $i => $row) {
				
				$arrListRms[$i]["action"] = '<label class="kt-checkbox kt-checkbox--single kt-checkbox--brand">
				<input type="checkbox" class="m-checkable itemChecked">
				<span></span>
			</label>';
				$arrListRms[$i]["code"] 	= $row['ItemLookupCode'];	
				$arrListRms[$i]["desc"] 	= $row['Description'];	
				$arrListRms[$i]["brand"] 	= $row['Name'];	
				$arrListRms[$i]["actions"] 	= '';	
			}
		}

		$datas = [];
		$datas = ["itemLocal" => $arrList , "itemRms" => $arrListRms]	;

		$this->sendJsonResponse(Status::Ok,"",$datas,$this->type);
		
		unset($rows) ;
		unset($cls) ;
	}
	private function getRecord($params=null) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new ItemClass($this->db) ;
			$row = $cls->getRecord($id) ;
			if (is_null($row)) {
				$this->sendJsonResponse(Status::Error,"Invalid Item id. Please try again.",$id,$this->type);
			} else {
				$datas = array() ;
				$datas['id'] = $id ;
				$datas['desc'] = $row[ItemTable::C_DESC];
				$datas['code'] = $row[ItemTable::C_CODE];
				$datas['brand'] = $row[ItemTable::C_BRAND];
				$this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
			}
			unset($cls) ;
		} else {
			$this->sendJsonResponse(Status::Error,"Missing Item id. Please try again.","",$this->type);
		}
	}
	private function getView() {
        // Log::write("Item " . $this->getWebPageURL());
		ob_start() ;
		include (PATH_VIEWS . "activity/ItemExportView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}
	private function getReport($params=null) {
		require_once(PATH_LIB . 'ListPdf.php');
	
		$cls = new ItemClass($this->db) ;
		$filter = $this->db->fieldParam(ItemTable::C_ORG_ID) ;
		$params = array() ;
		$params[] = $this->db->valueParam(ItemTable::C_ORG_ID,$_SESSION[SE_ORGID]) ;
		$rows = $cls->getTable($filter,ItemTable::C_ID,$params) ;
	
		$i = 'items';
		$nr = 'newrow';
		$datas = array() ;
		foreach ($rows as $row) {
			$items = array() ;
			$items[$i][] = $this->createPdfItem($row[ItemTable::C_ID],30) ;
			$items[$i][] = $this->createPdfItem($row[ItemTable::C_CODE],120) ;
			$items[$i][] = $this->createPdfItem($row[ItemTable::C_DESC],200) ;
			$items[$i][] = $this->createPdfItem($row[ItemTable::C_BRAND],200) ;
			$items[$nr] = "1";
			$datas[] = $items ;
		}
		$cols = array() ;
		$cols[] = $this->createPdfItem("ID",30,0,"C","B");
		$cols[] = $this->createPdfItem("Code",120,0,"C","B") ;
		$cols[] = $this->createPdfItem("Description",200,0,"C","B") ;
		$cols[] = $this->createPdfItem("Brand",200,0,"C","B") ;
		$pdf = new ListPdf('P');
		$pdf->setCompanyName($_SESSION[SE_ORGNAME]) ;
		$pdf->setReportTitle("Item Listing") ;
		$pdf->setColumnsHeader($cols) ;
		$pdf->render($datas) ;
		$pdf->Output('brand.pdf', 'I');
		unset($rows) ;
		unset($cls) ;
		unset($datas) ;
		unset($params) ;
		unset($items) ;
		unset($cols) ;
	}
}
?>