<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/salestarget/SalesTargetClass.php");

class PortalSalesTarget extends ActivityBase {

	function __construct() {
		$this->db 		= $_SESSION[SE_DB] ;
		$this->orgid 	= $_SESSION[SE_ORGID] ;
		$this->fldorg   = SalesTargetTable::C_ORG_ID ;
	}
	
	function __destruct() {
		unset($this->db) ;
	}
	
	public function processRequest($params) {
		$this->type = Command::PortalSalesTargetView ;
		try {
			$this->db->open() ;
			$this->loadSetting() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
            }

			switch ($this->type) {
                case Command::PortalSalesTargetView:
                    $this->processView($params) ;
                    break ;
                case Command::PortalSalesTargetAdd:
                    $this->addRecord($params) ;
                    break ;
                case Command::PortalSalesTargetUpdate:
                    $this->updateRecord($params) ;
                    break ;
                case Command::PortalSalesTargetGet:
                    $this->getRecord($params) ;
                    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 processView($params) {
        ob_start() ; 
        include (PATH_VIEWS . "portal/salestarget/SalesTargetAddView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  $var_screen;
        $dataReturn['headTitle']    =  "Sales Target" ;

        $this->sendJsonResponse(Status::Ok,"Sales Target",$dataReturn,$this->type);
    }

	private function addRecord($params) {
        $cls = new SalesTargetClass($this->db) ;

        $datas      = array() ;
        $dataReturn = 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(SalesTargetTable::C_YEAR,$this->getParamInt($params,'year',0)) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_BU,$this->getParamInt($params,'bu',0)) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_TOTAL,floatVal(str_replace(",", "", $this->getParam($params,'total',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_1,floatVal(str_replace(",", "", $this->getParam($params,'jan',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_2,floatVal(str_replace(",", "", $this->getParam($params,'feb',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_3,floatVal(str_replace(",", "", $this->getParam($params,'mar',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_4,floatVal(str_replace(",", "", $this->getParam($params,'apr',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_5,floatVal(str_replace(",", "", $this->getParam($params,'may',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_6,floatVal(str_replace(",", "", $this->getParam($params,'jun',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_7,floatVal(str_replace(",", "", $this->getParam($params,'jul',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_8,floatVal(str_replace(",", "", $this->getParam($params,'aug',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_9,floatVal(str_replace(",", "", $this->getParam($params,'sep',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_10,floatVal(str_replace(",", "", $this->getParam($params,'oct',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_11,floatVal(str_replace(",", "", $this->getParam($params,'nov',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_12,floatVal(str_replace(",", "", $this->getParam($params,'dec',"0")))) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_ORG_ID,$orgid) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_WS_ID,$ws) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MODIFY_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_CREATE_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_MODIFY_DATE,$modifydate) ;
        $datas[] = $this->db->fieldValue(SalesTargetTable::C_CREATE_DATE,$modifydate) ;
        
        try {
            $this->db->beginTran();
            $id = $cls->addRecord($datas) ;
            if ($id > 0) {
                $this->db->commitTran();
				$this->sendJsonResponse(Status::Ok,"Sales Target successfully saved to the system.",$id,$this->type);
			} else {
                $this->db->rollbackTran();
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding new Sales Target to the system.",$dataReturn, $this->type) ;
			}
		} catch (Exception $e) {
            $this->db->rollbackTran();
			Log::write('[SalesTarget]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
    }

	private function updateRecord($params) {
		// log::write($params);
		if(isset($params['id'])){
			$id = $params['id'];
			$cls = new SalesTargetClass($this->db) ;

			$datas      = array() ;
			$dataReturn = 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(SalesTargetTable::C_YEAR,$this->getParamInt($params,'year',0)) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_BU,$this->getParamInt($params,'bu',0)) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_TOTAL,floatVal(str_replace(",", "", $this->getParam($params,'total',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_1,floatVal(str_replace(",", "", $this->getParam($params,'jan',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_2,floatVal(str_replace(",", "", $this->getParam($params,'feb',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_3,floatVal(str_replace(",", "", $this->getParam($params,'mar',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_4,floatVal(str_replace(",", "", $this->getParam($params,'apr',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_5,floatVal(str_replace(",", "", $this->getParam($params,'may',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_6,floatVal(str_replace(",", "", $this->getParam($params,'jun',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_7,floatVal(str_replace(",", "", $this->getParam($params,'jul',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_8,floatVal(str_replace(",", "", $this->getParam($params,'aug',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_9,floatVal(str_replace(",", "", $this->getParam($params,'sep',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_10,floatVal(str_replace(",", "", $this->getParam($params,'oct',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_11,floatVal(str_replace(",", "", $this->getParam($params,'nov',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MONTH_12,floatVal(str_replace(",", "", $this->getParam($params,'dec',"0")))) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_ORG_ID,$orgid) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_WS_ID,$ws) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MODIFY_BY,$modifyby) ;
			$datas[] = $this->db->fieldValue(SalesTargetTable::C_MODIFY_DATE,$modifydate) ;
			
			try {
				$cls->updateRecord($id, $datas);
				$this->sendJsonResponse(Status::Ok,"Sales Target successfully saved to the system.",$id,$this->type);
			} catch (Exception $e) {
				Log::write('[SalesTarget]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
			}
			unset($cls) ;
		} else {
			Log::write('[SalesTarget]' . "Missing sales target id.");
			$this->sendJsonResponse(Status::Error,"Please provide the sales target id that you wish to update.","",$this->type) ;
		}
    }

	private function getRecord($params) {
		// log::write($params);
		if(isset($params['id'])){
			$id = $params['id'];
			$cls = new SalesTargetClass($this->db) ;
			
			try {
				$filter = SalesTargetTable::C_BU." = ".$this->getParamInt($params, 'bu', 0)." AND ".SalesTargetTable::C_YEAR." = ".$this->getParamInt($params, 'year', 0);
				$rows = $cls->getTable($filter);
				if (!is_null($rows) && count($rows) > 0) {
					$dataReturn = array();
					foreach($rows as $row){
						$dataReturn['id'] 		= $row[SalesTargetTable::C_ID];
						$dataReturn['bu'] 		= $row[SalesTargetTable::C_BU];
						$dataReturn['year'] 	= $row[SalesTargetTable::C_YEAR];
						$dataReturn['total'] 	= number_format($row[SalesTargetTable::C_TOTAL], 2, '.', ',');
						$dataReturn['jan'] 		= number_format($row[SalesTargetTable::C_MONTH_1], 2, '.', ',');
						$dataReturn['feb'] 		= number_format($row[SalesTargetTable::C_MONTH_2], 2, '.', ',');
						$dataReturn['mar'] 		= number_format($row[SalesTargetTable::C_MONTH_3], 2, '.', ',');
						$dataReturn['apr'] 		= number_format($row[SalesTargetTable::C_MONTH_4], 2, '.', ',');
						$dataReturn['may'] 		= number_format($row[SalesTargetTable::C_MONTH_5], 2, '.', ',');
						$dataReturn['jun'] 		= number_format($row[SalesTargetTable::C_MONTH_6], 2, '.', ',');
						$dataReturn['jul'] 		= number_format($row[SalesTargetTable::C_MONTH_7], 2, '.', ',');
						$dataReturn['aug'] 		= number_format($row[SalesTargetTable::C_MONTH_8], 2, '.', ',');
						$dataReturn['sep'] 		= number_format($row[SalesTargetTable::C_MONTH_9], 2, '.', ',');
						$dataReturn['oct'] 		= number_format($row[SalesTargetTable::C_MONTH_10], 2, '.', ',');
						$dataReturn['nov'] 		= number_format($row[SalesTargetTable::C_MONTH_11], 2, '.', ',');
						$dataReturn['dec'] 		= number_format($row[SalesTargetTable::C_MONTH_12], 2, '.', ',');
					}

					$this->sendJsonResponse(Status::Ok,"Sales Target successfully retrieved to the system.",$dataReturn,$this->type);
				} 
				else {
					$this->sendJsonResponse(Status::Error,"No record found.","",$this->type) ;
				}
			} catch (Exception $e) {
				$this->db->rollbackTran();
				Log::write('[SalesTarget]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
			}
			unset($cls) ;
		} else {
			Log::write('[SalesTarget]' . "Missing sales target id.");
			$this->sendJsonResponse(Status::Error,"Please provide the sales target id that you wish to retrieve.","",$this->type) ;
		}
    }
}
?>