<?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";
	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;
					}
				}
			}	
		} catch (Exception $e) {
			$result = false;
		}
		return $result;
	}

	public function sendEmail($subject, $message,$fromEmails, $recipientEmails, $ccEmails = null, $attachmentList = null, $companyId = 0,$emailSetting, $appType, $appId) {
		$config = $this->loadConfig();
		$service = $this->checkService();
		if(!$config || !$service){
			 return false;
		}

		$this->dbnotif->open();        
        $emailSec = "none";
        if ($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);        
        $data = array();
		/*if ($appType==AppType::Activity) {
         $appName = AppName::Activity;
        }elseif($appType==AppType::Invoice) {
         $appName = AppName::Invoice;
        }*/
  		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_NAME,"P-Service");
		$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_PORT,$emailSetting['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);
		
		try {
			$batch_data = array();
			$i = 0;
			foreach ($recipientEmails as $recipientEmail) {
				if (isset($recipientEmail) && !empty($recipientEmail)){				
					$data[] = $this->dbnotif->fieldValue(NotificationCentre::C_TO,$recipientEmail) ;
					$id = $this->addRecord($data);
					$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();
					$val [] = $this->dbnotif->formatValueParam(EmailLogNc::C_EMAIL_ID);
					$val [] = $this->dbnotif->formatValueParam(EmailLogNc::C_TRAN_TYPE);
					$val [] = $this->dbnotif->formatValueParam(EmailLogNc::C_TRAN_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,$data[EmailLogNc::C_TRAN_ID]) ;
				}
				$sql .= implode(",", $sql_temp);
				$this->dbnotif->insertRow($sql,$params) ;
				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" ;	
}
?>