<?php
declare(strict_types=1);

use PHPMailer\PHPMailer\PHPMailer;

/**
 * 发邮件，配置读 [projectDir]/config/common.php 里的 mailSendServer
 */
final class Mailer
{
    /**
     * @throws MvcException 配置缺失或发送失败时
     */
    public static function send(string $to, string $subject, string $htmlBody): void
    {
        $common = require Mvc::$cfg['projectDir'] . '/config/common.php';
        $cfg = $common['mailSendServer'] ?? null;
        if (!$cfg) {
            throw new MvcException('未配置 mailSendServer，无法发送邮件');
        }

        $mailer = new PHPMailer(true);

        try {
            $mailer->isSMTP();
            $mailer->Host = $cfg['server'];
            $mailer->Port = $cfg['port'];
            $mailer->SMTPAuth = true;
            $mailer->Username = $cfg['username'];
            $mailer->Password = $cfg['password'];
            $mailer->CharSet = 'UTF-8';

            if ((int) $cfg['port'] === 465) {
                $mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            } elseif ((int) $cfg['port'] === 587) {
                $mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            }

            $mailer->setFrom($cfg['username'], $cfg['displayname'] ?? '');
            $mailer->addAddress($to);
            $mailer->isHTML(true);
            $mailer->Subject = $subject;
            $mailer->Body = $htmlBody;

            $mailer->send();
        } catch (\Throwable $e) {
            throw new MvcException('邮件发送失败: ' . $e->getMessage());
        }
    }
}
