<?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 . "prospect/ProspectDocumentClass.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 Meeting 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) {
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
			$isTurnOff = false;
			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_GET:
					$this->getRecord($params) ;
					break ;
				case 'DELETE_ATTACHMENT':
					$this->deleteAttachment($params);
					break;
				case REQ_VIEW:
					$this->processView() ;
					break ;
				case "ACCOUNT_NAME_SEARCH":
					$this->getAccountList() ;
					break ;
				case "GET_ACCOUNT_INFO":
					$this->getAccountDetail($params) ;
					break ;
				// case REQ_UPLOAD_LOGO:
				// 	$this->saveMeetingAttachment($params);
				// 	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/meeting/MeetingView.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) && count($rows) > 0) {
				$data['id']			= $rows[0][ProspectTable::C_ID];
				$data['name']		= $rows[0][ProspectTable::C_NAME];
				$data['phone']		= $rows[0][ProspectTable::C_TELEPHONE];
				$data['email']		= $rows[0][ProspectTable::C_COMPANY_EMAIL];
				$data['address']	= $rows[0][ProspectTable::C_ADDRESS_1];
				if(isset($params['person_id'])) {
					$data['person_id']  =  $params['person_id'];
				}
				// $data['contact_id']	= $rows[0][ProspectContactTable::C_CONTACT_ID];

				$data['contacts']	= [];
				$contactOptions = "<option value=''>Select Contact</option>";
				foreach($rows as $row){
					$contact = [];
					$contact['contact_id']	= $row[ProspectContactTable::C_CONTACT_ID];
					$contact['person_id']	= $row[PersonContactTable::C_ID];
					$contact['name']		= $row[PersonContactTable::C_FULL_NAME];
					$contact['phone']		= $row[PersonContactTable::C_TELEPHONE];
					$contact['email']		= $row[PersonContactTable::C_EMAIL];
					$data['contacts'][] 	= $contact;

					$contactOptions .= "<option value='".$row[PersonContactTable::C_ID]."'>".$row[PersonContactTable::C_FULL_NAME]."</option>";
				}
				$data['contact_options'] = $contactOptions;
            }
			$this->sendJsonResponse(Status::Ok,"",$data,$this->type);
        } catch (Exception $e) {
            Log::write('[getAccount]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"","",$this->type) ;
        }
    }

	private function getAccountList(){
        $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 ($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) ;
		$clsConversation 	= new ProspectConversationClass($this->db) ;
		
		$modifyby 		= $_SESSION[SE_USERID] ;
		$modifydate 	= date_create('now')->format('Y-m-d H:i:s') ;

		$prospect_id = $this->getParamInt($params, 'prospect_id', 0);
		$person_id = $this->getParamInt($params, 'person_id', 0);
		$contact_id = $this->getParamInt($params, 'contact_id', 0);
		$conversation_id = $this->getParamInt($params, 'conversation_id', 0);

		try {
			$this->db->beginTran();
			// if($prospect_id == 0) {
			// 	$datas_prospect   = array() ;
			// 	$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_NAME, $this->getParam($params,'name',""));
			// 	$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_TELEPHONE, $this->getParam($params,'phone',""));
			// 	$datas_prospect[] = $this->db->fieldValue(ProspectTable::C_COMPANY_EMAIL,$this->getParam($params,'email',""));
			// 	$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);

			// 	$datas_person 	= array();
			// 	$datas_person[] = $this->db->fieldValue(PersonContactTable::C_FULL_NAME,$this->getParam($params,'name',""));
			// 	$datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_NAME,$this->getParam($params,'name',""));
			// 	$datas_person[] = $this->db->fieldValue(PersonContactTable::C_TELEPHONE,$this->getParam($params,'phone',""));
			// 	$datas_person[] = $this->db->fieldValue(PersonContactTable::C_EMAIL,$this->getParam($params,'location',""));
			// 	$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_ACTION_LOCATION,$this->getParam($params,'followup_location',"")) ;
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_ACTION_DATE,$this->getParam($params,'followup_date',NULL_DATE)) ;
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_ACTION_STATUS,$this->getParam($params,'status',"")) ;
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_NEXT_ACTION,$this->getParam($params,'next_action',"")) ;
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_BEST_TIME,$this->getParam($params,'followup_time',"")) ;
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_INSERT_TO_CALENDAR,$this->getParam($params,'insert_to_calendar',0));
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_REMINDER_DAYS,$this->getParam($params,'reminder_days',0));
			$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->updateRecord($contact_id, $datas_contact);

			$datas_conversation   = array();
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_ID, $prospect_id) ;
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_CONTACT_ID,$contact_id) ;
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_DESC,$this->getParam($params,'conversation',"")) ;
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_LOCATION,$this->getParam($params,'location',"")) ;
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_CREATE_BY, $modifyby);
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_CREATE_DATE, $this->getParam($params,'date',"") . " " . $this->getParam($params,'time',""));
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_MODIFY_BY, $modifyby);
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_MODIFY_DATE, $modifydate);
			$conversation_id 	  = $clsConversation->addRecord($datas_conversation);

			$mesg = "";
			if($this->getParam($params,'file_name',"") != ""){
				$temp_file = PATH_TEMP . $this->getParam($params,'file_doc',"") ;
				if(!file_exists($temp_file)){
					log::write("File not found.");
				} else {
					$ext = pathinfo($temp_file, PATHINFO_EXTENSION);
					$file_doc = "doc_" . date('Ymdhis') . "." . $ext ;
					if(!file_exists(PATH_PROSPECT_ATTACHMENT . $prospect_id)){
						mkdir(PATH_PROSPECT_ATTACHMENT . $prospect_id, 0777, true);
					}
					$uploadfile = PATH_PROSPECT_ATTACHMENT . $prospect_id . "/" . $file_doc ;
					if(rename($temp_file, $uploadfile)) {
						log::write("File uploaded successfully.");
					} else {
						$phpErr = error_get_last();
						$mesg = isset($phpErr['message']) ? $phpErr['message'] : "Error in processing uploaded file.";
						log::write("[UploadError] " . $mesg);
					}

					$clsDocument = new ProspectDocumentClass($this->db) ;
					$datas_document   = array();
					$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_ID, $prospect_id) ;
					$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_CONVERSATION_ID,$conversation_id) ;
					$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_NAME,$this->getParam($params,'file_name',"")) ;
					$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_FILE,$file_doc) ;
					$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_FILE_TYPE,$ext) ;
					$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_CREATE_BY, $modifyby);
					$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_CREATE_DATE, $modifydate);
					$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_MODIFY_BY, $modifyby);
					$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_MODIFY_DATE, $modifydate);
					$clsDocument->addRecord($datas_document);
				}
			}

			$this->db->commitTran();
			// gather attachments for response so client can refresh list
			$attachments = $this->getMeetingAttachments($prospect_id, $conversation_id);
			$responseData = array(
				'prospect_id' => $prospect_id,
				'conversation_id' => $conversation_id,
				'attachments' => $attachments
			);
			$this->sendJsonResponse(Status::Ok,"Meeting successfully added to the system. " . $mesg, $responseData,$this->type);
		} catch (Exception $e) {
			$this->db->rollbackTran();
			Log::write('[Meeting]' . $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) ;
		$clsConversation 	= new ProspectConversationClass($this->db) ;
		
		$modifyby 			= $_SESSION[SE_USERID] ;
		$modifydate 		= date_create('now')->format('Y-m-d H:i:s') ;

		$prospect_id = $this->getParamInt($params, 'prospect_id', 0);
		$person_id = $this->getParamInt($params, 'person_id', 0);
		$contact_id = $this->getParamInt($params, 'contact_id', 0);
		$conversation_id = $this->getParamInt($params, 'conversation_id', 0);

		try {
			$this->db->beginTran();
			// $datas_prospect   = array() ;
			// $datas_prospect[] = $this->db->fieldValue(ProspectTable::C_NAME, $this->getParam($params,'name',""));
			// $datas_prospect[] = $this->db->fieldValue(ProspectTable::C_TELEPHONE, $this->getParam($params,'phone',""));
			// $datas_prospect[] = $this->db->fieldValue(ProspectTable::C_COMPANY_EMAIL,$this->getParam($params,'email',""));
			// $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);

			// $datas_person 	= array();
			// $datas_person[] = $this->db->fieldValue(PersonContactTable::C_FULL_NAME,$this->getParam($params,'name',""));
			// $datas_person[] = $this->db->fieldValue(PersonContactTable::C_PREFER_NAME,$this->getParam($params,'name',""));
			// $datas_person[] = $this->db->fieldValue(PersonContactTable::C_TELEPHONE,$this->getParam($params,'phone',""));
			// $datas_person[] = $this->db->fieldValue(PersonContactTable::C_EMAIL,$this->getParam($params,'email',""));
			// $datas_person[] = $this->db->fieldValue(PersonContactTable::C_MODIFY_BY, $modifyby);
			// $datas_person[] = $this->db->fieldValue(PersonContactTable::C_MODIFY_DATE, $modifydate);
			// $clsPerson->updateRecord($person_id, $datas_person);

			$datas_contact 	 = array();
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_ACTION_LOCATION,$this->getParam($params,'followup_location',"")) ;
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_ACTION_DATE,$this->getParam($params,'followup_date',NULL_DATE)) ;
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_ACTION_STATUS,$this->getParam($params,'status',"")) ;
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_NEXT_ACTION,$this->getParam($params,'next_action',"")) ;
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_BEST_TIME,$this->getParam($params,'followup_time',"")) ;
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_INSERT_TO_CALENDAR,$this->getParam($params,'insert_to_calendar',0));
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_REMINDER_DAYS,$this->getParam($params,'reminder_days',0));
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_MODIFY_BY, $modifyby);
			$datas_contact[] = $this->db->fieldValue(ProspectContactTable::C_MODIFY_DATE, $modifydate);
			$clsContact->updateRecord($contact_id, $datas_contact);
			

			$datas_conversation   = array();
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_DESC,$this->getParam($params,'conversation',"")) ;
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_LOCATION,$this->getParam($params,'location',"")) ;
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_MODIFY_BY, $modifyby);
			$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_MODIFY_DATE, $this->getParam($params,'date',"") . " " . $this->getParam($params,'time',""));
			if($conversation_id != 0){
				$clsConversation->updateRecord($conversation_id, $datas_conversation);
			}else{
				$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_ID, $prospect_id) ;
				$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_CONTACT_ID,$contact_id) ;
				$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_CREATE_BY, $modifyby);
				$datas_conversation[] = $this->db->fieldValue(ProspectConversationTable::C_CREATE_DATE, $this->getParam($params,'date',"") . " " . $this->getParam($params,'time',""));
				$conversation_id = $clsConversation->addRecord($datas_conversation);
			}		

			$mesg = "";
			if($this->getParam($params,'file_name',"") != ""){
				$temp_file = PATH_TEMP . $this->getParam($params,'file_doc',"") ;
				$ext = pathinfo($temp_file, PATHINFO_EXTENSION);
				$file_doc = "doc_" . date('Ymdhis') . "." . $ext ;
				if(!file_exists(PATH_PROSPECT_ATTACHMENT . $prospect_id)){
					mkdir(PATH_PROSPECT_ATTACHMENT . $prospect_id, 0777, true);
				}
				$uploadfile = PATH_PROSPECT_ATTACHMENT . $prospect_id . "/" . $file_doc ;
				if(rename($temp_file, $uploadfile)) {
					log::write("File uploaded successfully.");
				} else {
					$phpErr = error_get_last();
					$mesg = isset($phpErr['message']) ? $phpErr['message'] : "Error in processing uploaded file.";
					log::write("[UploadError] " . $mesg);
				}

				$clsDocument = new ProspectDocumentClass($this->db) ;
				$datas_document   = array();
				$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_ID, $prospect_id) ;
				$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_CONVERSATION_ID,$conversation_id) ;
				$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_NAME,$this->getParam($params,'file_name',"")) ;
				$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_FILE,$file_doc) ;
				$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_FILE_TYPE,$ext) ;
				$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_CREATE_BY, $modifyby);
				$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_CREATE_DATE, $modifydate);
				$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_MODIFY_BY, $modifyby);
				$datas_document[] = $this->db->fieldValue(ProspectDocumentTable::C_MODIFY_DATE, $modifydate);
				$clsDocument->addRecord($datas_document);
			}

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

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

		$prospect_id = $this->getParamInt($params, 'prospect_id', 0);
		$person_id = $this->getParamInt($params, 'person_id', 0);
		$contact_id = $this->getParamInt($params, 'contact_id', 0);
		$conversation_id = $this->getParamInt($params, 'conversation_id', 0);

		$rowPerson			= $clsPerson->getRecord($person_id);
		$rowContact			= $clsContact->getRecord($contact_id);
		$rowsConversation	= $clsConversation->getRecord($conversation_id);

		// Fetch attachments so the view can render them server-side when included
		$attachments = $this->getMeetingAttachments($prospect_id, $conversation_id);

		include (PATH_VIEWS . "mobile/meeting/MeetingView.php") ;

		$datas = [];
		if(is_null($rowPerson) || is_null($rowContact) || is_null($rowsConversation)){
			log::write("Meeting record not found.");
			$this->sendJsonResponse(Status::Error,"Meeting record not found.","",$this->type);
			return;
		}
		$datas['account_name']		= $clsProspect->getDescription($prospect_id);
		$datas['contact_name']		= $rowPerson[PersonContactTable::C_PREFER_NAME];
		$datas['contact_phone']		= $rowPerson[PersonContactTable::C_TELEPHONE];
		$datas['contact_email']		= $rowPerson[PersonContactTable::C_EMAIL];
		$datas['location']			= $rowsConversation[ProspectConversationTable::C_LOCATION] ?? '';
		$datas['followup_location']	= $rowContact[ProspectContactTable::C_ACTION_LOCATION];
		$datas['followup_date']		= date_create($rowContact[ProspectContactTable::C_ACTION_DATE])->format('Y-m-d');
		$datas['followup_time']		= $rowContact[ProspectContactTable::C_BEST_TIME];
		$datas['status']			= $rowContact[ProspectContactTable::C_ACTION_STATUS];
		$datas['next_action']		= $rowContact[ProspectContactTable::C_NEXT_ACTION];
		$datas['conversation']		= $rowsConversation[ProspectConversationTable::C_DESC] ?? '';
		$datas['date']				= date_create($rowsConversation[ProspectConversationTable::C_CREATE_DATE] ?? date('Y-m-d'))->format('Y-m-d');
		$datas['time']				= date_create($rowsConversation[ProspectConversationTable::C_CREATE_DATE] ?? date('H:i'))->format('H:i');
		$datas['prospect_id']		= $prospect_id;
		$datas['contact_id']		= $contact_id;
		$datas['person_id']			= $person_id;
		$datas['conversation_id']	= $conversation_id;
		$datas['insert_to_calendar'] = $rowContact[ProspectContactTable::C_INSERT_TO_CALENDAR];
		$datas['reminder_days']      = $rowContact[ProspectContactTable::C_REMINDER_DAYS];
		$datas['attachments']		= $attachments;
		$datas['htmlContent']		= Util::minifyHtml(ob_get_clean());
		
		$this->sendJsonResponse(Status::Ok,"Meeting successfully retrieved from the system.",$datas,$this->type);
	}

	private function getMeetingAttachments($prospect_id, $conversation_id){
		$clsDocument 		= new ProspectDocumentClass($this->db) ;
		$rows = $clsDocument->getMeetingAttachments($prospect_id, $conversation_id);
		$datas = [];
		if(is_null($rows) || count($rows) == 0) return $datas;
		foreach($rows as $row){
			$datas[] = [
				"id" => $row[ProspectDocumentTable::C_ID],
				"filename" => $row[ProspectDocumentTable::C_NAME],
				"filedoc" => $row[ProspectDocumentTable::C_FILE],
				"fileext" => $row[ProspectDocumentTable::C_FILE_TYPE],
			];
		}
		return $datas;
	}

	private function deleteDir($dirPath) {
        if ( !is_dir($dirPath) ) {
            // throw new InvalidArgumentException("$dirPath must be a directory");
        }
        if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
            $dirPath .= '/';
        }
        $files = glob($dirPath . '*', GLOB_MARK);
        foreach ($files as $file) {
            if (is_dir($file)) {
                self::deleteDir($file);
            } else {
                unlink($file);
            }
        }

        if(file_exists($dirPath)){
            $this->recursiveRemoveDirectory($dirPath);
        }

    }

	public function saveMeetingAttachment($id, $base64file, $extension, $filename)
    {
        $newfile = "";
        $doc_desc ="";
		$cls = new ProspectClass($this->db);
		$cls_Doc = new ProspectDocumentClass($this->db);

        if($base64file!="" || $base64file!=null){

            $path = PATH_PROSPECT_ATTACHMENT .(!isset($_SESSION[SE_BU]) ? "" : $_SESSION[SE_BU]."/"). $id . "/";
			//log::write($path);
            if (!file_exists($path)) {
                mkdir($path, 1777, true);
            }else{
                $this->deleteDir($path);
                mkdir($path, 1777, true);
            }

            $data= $base64file;
            $type= $extension;
			$encoded = substr($data, strpos($base64file, ',') + 1);
			//log::write(strlen($encoded));
            $newfile = $filename;

            if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
                $data = substr($data, strpos($data, ',') + 1);
                $type = strtolower($type[1]); // jpg, png, gif

                if (!in_array($type, [ 'jpg', 'jpeg', 'png' ])) {
                    Log::write('invalid image type');
					$mesg = "invalid image type";
                    return $mesg;
                }
                $data = str_replace( ' ', '+', $data );
                $data = base64_decode($data);

                if ($data === false) {
                    //throw new \Exception('base64_decode failed');
                    Log::write('base64_decode failed');
					$mesg = "base64_decode failed.";
                    return $mesg;
                }

                file_put_contents($path . $newfile, $data);
            } else if (preg_match('/^data:application\/(\w+);base64,/', $data, $type)) {
                $data = substr($data, strpos($data, ',') + 1);
                $type = strtolower($type[1]); // pdf

                if (!in_array($type, [ 'pdf' ])) {

                    Log::write('invalid file type');
                    $mesg = "invalid file type.";
                    return $mesg;
                }
                $data = str_replace( ' ', '+', $data );
                $data = base64_decode($data);
				//log::write($data);
                if ($data === false) {
                    //throw new \Exception('base64_decode failed');
                    Log::write('base64_decode failed');
					$mesg = "base64_decode failed.";
                    return $mesg;
                }

                file_put_contents($path . $newfile, $data);
            }else {
                //throw new \Exception('did not match data URI with image data');
                Log::write('did not match data URI with image data');
				$mesg = "did not match data URI with image data.";
                return $mesg;
            }

            try {
				//log::write($id);
                $datas_doc_to_save = array() ;
                $datas_doc_to_save[] = $this->db->fieldValue(ProspectDocumentTable::C_ID ,$id);
                $datas_doc_to_save[] = $this->db->fieldValue(ProspectDocumentTable::C_DOCUMENT_ID ,1);

                $datas_doc_to_save[] = $this->db->fieldValue(ProspectDocumentTable::C_NAME , $filename);
                $datas_doc_to_save[] = $this->db->fieldValue(ProspectDocumentTable::C_FILE , $encoded);
                $datas_doc_to_save[] = $this->db->fieldValue(ProspectDocumentTable::C_FILE_TYPE , $type);

                $cls_Doc->addRecord($datas_doc_to_save) ;
                return;

            } catch (Exception $e){
                Log::write('[attachment]' . $e->getMessage());
				$mesg = $e->getMessage();
                return $mesg;

            }

        }

    }

	private function deleteAttachment($params){
		$clsDocument = new ProspectDocumentClass($this->db);
		try{
			if(!isset($_SESSION[SE_USERID]) || $_SESSION[SE_USERID] == ""){
				$this->sendJsonResponse(Status::Error,"Permission denied.","",$this->type);
				return;
			}

			$prospect_id = $this->getParamInt($params,'prospect_id',0);
			$filedoc = $this->getParam($params,'filedoc','');

			if($filedoc == ""){
				$this->sendJsonResponse(Status::Error,"Invalid parameters.","",$this->type);
				return;
			}

			// If prospect_id == 0 treat as temp upload (no DB record yet)
			if ($prospect_id == 0) {
				$tempPath = PATH_TEMP . $filedoc;
				if (file_exists($tempPath)) {
					@unlink($tempPath);
					$this->sendJsonResponse(Status::Ok,"Temporary attachment deleted.", array('filedoc' => $filedoc), $this->type);
					return;
				} else {
					$this->sendJsonResponse(Status::Error,"Attachment not found.","",$this->type);
					return;
				}
			}

			// verify document exists
			$sql = "SELECT * FROM " . ProspectDocumentTable::C_TABLE .
				" WHERE " . ProspectDocumentTable::C_ID . " = " . $prospect_id .
				" AND " . ProspectDocumentTable::C_FILE . " LIKE '%" . $filedoc . "%'";
			$rows = $this->db->getTable($sql);
			if (is_null($rows) || count($rows) == 0) {
				$this->sendJsonResponse(Status::Error,"Attachment not found.","",$this->type);
				return;
			}

			// delete DB record
			$delSql = "DELETE FROM " . ProspectDocumentTable::C_TABLE .
				" WHERE " . ProspectDocumentTable::C_ID . " = " . $prospect_id .
				" AND " . ProspectDocumentTable::C_FILE . " LIKE '%" . $filedoc . "%'";
			$this->db->executeSql($delSql);

			// delete file from filesystem if exists
			$path = PATH_PROSPECT_ATTACHMENT . $prospect_id . "/" . $filedoc;
			if(file_exists($path)){
				@unlink($path);
			}

			$this->sendJsonResponse(Status::Ok,"Attachment deleted.", array('filedoc' => $filedoc), $this->type);
		} catch (Exception $e){
			Log::write('[Meeting::deleteAttachment] ' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Error deleting attachment.","",$this->type);
		}
	}

	private function deleteMissingAttachment($prospect_id, $filedoc){
		$delSql = "DELETE FROM " . ProspectDocumentTable::C_TABLE .
			" WHERE " . ProspectDocumentTable::C_ID . " = " . $prospect_id .
			" AND " . ProspectDocumentTable::C_FILE . " LIKE '%" . $filedoc . "%'";
		$deleted = $this->db->executeSql($delSql);
	}
}
?>
