<?php

declare(strict_types=1);

use PHPMailer\PHPMailer\PHPMailer;

require_once dirname(__DIR__) . '/vendor/autoload.php';

/**
 * Build a configured PHPMailer instance. Credentials remain in .env only.
 */
function iav_make_mailer(array $config): PHPMailer
{
    $mailer = new PHPMailer(true);
    $mailer->CharSet = PHPMailer::CHARSET_UTF8;
    $mailer->Encoding = PHPMailer::ENCODING_BASE64;
    $mailer->Timeout = (int) $config['timeout'];

    if ($config['transport'] === 'smtp') {
        $mailer->isSMTP();
        $mailer->Host = (string) $config['host'];
        $mailer->Port = (int) $config['port'];
        $mailer->SMTPAuth = $config['username'] !== '';
        $mailer->Username = (string) $config['username'];
        $mailer->Password = (string) $config['password'];
        $mailer->SMTPAutoTLS = true;

        $mailer->SMTPSecure = match (strtolower((string) $config['encryption'])) {
            'ssl', 'smtps' => PHPMailer::ENCRYPTION_SMTPS,
            'tls', 'starttls' => PHPMailer::ENCRYPTION_STARTTLS,
            default => '',
        };
    } else {
        $mailer->isMail();
    }

    $mailer->setFrom($config['from']['address'], $config['from']['name']);
    if ($config['reply_to'] !== '') {
        $mailer->addReplyTo($config['reply_to'], $config['from']['name'] . ' Support');
    }

    $mailer->isHTML(true);
    $mailer->XMailer = 'Instant AI Virtuals Mailer';

    return $mailer;
}
