<?php
###############################################################################

namespace 	CodePunch\Base;

###############################################################################

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

###############################################################################

require realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '../../PHPMailer/src/Exception.php';
require realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '../../PHPMailer/src/PHPMailer.php';
require realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '../../PHPMailer/src/SMTP.php';

###############################################################################

class Mailer {
	
	public $authentication = null;
	public $mail = null;
	
	###########################################################################
	
	public function __construct($auth)
	{ 
		$this->authentication = $auth;
		$setup = new \CodePunch\Config\Settings($auth);
		$language = $setup->getOption('interface_language', \CodePunch\Config\Defaults::LANGUAGE);
		$method = $setup->getOption('email_send_method', \CodePunch\Config\Defaults::EMAIL_SEND_METHOD);
		
		$this->mail = new PHPMailer(true); 
		if(strcasecmp($method, "smtp") == 0){
			$this->mail->isSMTP();                                    
			$this->mail->Host       = $setup->getOption('email_smtp_server', '');
			$this->mail->SMTPAuth   = $setup->getOption('email_smtp_user', '') == '' ? false : true;
			$this->mail->SMTPSecure = $setup->getOption('email_smtp_secure', 'tls');
			$this->mail->Port       = $setup->getOption('email_smtp_port', 587);
			$this->mail->Username   = $setup->getOption('email_smtp_user', '');
			$this->mail->Password   = $setup->getEncryptedOption('email_smtp_password', '');
		}
		else if(strcasecmp($method, "qmail") == 0)
			$this->mail->IsQmail();
		else if(strcasecmp($method, "sendmail") == 0)
			$this->mail->IsSendmail();
		else if(strcasecmp($method, "default") == 0)
			$this->mail->IsMail();
		
		$this->mail->setLanguage($language);
		$this->mail->CharSet   = 'UTF-8';
		$this->mail->WordWrap  = $setup->getOption('email_word_wrap', "60");
		$this->mail->setFrom($setup->getOption('email_from_address', ''), $setup->getOption('email_from_name', ''));
		$replyaddr = $setup->getOption('email_reply_address', '');
		$replyname = $setup->getOption('email_reply_name', '');
		if(filter_var($replyaddr, FILTER_VALIDATE_EMAIL))
			$this->mail->addReplyTo($replyaddr, $replyname);
	}

	###########################################################################

	public function send($recipients, $subject, $message, $altbody="", $debuglevel=0)
	{
		if($this->mail) {
			$this->mail->ClearAllRecipients( );
			try {
				$ishtml = false;
				if(preg_match('/^'.preg_quote("<html>")."/", $message))
					$ishtml = true;
				
				$this->mail->SMTPDebug = $debuglevel;
				$this->mail->isHTML($ishtml);                              
				$this->mail->Subject = $subject;
				$this->mail->Body    = $message;
				if($ishtml && $altbody != "")
					$this->mail->AltBody = $altbody;
				
				foreach($recipients as $to) {
					foreach($to as $toemail => $toname) 
						$this->mail->addAddress($toemail, $toname);
				}

				return $this->mail->send() ? true : false;
			} 
			catch (Exception $e) {
				$logger = new \CodePunch\Base\CPLogger();
				$logger->error($e->getMessage() . "\n" . $this->mail->ErrorInfo);
			}
		}
		return false;
	}
	
	###########################################################################
	
	public static function formatEmailRecipients($recipients)
	{
		$rows = explode("\n", $recipients);
		$recipients = array();
		foreach($rows as $row) {
			$recipient = array();
			$row = str_replace(",", ";", $row);
			$parts = explode(";", $row);
			$parts = array_map("trim", $parts);
			if(count($parts) >= 2) {
				if(filter_var($parts[0], FILTER_VALIDATE_EMAIL) && !filter_var($parts[1], FILTER_VALIDATE_EMAIL)) 
					$recipient[$parts[0]] = $parts[1];
				else if(filter_var($parts[1], FILTER_VALIDATE_EMAIL) && !filter_var($parts[0], FILTER_VALIDATE_EMAIL))
					$recipient[$parts[1]] = $parts[0];
			}
			else if(count($parts) == 1 && filter_var($parts[0], FILTER_VALIDATE_EMAIL))
				$recipient[$parts[0]] = "";
			if(count($recipient))
				$recipients[] = $recipient;
		}
		return $recipients;
	}
	
	###########################################################################
}

