<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/src/PHPMailer.php';
require_once __DIR__ . '/src/SMTP.php';
require_once __DIR__ . '/src/Exception.php';

function sendMail($to, $subject, $htmlBody, $dynamicTags = []) {
    $settingsFile = __DIR__ . '/email-templates.json';

    if (!file_exists($settingsFile)) {
        error_log("Mailer error: email-templates.json not found.");
        return false;
    }

    $settings = json_decode(file_get_contents($settingsFile), true);

    // ✅ Inject login_url if not already provided
    if (!isset($dynamicTags['login_url']) && isset($settings['base_url'])) {
        $dynamicTags['login_url'] = rtrim($settings['base_url'], '/') . '/user-login.php';
    }

    // ✅ Replace all {{tag}} with dynamic values
    foreach ($dynamicTags as $tag => $value) {
        $subject = str_replace("{{{$tag}}}", $value, $subject);
        $htmlBody = str_replace("{{{$tag}}}", $value, $htmlBody);
    }

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


    try {
        $mail->isSMTP();
        $mail->Host       = $settings['smtp_host'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $settings['smtp_user'];
        $mail->Password   = $settings['smtp_pass'];
        $mail->SMTPSecure = $settings['smtp_secure'];
        $mail->Port       = $settings['smtp_port'];

        $mail->setFrom($settings['from_email'], $settings['from_name']);
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = nl2br($htmlBody);

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Mailer error: " . $mail->ErrorInfo);
        return false;
    }
}
?>
