<?php

declare(strict_types=1);

namespace App\Core;

use PHPMailer\PHPMailer\PHPMailer;
use Throwable;

/**
 * Envoi d'email via PHPMailer (SMTP) — D-20. Configuration dans config/local.php.
 * Retourne false sans lever d'exception si l'envoi échoue ou n'est pas configuré.
 */
final class MailService
{
    /** Valeur d'un réglage admin, sinon repli sur la config/local.php. */
    private static function cfg(string $settingKey, string $configKey, string $default = ''): string
    {
        $v = trim((string) Settings::get($settingKey, ''));
        return $v !== '' ? $v : (string) Config::get($configKey, $default);
    }

    public static function send(string $subject, string $body, string $replyToEmail, string $replyToName): bool
    {
        // Destinataire : email de réception défini en admin, sinon repli sur config/local.php.
        $to = self::cfg('contact_email', 'mail.to');
        if ($to === '') {
            return false;
        }

        require_once BASE_PATH . '/src/Vendor/PHPMailer/Exception.php';
        require_once BASE_PATH . '/src/Vendor/PHPMailer/PHPMailer.php';
        require_once BASE_PATH . '/src/Vendor/PHPMailer/SMTP.php';

        try {
            $mail = new PHPMailer(true);
            $mail->CharSet = 'UTF-8';

            $smtpHost = self::cfg('mail_smtp_host', 'mail.smtp.host');
            if ($smtpHost !== '') {
                $mail->isSMTP();
                $mail->Host = $smtpHost;
                $mail->Port = (int) self::cfg('mail_smtp_port', 'mail.smtp.port', '587');
                $user = self::cfg('mail_smtp_user', 'mail.smtp.user');
                if ($user !== '') {
                    $mail->SMTPAuth = true;
                    $mail->Username = $user;
                    $mail->Password = self::cfg('mail_smtp_pass', 'mail.smtp.pass');
                }
                $secure = self::cfg('mail_smtp_secure', 'mail.smtp.secure', 'tls');
                if ($secure !== '' && $secure !== 'none') {
                    $mail->SMTPSecure = $secure;
                }
            }

            $from = self::cfg('mail_from_email', 'mail.from');
            $mail->setFrom($from !== '' ? $from : $to, self::cfg('mail_from_name', 'mail.from_name', 'Site'));
            $mail->addAddress($to);
            if (filter_var($replyToEmail, FILTER_VALIDATE_EMAIL)) {
                $mail->addReplyTo($replyToEmail, $replyToName);
            }

            $mail->isHTML(false);
            $mail->Subject = $subject;
            $mail->Body    = $body;

            return $mail->send();
        } catch (Throwable) {
            return false;
        }
    }
}
