<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/../../config/env.php';
require_once __DIR__ . '/templates/loader.php';

/**
 * Build and optionally send mail from a file-based template.
 */
function sendMailFromTemplate(string $templateKey, bool $previewOnly = false): bool
{
    $mail = new PHPMailer(true);

    $email    = $_ENV['MAIL_TO'];
    $username = $_ENV['USERNAME'];

    try {
        $mail->isSMTP();
        $mail->Host       = $_ENV['MAIL_HOST'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $_ENV['MAIL_USERNAME'];
        $mail->Password   = $_ENV['MAIL_PASSWORD'];
        $mail->SMTPSecure = $_ENV['MAIL_ENCRYPTION'];
        $mail->Port       = (int) $_ENV['MAIL_PORT'];

        $mail->setFrom($_ENV['MAIL_FROM'], $_ENV['MAIL_FROM_NAME']);
        $mail->addAddress($email, $username);

        $domain           = $_ENV['DOMAIN'] ?? 'UNKNOWN DOMAIN';
        $company          = $_ENV['COMPANY_NAME'] ?? 'UNKNOWN COMPANY';
        $github           = $_ENV['GITHUB'] ?? 'UNKNOWN GITHUB';
        $website          = $_ENV['WEBSITE'] ?? 'UNKNOWN WEBSITE';
        $projectStartYear = $_ENV['PROJECT_START_YEAR'] ?? 2025;
        $currentYear      = (int) date('Y');
        $startYear        = min((int) $projectStartYear, $currentYear);
        $yearText         = ($currentYear > $startYear)
            ? $startYear . '-' . substr((string) $currentYear, -2)
            : $startYear;

        // context passed to template files
        $ctx = [
            'email'    => $email,
            'username' => $username,
            'domain'   => $domain,
            'company'  => $company,
            'github'   => $github,
            'website'  => $website,
            'yearText' => $yearText,
        ];

        // 🔥 load subject + body from the selected template file
        $tpl = loadMailTemplate($templateKey, $ctx);

        $mail->CharSet  = 'UTF-8';
        $mail->Encoding = 'base64';
        $mail->isHTML(true);
        $mail->Subject  = $tpl['subject'];
        $mail->Body     = $tpl['body'];

        // expose everything for preview
        $GLOBALS['MAIL_PREVIEW_SUBJECT']    = $mail->Subject;
        $GLOBALS['MAIL_PREVIEW_BODY']       = $mail->Body;
        $GLOBALS['MAIL_PREVIEW_TO']         = $email;
        $GLOBALS['MAIL_PREVIEW_USERNAME']   = $username;
        $GLOBALS['MAIL_PREVIEW_DOMAIN']     = $domain;
        $GLOBALS['MAIL_PREVIEW_COMPANY']    = $company;
        $GLOBALS['MAIL_PREVIEW_FROM']       = $_ENV['MAIL_FROM'];
        $GLOBALS['MAIL_PREVIEW_FROM_NAME']  = $_ENV['MAIL_FROM_NAME'];

        $GLOBALS['MAIL_PREVIEW_MAIL_HOST']       = $_ENV['MAIL_HOST']       ?? null;
        $GLOBALS['MAIL_PREVIEW_MAIL_USERNAME']   = $_ENV['MAIL_USERNAME']   ?? null;
        $GLOBALS['MAIL_PREVIEW_MAIL_PORT']       = $_ENV['MAIL_PORT']       ?? null;
        $GLOBALS['MAIL_PREVIEW_MAIL_ENCRYPTION'] = $_ENV['MAIL_ENCRYPTION'] ?? null;
        $GLOBALS['MAIL_PREVIEW_PROJECT_START']   = $startYear;
        $GLOBALS['MAIL_PREVIEW_CURRENT_YEAR']    = $currentYear;
        $GLOBALS['MAIL_PREVIEW_MAIL_PASSWORD']   = empty($_ENV['MAIL_PASSWORD']) ? 'not set' : '•••• (configured)';

        // template info for UI
        $GLOBALS['MAIL_PREVIEW_TEMPLATE_KEY']   = $tpl['key'];
        $GLOBALS['MAIL_PREVIEW_TEMPLATE_LABEL'] = $tpl['label'];
        $GLOBALS['MAIL_PREVIEW_TEMPLATES_INDEX'] = getMailTemplatesIndex($ctx);

        if ($previewOnly) {
            return true;
        }

        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log('Mailer Error: ' . $mail->ErrorInfo);
        return false;
    } catch (\Throwable $e) {
        error_log('Mailer Exception: ' . $e->getMessage());
        return false;
    }
}

/**
 * Backwards-compatible wrapper.
 * Default template: 'quary'
 */
function sendAccountCreationMail(bool $previewOnly = false, string $templateKey = 'quary'): bool
{
    return sendMailFromTemplate($templateKey, $previewOnly);
}