<?php
include (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "prospect/PersonContactClass.php") ;
require_once (PATH_MODELS . "prospect/ProspectClass.php") ;
require_once (PATH_MODELS . "prospect/ProspectContactClass.php") ;
require_once (PATH_MODELS . "prospect/ProspectConversationClass.php") ;
require_once (PATH_MODELS . "admin/UserClass.php") ;
require_once (PATH_MODELS . "admin/UserResetPasswordHistoryClass.php") ;
require_once (PATH_MODELS . "admin/UserPasswordHistoryClass.php") ;
require_once(PATH_MODELS . "admin/UserGroupClass.php");
require_once(PATH_MODELS . "admin/UserRight.php");
require_once (PATH_LIB . "LicenseFile.php") ;

class Account extends MobileBase {
	private $clsuser ;
	private $type ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
		$this->clsuser = new UserClass($this->db) ;

	}
	function __destruct() {
		unset($this->clsuser) ;

	}
	public function processRequest($params) {
		log::write("Account::processRequest".json_encode($params)) ;
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
			$isTurnOff = false;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			if (!$this->checkSessionTimeout($this->type)) {
				$this->db->close();
				return false;
			}

			switch ($this->type) {
				case REQ_ADD:
					$this->addRecord($params) ;
					break ;
				case REQ_UPDATE:
					$this->updateRecord($params) ;
					break ;
				case "ACCOUNT_NAME_SEARCH":
					$this->getAccountList($params) ;
					break ;
				case "GET_ACCOUNT_INFO":
					$this->getAccountDetail($params) ;
					break ;
				case REQ_VIEW:
					$this->processView() ;
					break ;
				default:
					$this->sendJsonResponse(Status::Error,"Invalid request.","") ;
					break ;
			}
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
	}

	private function processView() {
		ob_start() ;
		include (PATH_VIEWS . "mobile/account/AccountView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}

	private function getAccountDetail($params){
        $cls 	= new ProspectClass($this->db) ;
        try {
			$rows 	= $cls->getProspectAndContact($params['account_name']);
            $data = [];
            if (!is_null($rows)) {
				$data['account_flag'] = $rows[0][ProspectTable::C_FLAG];
				$data['name']		= $rows[0][ProspectTable::C_NAME];
				$data['id']			= $rows[0][ProspectTable::C_ID];
				$data['category']	= $rows[0][ProspectTable::C_SALES_STATUS2];
				$data['status']		= $rows[0][ProspectTable::C_COMPANY_STATUS];
				$data['office']		= $rows[0][ProspectTable::C_TELEPHONE];
				$data['mobile']		= $rows[0][ProspectTable::C_TELEPHONE2];
				$data['email']		= $rows[0][ProspectTable::C_COMPANY_EMAIL];
				$data['address']	= $rows[0][ProspectTable::C_ADDRESS_1];
				$data['contact']	= [];
                foreach ($rows as $row) {
					$contact_prefer = [];
					if($row[PersonContactTable::C_PREFER_WHATSAPP] == 1){
						array_push($contact_prefer, 1);
					}
					if($row[PersonContactTable::C_PREFER_TELEGRAM] == 1){
						array_push($contact_prefer, 2);
					}
					if($row[PersonContactTable::C_PREFER_EMAIL] == 1){
						array_push($contact_prefer, 3);
					}
					if($row[PersonContactTable::C_PREFER_TELEPHONE] == 1){
						array_push($contact_prefer, 4);
					}
					if($row[PersonContactTable::C_PREFER_PROMOTION] == 1){
						array_push($contact_prefer, 5);
					}
					$contact = [];
					$contact['contact_id']			= $row[ProspectContactTable::C_CONTACT_ID];
					$contact['person_id']			= $row[PersonContactTable::C_ID];
					$contact['contact_name']		= $row[PersonContactTable::C_FULL_NAME];
					$contact['contact_designation']	= $row[ProspectContactTable::C_DESIGNATION];
					$contact['contact_dept']		= $row[ProspectContactTable::C_DEPT];
					$contact['contact_report_to']	= $row[ProspectContactTable::C_REPORT_TO];
					$contact['contact_email']		= $row[PersonContactTable::C_EMAIL];
					$contact['contact_phone']		= $row[PersonContactTable::C_TELEPHONE];
					$contact['contact_prefer']		= $contact_prefer;
					$contact['contact_comment']		= $row[PersonContactTable::C_COMMENT];

					array_push($data['contact'], $contact);
                }
            }
			$this->sendJsonResponse(Status::Ok,"",$data,$this->type);
        } catch (Exception $e) {
            Log::write('[getAccount]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"","",$this->type) ;
        }
    }

	private function getAccountList($params=null){
        $cls = new ProspectClass($this->db) ;
		$clsGroup = new UserGroupClass($this->db);
		$clsRight = new UserRight();

        try {
			$row_group = $clsGroup->getRecord($_SESSION[SE_USERGROUP]);
			
			if (is_null($row_group[UserGroupTable::C_RIGHTS]))
				$clsRight->initRights();
			else {
				$clsRight->toRights($row_group[UserGroupTable::C_RIGHTS]);
			}
			$rights = $clsRight->getAdminRights();
			
			$filter = "";
			if(isset($params['account_flag'])) {
				$filter = $params['account_flag'] != "" ? ProspectTable::C_FLAG . " = '" . $params['account_flag'] . "'" : "";
			}

			if ($rights[UserRight::C_MARKETING_VIEW_OTHERS][UserRight::C_ENABLE] == 0 && $rights[UserRight::C_SALES_VIEW_OTHERS][UserRight::C_ENABLE] == 0) {
				$created_by  = $_SESSION[SE_USERID];
				$filter .= ProspectTable::C_CREATE_BY . " = " . $created_by . " ";
			}
			
            $rows = $cls->getTable($filter);
            $data = [];
            if (!is_null($rows)) {
                foreach ($rows as $row) {
					if (trim($row[ProspectTable::C_NAME]) != "") {
						array_push($data,trim("".$row[ProspectTable::C_NAME].""));
					}
                }
            }
			$this->sendJsonResponse(Status::Ok,"",$data,$this->type);
        } catch (Exception $e) {
            Log::write('[getAccountList]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"","",$this->type) ;
        }
    }

	private function addRecord($params) {
		$clsProspect 		= new ProspectClass($this->db) ;
		$clsPerson 			= new PersonContactClass($this->db) ;
		$clsContact 		= new ProspectContactClass($this->db) ;
		
		$modifyby 		= $_SESSION[SE_USERID] ;
		$modifydate 	= date_create('now')->format('Y-m-d H:i:s') ;

		if($clsProspect->isDescDuplicate($params['name'])){
			$this->sendJsonResponse(Status::Error,"Account name exist in the system.","",$this->type);
			return;
		}
		try {
			$this->db->beginTran();
			$datas_prospect   = array() ;
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_FLAG, $this->getParam($params,'account_flag',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_NAME, $this->getParam($params,'name',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_SALES_STATUS2, $this->getParam($params,'category',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_COMPANY_STATUS,$this->getParam($params,'status',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_TELEPHONE, $this->getParam($params,'office',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_TELEPHONE2, $this->getParam($params,'mobile',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_COMPANY_EMAIL, $this->getParam($params,'email',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_ADDRESS_1, $this->getParam($params,'address',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_CREATE_BY, $modifyby);
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_CREATE_DATE, $modifydate);
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_MODIFY_BY, $modifyby);
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_MODIFY_DATE, $modifydate);
			$prospect_id 	  = $clsProspect->addRecord($datas_prospect);

			$contacts = $params['contact'];
			foreach($contacts as $contact){
				$contact_prefers = $contact['contact_pref'];
				$prefer_whatsapp	= 0;
				$prefer_telegram	= 0;
				$prefer_email		= 0;
				$prefer_call		= 0;
				$prefer_promotion	= 0;

				if(!is_null($contact_prefers) && count($contact_prefers) > 0){
					foreach($contact_prefers as $contact_prefer){
						if($contact_prefer == 1){
							$prefer_whatsapp = 1;
						}
						if($contact_prefer == 2){
							$prefer_telegram = 1;
						}
						if($contact_prefer == 3){
							$prefer_email = 1;
						}
						if($contact_prefer == 4){
							$prefer_call = 1;
						}
						if($contact_prefer == 5){
							$prefer_promotion = 1;
						}
					}
				}
				$datas_person 	= array();
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_FULL_NAME,$this->getParam($contact,'contact_name',""));
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_NAME,$this->getParam($contact,'contact_name',""));
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_TELEPHONE,$this->getParam($contact,'contact_phone',""));
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_EMAIL,$this->getParam($contact,'contact_email',""));
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_COMMENT,$this->getParam($contact,'contact_comment',""));
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_PROMOTION,$prefer_promotion);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_WHATSAPP,$prefer_whatsapp);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_TELEGRAM,$prefer_telegram);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_EMAIL,$prefer_email);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_TELEPHONE,$prefer_call);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_CREATE_BY, $modifyby);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_CREATE_DATE, $modifydate);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_MODIFY_BY, $modifyby);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_MODIFY_DATE, $modifydate);
				$person_id 	 	= $clsPerson->addRecord($datas_person);

				$datas_contact 	 = array();
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_ID,$prospect_id) ;
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_PERSON_CONTACT,$person_id) ;
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_DESIGNATION,$this->getParam($contact,'contact_designation',"")) ;
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_DEPT,$this->getParam($contact,'contact_dept',"")) ;
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_REPORT_TO,$this->getParam($contact,'contact_report_to',"")) ;
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_CREATE_BY, $modifyby);
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_CREATE_DATE, $modifydate);
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_MODIFY_BY, $modifyby);
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_MODIFY_DATE, $modifydate);
				$clsContact->addRecord($datas_contact);
			}


			$this->db->commitTran();
			$this->sendJsonResponse(Status::Ok,"Account successfully added to the system.","",$this->type);
		} catch (Exception $e) {
			$this->db->rollbackTran();
			Log::write('[Account]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
	}

	private function updateRecord($params) {
		$clsProspect 		= new ProspectClass($this->db) ;
		$clsPerson 			= new PersonContactClass($this->db) ;
		$clsContact 		= new ProspectContactClass($this->db) ;

		$modifyby 			= $_SESSION[SE_USERID] ;
		$modifydate 		= date_create('now')->format('Y-m-d H:i:s') ;

		$prospect_id 		= $params['id'];

		if($clsProspect->isDescDuplicate($params['name'], $prospect_id)){
			$this->sendJsonResponse(Status::Error,"Account already exist in the system","",$this->type);
			return;
		}
		try {
			$this->db->beginTran();
			$datas_prospect   = array() ;
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_FLAG, $this->getParam($params,'account_flag',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_NAME, $this->getParam($params,'name',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_SALES_STATUS2, $this->getParam($params,'category',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_COMPANY_STATUS,$this->getParam($params,'status',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_TELEPHONE, $this->getParam($params,'office',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_TELEPHONE2, $this->getParam($params,'mobile',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_COMPANY_EMAIL, $this->getParam($params,'email',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_ADDRESS_1, $this->getParam($params,'address',""));
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_MODIFY_BY, $modifyby);
			$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_MODIFY_DATE, $modifydate);
			$clsProspect->updateRecord($prospect_id, $datas_prospect);

			$contacts = $params['contact'];
			$contact_ids = "";
			foreach($contacts as $contact){
				$contact_prefers 	= $contact['contact_prefer'];
				$contact_id 		= $contact['contact_id'];
				$contact_person_id 	= $contact['contact_person_id'];

				$prefer_whatsapp	= 0;
				$prefer_telegram	= 0;
				$prefer_email		= 0;
				$prefer_call		= 0;
				$prefer_promotion	= 0;
				foreach($contact_prefers as $contact_prefer){
					if($contact_prefer == 1){
						$prefer_whatsapp = 1;
					}
					if($contact_prefer == 2){
						$prefer_telegram = 1;
					}
					if($contact_prefer == 3){
						$prefer_email = 1;
					}
					if($contact_prefer == 4){
						$prefer_call = 1;
					}
					if($contact_prefer == 5){
						$prefer_promotion = 1;
					}
				}				
				$datas_person 	= array();
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_FULL_NAME,$this->getParam($contact,'contact_name',""));
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_NAME,$this->getParam($contact,'contact_name',""));
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_TELEPHONE,$this->getParam($contact,'contact_phone',""));
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_EMAIL,$this->getParam($contact,'contact_email',""));
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_COMMENT,$this->getParam($contact,'contact_comment',""));
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_PROMOTION,$prefer_promotion);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_WHATSAPP,$prefer_whatsapp);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_TELEGRAM,$prefer_telegram);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_EMAIL,$prefer_email);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_TELEPHONE,$prefer_call);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_MODIFY_BY, $modifyby);
				$datas_person[] = $this->db->fieldValue(PersonContactTable::C_MODIFY_DATE, $modifydate);
				
				$datas_contact 	 = array();
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_DESIGNATION,$this->getParam($contact,'contact_designation',"")) ;
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_DEPT,$this->getParam($contact,'contact_dept',"")) ;
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_REPORT_TO,$this->getParam($contact,'contact_report_to',"")) ;
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_MODIFY_BY, $modifyby);
				$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_MODIFY_DATE, $modifydate);
				
				if($contact_person_id == 0 || $contact_id == 0){
					$datas_person[] = $this->db->fieldValue(PersonContactTable::C_CREATE_BY, $modifyby);
					$datas_person[] = $this->db->fieldValue(PersonContactTable::C_CREATE_DATE, $modifydate);
					$person_id 	 	= $clsPerson->addRecord($datas_person);

					$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_ID,$prospect_id) ;
					$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_PERSON_CONTACT,$person_id) ;
					$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_CREATE_BY, $modifyby);
					$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_CREATE_DATE, $modifydate);
					$contact_id = $clsContact->addRecord($datas_contact);

				}else{
					$clsPerson->updateRecord($contact_person_id, $datas_person);
					$clsContact->updateRecord($contact_id, $datas_contact);
				}

				if($contact_ids != ""){
					$contact_ids .= "," . $contact_id;
				}else{
					$contact_ids .= $contact_id;
				}

				$contact_ids = trim($contact_ids, ",");

				// $deleted_contact = $params['deleted_contact'];
				// if(!is_null($deleted_contact) && count($deleted_contact) > 0){
				// 	foreach($deleted_contact as $del_contact_id){
				// 		if($contact_ids != ""){
				// 			$contact_ids .= "," . $del_contact_id;
				// 		}else{
				// 			$contact_ids .= $del_contact_id;
				// 		}
				// 	}
				// }
			}
			$clsContact->deleteProspectContactFromProspect($prospect_id, $contact_ids);
			$this->db->commitTran();
			$this->sendJsonResponse(Status::Ok,"Account successfully updated to the system.","",$this->type);
		} catch (Exception $e) {
			$this->db->rollbackTran();
			Log::write('[Account]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
	}

	function getAccountCategory(){//Prospect C_SALES_STATUS2
		$arr = array() ;
		$arr[] = array ('code'=>'0','desc'=>"-- Select Category --" );
		$arr[] = array ('code'=>'1','desc'=>"Raw" );
		$arr[] = array ('code'=>'2','desc'=>"Suspect" );
		$arr[] = array ('code'=>'3','desc'=>"Prospect" );
		$arr[] = array ('code'=>'4','desc'=>"Customer" );
		return Util::createOptionValue($arr) ;
	}

	function getAccountCompanyStatus(){//Prospect C_COMPANY_STATUS
		$arr = array() ;
		$arr[] = array ('code'=>'0','desc'=>"-- Select Status --" );
		$arr[] = array ('code'=>'1','desc'=>"Active" );
		$arr[] = array ('code'=>'2','desc'=>"Inactive" );
		return Util::createOptionValue($arr) ;
	}
}
?>
