<?php

namespace app\common\library;

use PHPMailer\PHPMailer\PHPMailer;

/**
 * 邮件类（Webman 迁移版）
 */
class Email extends PHPMailer
{
    public bool $configured = false;

    public array $options = [
        'charset' => 'utf-8',
        'debug' => true,
        'lang' => 'zh_cn',
    ];

    public function __construct(array $options = [])
    {
        $this->options = array_merge($this->options, $options);

        parent::__construct($this->options['debug']);

        $langSet = function_exists('locale') ? locale() : 'zh_CN';
        if ($langSet == 'zh-cn' || $langSet == 'zh_CN' || !$langSet) {
            $langSet = 'zh_cn';
        }
        $this->options['lang'] = $this->options['lang'] ?: $langSet;

        $langPath = root_path() . 'vendor' . DIRECTORY_SEPARATOR . 'phpmailer' . DIRECTORY_SEPARATOR . 'phpmailer' . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
        if (is_dir($langPath)) {
            $this->setLanguage($this->options['lang'], $langPath);
        }
        $this->CharSet = $this->options['charset'];

        $sysMailConfig = get_sys_config('', 'mail');
        $this->configured = true;
        if (is_array($sysMailConfig)) {
            foreach ($sysMailConfig as $item) {
                if (!$item) {
                    $this->configured = false;
                    break;
                }
            }
        } else {
            $this->configured = false;
        }

        if ($this->configured) {
            $this->Host = $sysMailConfig['smtp_server'];
            $this->SMTPAuth = true;
            $this->Username = $sysMailConfig['smtp_user'];
            $this->Password = $sysMailConfig['smtp_pass'];
            $this->SMTPSecure = ($sysMailConfig['smtp_verification'] ?? '') == 'SSL' ? self::ENCRYPTION_SMTPS : self::ENCRYPTION_STARTTLS;
            $this->Port = $sysMailConfig['smtp_port'] ?? 465;
            $this->setFrom($sysMailConfig['smtp_sender_mail'] ?? '', $sysMailConfig['smtp_user'] ?? '');
        }
    }

    public function setSubject($subject): void
    {
        $this->Subject = "=?utf-8?B?" . base64_encode($subject) . "?=";
    }
}
