<?php
require_once(PATH_CODE . 'ConfigDb.php') ;
class NotificationCentre {
	const C_TABLE 	 		= "EMAIL_REQUEST" ;
	const C_NAME 	 		= "APP_NAME";
	const C_ID 		 		= "EMAIL_REQUEST_ID";
	const C_PORT 	 		= "EMAIL_PORT";
	const C_SERVER 	 		= "EMAIL_SERVER";
	const C_SECURITY 		= "EMAIL_SECURITY";
	const C_AUTH 	 		= "NEED_AUTHENTICATION";
	const C_FROM 	 		= "EMAIL_FROM";
	const C_PASSWORD 		= "EMAIL_PASSWORD";
	const C_SUBJECT  		= "EMAIL_SUBJECT";
	const C_CONTENT  		= "EMAIL_CONTENT";
	const C_BODY 			= "EMAIL_BODY";
	const C_TO 				= "EMAIL_TO";
	const C_CC 				= "EMAIL_CC";
	const C_BCC 			= "EMAIL_BCC";
	const C_ATTACHMENT		= "ATTACHMENT";	
	const C_TIME 			= "REQUEST_TIME";
	const C_FAIL 			= "FAIL_COUNT";
	const C_STATUS 			= "STATUS";
	const C_STATUS_TIME 	= "STATUS_TIME";
	const C_USE_GRAPH_API	= "USE_MICROSOFT_GRAPH_API";
	const C_TENANT_ID		= "AZURE_TENANT_ID";
	private $dbnotif 	= null;
	function __construct() {		
	}

	public function loadConfig()
	{
		$config = new ConfigDb(PATH_CODE . 'db.xml') ;
		$config->loadConfig() ;
		try {
			// $this->conn = new PDO($this->dsn,$this->dbuser, $this->dbpwd,$this->dbopt); 
			// $this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); 
			$dsn = "";
			if ($config->getDbTypeNotif() == DbType::MySql){
				$this->dbnotif = new MySqlDb($config->getHostNotif(),$config->getDbNameNotif(),$config->getUserNameNotif(),$config->getPasswordNotif()) ;
				$dsn = "mysql:host=".$config->getHostNotif().";bname=".$config->getDbNameNotif() ;
			}
			else if ($config->getDbTypeNotif() == DbType::MySqli){
				$this->dbnotif = new MySqliDb($config->getHostNotif(),$config->getDbNameNotif(),$config->getUserNameNotif(),$config->getPasswordNotif()) ;
			}
			else{
				$this->dbnotif = new MsSqlDb($config->getHostNotif(),$config->getDbNameNotif(),$config->getUserNameNotif(),$config->getPasswordNotif()) ;
				$dsn = "sqlsrv:Server=" . $config->getHostNotif() ;				
				$dsn .= ";Database=" . $config->getDbNameNotif();
			}
			// open database if exist
			   $pdo = new PDO($dsn,$config->getUserNameNotif(),$config->getPasswordNotif());

			   // check if table is exist
			   $stmt = $pdo->prepare("SELECT TOP 1 1 FROM ".NotificationCentre::C_TABLE);
			   if (!$stmt->execute()) {
			    // return false if table didn't exist
			    return false;
			   }
			//unset($config) ;
			return true ;
		} catch(Exception $e) { 
			// throw if there is a trouble while opening database
			return false;
		}

	}

	public function checkService()
	{
		/* check if service is running*/
		$result = false;
		try {
			exec("tasklist", $task_list);
			$search_pattern = '~(NotificationCentre)\.exe~i';
			if ($task_list) {
				foreach ($task_list as $key) {
					if (preg_match($search_pattern, $key))
					{
						$result = true;
					}
				}
			}	
			//Log::write($task_list);
		} catch (Exception $e) {
			$result = false;
		}
		return $result;
	}

	public function sendEmail($subject, $message,$fromEmails, $recipientEmails, $ccEmails = null, $attachmentList = null, $companyId = 0,$emailSetting=null, $appType=0, $appId=0) {
		$config = $this->loadConfig();
		$service = $this->checkService();
		// $service = true;
		if(!$config || !$service){
			 return false;
		}
		$this->dbnotif->open();        
        $emailSec = "none";
        if (isset($emailSetting['ssl']) && $emailSetting['ssl'] == '1'){
            if (trim($emailSetting['mailserver']) == 'smtp.office365.com'){
                $emailSec = "tls";  
            } else {
                $emailSec = "ssl";  
            }
        }
        $ccEmailStr = $attachmentStr= "";
        if($ccEmails) {
			$ccEmailStr = implode(";", $ccEmails);
		}
		if (!is_null($attachmentList) && count($attachmentList) > 0){
            $attachmentStr = implode(";", $attachmentList);
        }
        $auth = ($emailSetting['ea'] == '1' ? true : false);        

        $port = isset($emailSetting['port']) ? $emailSetting['port'] : 25;
  		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_NAME, "CCM");
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_PORT,$port);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_SERVER,$emailSetting['mailserver']);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_SECURITY,$emailSec);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_AUTH,$auth);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_FROM,$emailSetting['mailuser']);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_PASSWORD,$emailSetting['mailpwd'],"","");
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_SUBJECT,$subject);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_CONTENT,$message);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_TIME,date('Y-m-d H:i:s'));
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_FAIL,0);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_STATUS,0);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_STATUS_TIME,date('Y-m-d H:i:s'));
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_CC,$ccEmailStr);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_ATTACHMENT,$attachmentStr);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_USE_GRAPH_API,$emailSetting['oauth']);
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_TENANT_ID,($emailSetting['tenantid'] == NULL) ? "" : $emailSetting['tenantid']);
		// $subject, $message,$fromEmails, $recipientEmails, $ccEmails = null, $attachmentList = null, $companyId = 0,$emailSetting, $appType, $appId			
		try {
			$batch_data = array();
			$i = 0;
			foreach ($recipientEmails as $recipientEmail) {
				if (isset($recipientEmail) && !empty($recipientEmail)){
					$dataInsert = $data;
					$dataInsert[] = $this->dbnotif->fieldValue(NotificationCentre::C_TO,$recipientEmail) ;					
					$id = $this->addRecord($dataInsert);
					$batch_data[$i][EmailLogNc::C_EMAIL_ID]=$id;
					$batch_data[$i][EmailLogNc::C_TRAN_TYPE]=$appType;
					$batch_data[$i][EmailLogNc::C_TRAN_ID]=$appId;
					$i++;
				}
			}
			$this->addRecordLog($batch_data);
			return true;

		} catch (Exception $e) {
			return false;
		}
		$this->dbnotif->close();
	}

	function addRecord($datas) {
		$sql = "insert into " . NotificationCentre::C_TABLE ;
		$fld = "" ;
		$val = "" ;
		$fs = "" ;
		$params = array() ;
		try {
			if (is_array($datas) && count($datas) > 0) {
				foreach ($datas as $data) {
					$fld .= $fs . $data['field'] ;
					$val .= $fs . $this->dbnotif->formatValueParam($data['field']) ;
					$params[] = $this->dbnotif->valueParam($data['field'],$data['value']) ;
					$fs = ", " ;
				}
				$sql .= " (" . $fld . ") values (" . $val . ")";				
				$notifId = $this->dbnotif->insertRowGetId($sql,$params) ;
				return $notifId ;
			} else {
				return "error" ;
			}
		} catch (Exception $e) {
			return $e->getMessage(); ;
		}
	}

	function addRecordLog($datas) {
		$sql = "insert into " . EmailLogNc::C_TABLE ." (".EmailLogNc::C_EMAIL_ID.", ".EmailLogNc::C_TRAN_TYPE.", ".EmailLogNc::C_TRAN_ID.") VALUES";
		$params = array() ;	
		$sql_temp = array() ;	
		try {
			if (is_array($datas) && count($datas) > 0) {
				foreach ($datas as $data) {
					$val = array();					
					if ($data[EmailLogNc::C_TRAN_ID]) {
						$trans_id = $data[EmailLogNc::C_TRAN_ID];
					}else{
						$trans_id = 0;
						Log::write('[email log] trans_id = 0');
					}
					$val [] = $data[EmailLogNc::C_EMAIL_ID];
					$val [] = $data[EmailLogNc::C_TRAN_TYPE];
					$val [] = $trans_id;
					$val = implode(',', $val);
					$sql_temp[]= " (" . $val . ")";				
					$params[] = $this->dbnotif->valueParam(EmailLogNc::C_EMAIL_ID,$data[EmailLogNc::C_EMAIL_ID]) ;
					$params[] = $this->dbnotif->valueParam(EmailLogNc::C_TRAN_TYPE,$data[EmailLogNc::C_TRAN_TYPE]) ;
					$params[] = $this->dbnotif->valueParam(EmailLogNc::C_TRAN_ID,$trans_id) ;
				}
				$sql .= implode(",", $sql_temp);
				$this->dbnotif->executeSql($sql) ;
				return true ;
			} else {
				return false ;
			}
		} catch (Exception $e) {
			return $e->getMessage(); ;
		}
	}
	
}

/**
* 
*/
class EmailLogNc
{
	const C_TABLE = "EMAIL_LOG" ;
	const C_CODE = "CONT_CODE" ;
	const C_ID = "EMAIL_LOG_ID" ;
	const C_TRAN_ID = "TRANSACTION_ID" ;
	const C_TRAN_TYPE = "TRANSACTION_TYPE" ;
	const C_EMAIL_ID = "EMAIL_ID" ;	
}
?>