<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once dirname(__FILE__)."/../../dal/registryDAL.php";
require_once dirname(__FILE__)."/../PHPMailer/src/Exception.php";
require_once dirname(__FILE__)."/../PHPMailer/src/PHPMailer.php";
require_once dirname(__FILE__)."/../PHPMailer/src/SMTP.php";
class smtp_mail {
	public array $toAry = [];
	public string $name;
	public string $subject;
	public string $body;

	public function send(): string {
		$sendMailType = registryDAL::getRegistryValue("sendMailType");
		if ($sendMailType == 1 || $sendMailType == "5") {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, "https://www.webi.com.tw/api/smtp_preset.php");
			curl_setopt($ch, CURLOPT_HEADER, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$txtJ = curl_exec($ch);
			curl_close($ch);
			$objJ = json_decode($txtJ);

			$smtpSecure = $objJ->secure;
			$host = $objJ->host;
			$port = $objJ->port;
			$smtpAuth = $objJ->auth;
			$username = $objJ->user;
			$password = $objJ->pass;
		} else {
			$smtpSecure = registryDAL::getRegistryValue("sendMailSMTPSecure");
			$host = registryDAL::getRegistryValue("sendMailHost");
			$port = registryDAL::getRegistryValue("sendMailPort");
			$smtpAuth = registryDAL::getRegistryValue("sendMailSMTPAuth");
			$username = registryDAL::getRegistryValue("sendMailAddress");
			$password = registryDAL::getRegistryValue("sendMailPassword");
		}

		// 收件者mail,mail標體,mail內容,寄件者mail,寄件者名稱
		// 宣告一個PHPMailer物件
		$mail = new PHPMailer(true);
		try {
			$mail->isSMTP();								// 設定使用SMTP發送
			if ($smtpSecure !== "") {						// SSL
				$mail->SMTPSecure = $smtpSecure;
			}
			$mail->Host = $host;							// 指定SMTP的服務器位址
			$mail->Port = $port;							// 設定SMTP服務的POST default is 25, gmail is 465 or 587
			$mail->SMTPAuth = $smtpAuth;					// 設定為安全驗證方式
			$mail->Username = $username;					// SMTP的帳號
			$mail->Password = $password;					// SMTP的密碼
			$mail->setFrom($username);						// 寄件人Email or 寄件人名稱
			$mail->addAddress($this->toAry[0]);				// 收件人Email
			for ($i = 1; $i < count($this->toAry); $i++) {
				$mail->addCC($this->toAry[$i]);
			}
			$mail->addReplyTo($this->toAry[0]);				// 回信Email及名稱
			$mail->CharSet = "utf-8";						// 設定信件字元編碼
			$mail->Encoding = "base64";						// 設定信件編碼，大部分郵件工具都支援此編碼方式
			$mail->SMTPKeepAlive = true;
			$mail->SMTPDebug = 0;							// 1: message, 2: full result
			$mail->isHTML(true);							// 設置郵件格式為HTML
			$mail->WordWrap = 50;							// 每50自斷行
			$mail->Subject = $this->subject;				// 郵件標題
			$mail->Body = $this->body;						// 郵件內容
			$mail->send();									// 寄送郵件
			return "1";
		} catch (Exception $e) {
			return "Mailer Error: " . $mail->ErrorInfo;
		}
	}
}
?>