<?php
require_once (PATH_MODELS . "admin/OrganizationClass.php") ;
require_once (PATH_MODELS . "admin/OrganizationOptions.php") ;
require_once (PATH_LIB 	  . "class.phpmailer.php");
require_once (PATH_LIB . "NotificationCentre.php");
require_once (PATH_CONTROLLERS . "base/ControllerBase.php") ;

abstract class EmailBase extends ControllerBase {
	/**
	 * Sends an HTML email
	 * @param String 	$subject
	 * @param String 	$message
	 * @param ArrayList $recipientEmails
	 */
	 
	protected $orgId = 0;
	protected function sendEmailManual($subject, $message, $fromEmails, $ccEmails, $recipientEmails, $attachmentList, $companyId) {
		$mail             = new PHPMailer();
        $mail->SetLanguage( 'en', 'phpmailer/language/' );
        $mail->Timeout = 300;
		
		$mail->IsSMTP(); // telling the class to use SMTP
		$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
		
		$emailSetting 	  = $this->getEmailConfig();
        if ($emailSetting['ssl'] == '1'){
            if (trim($emailSetting['mailserver']) == 'smtp.office365.com'){
                $mail->SMTPSecure = "tls";
            } else {
                $mail->SMTPSecure = "ssl";  
            }
        }

        $mail->SMTPAuth   = ($emailSetting['ea'] == '1' ? true : false);                    // enable SMTP authentication
        $mail->Host       =	$emailSetting['mailserver'];                                    // sets the SMTP server
        $mail->Port       = $emailSetting['port'];                                          // set the SMTP port for the GMAIL server
        $mail->Username   = $emailSetting['mailuser'];                                      // SMTP account username
        $mail->Password   = $emailSetting['mailpwd'];                                       // SMTP account password
        $mail->SetFrom($emailSetting['mailuser']);
		
		$mail->SetFrom($fromEmails[0]);
		if(is_null($ccEmails) == false) {
			foreach ($ccEmails as $ccEmail) {
				$mail->AddCC($ccEmail);
			}
			$ccEmailStr = implode(";", $ccEmails);
			$mail->addCustomHeader("Cc: " . $ccEmailStr);
		}
		
		$mail->Subject    = $subject;
		// $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
		
		$mail->IsHTML(true);
		$mail->MsgHTML($message);
		
		foreach ($recipientEmails as $recipientEmail) {
			if (isset($recipientEmail) && !empty($recipientEmail))
				$mail->AddAddress($recipientEmail);
		} 
		$toEmailStr = implode(",", $recipientEmails);
		$mail->addCustomHeader("to: " . $toEmailStr);
        if (!is_null($attachmentList) && count($attachmentList) > 0){
            foreach($attachmentList as $attachment){
                $mail->AddAttachment($attachment);      // attachment
            }
        }
		try {
            $result = $mail->Send();
            if (!$result){
                Log::write($mail->ErrorInfo);
            }
			return $result;
		} catch (Exception $e) {
			Log::write('[Send Email] :'.$e->getMessage());
			return false;
		}
	}
	
	protected function sendEmail($subject, $message, $fromEmails, $ccEmails = null, $recipientEmails, $attachmentList = null, $companyId = 0, $appType = 0, $appId = 0) {
		if ($companyId != 0){
            $emailSetting 	  = $this->getEmailConfigFromCompany($companyId);
        } else {
            $emailSetting 	  = $this->getEmailConfig();
        }
		// log::write("HERE");
		// log::write($emailSetting);
		$clsNc = new NotificationCentre();
		$result = $clsNc->sendEmail($subject, $message,$fromEmails, $recipientEmails, $ccEmails, $attachmentList, $companyId, $emailSetting, $appType, $appId);
		if (!$result) {
			$result = $this->sendEmailManual($subject, $message,$fromEmails, $ccEmails, $recipientEmails, $attachmentList, $companyId);
		}
		return $result;        
	}
	
	protected function getEmailConfig() {
		$cls = new OrganizationClass($this->db) ;
		if($this->orgId == -1)
			$row = $cls->getRecord(0) ;
		else
			$row = $cls->getRecord($this->orgId) ;

		// log::write("HERE2");
		// log::write(print_r($row,true));

		if (is_null($row))
			return null;
		
		if (is_null($row[OrganizationTable::C_OPTIONS]) || $row[OrganizationTable::C_OPTIONS] == "") 
			return null;
		
		$opt = new OrganizationOptions() ;
		if(!is_null($row) && count($row) > 0)
			$opt->loadXml($row[OrganizationTable::C_OPTIONS]) ;
		$op = $opt->getOption() ;
		
		$datas = array();
		$datas['mailserver']= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_SERVER] ;
		$datas['mailuser'] 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_USER] ;
		$datas['mailpwd'] 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_PWD] ;
		$datas['ea'] = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_ENABLE_AUTHENTICATION] ;
		$datas['port'] = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_PORT] ;
		$datas['ssl'] = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_SSL] ;
		
		return $datas;
	}
	
	protected function getEmailConfigFromCompany($coyId) {
		$cls = new OrganizationClass($this->db) ;
		$row = $cls->getRecord($coyId) ;

		if (is_null($row))
			return null;
		
		
		if (is_null($row[OrganizationTable::C_OPTIONS]) || $row[OrganizationTable::C_OPTIONS] == "") 
			return null;
		
		$opt = new OrganizationOptions() ;
		if(!is_null($row) && count($row) > 0)
			$opt->loadXml($row[OrganizationTable::C_OPTIONS]) ;
		$op = $opt->getOption() ;
		
		$datas = array();
		$datas['mailserver']= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_SERVER] ;
		$datas['mailuser'] 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_USER] ;
		$datas['mailpwd'] 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_PWD] ;
		$datas['ea'] = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_ENABLE_AUTHENTICATION] ;
		$datas['port'] = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_PORT] ;
		$datas['ssl'] = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_SSL] ;
		
		return $datas;
	}

	protected function getBaseURL(){
        $pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
        if ($_SERVER["SERVER_PORT"] != "80")
        {
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"];
			$strURL = explode('/',$_SERVER['PHP_SELF'])[1];
			if($strURL != "portal") {
				$pageURL .= "/".$strURL;
			}
        }
        else
        {
            $pageURL .= $_SERVER["SERVER_NAME"];
        }
        if (strpos($pageURL, "?") !== false){
            $pageURL = substr($pageURL, 0, strpos($pageURL, "?"));
        }
        return $pageURL;
    }
} 