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

require_once '../envLoader.php';
loadEnv('../../.env');

require '../../vendor/autoload.php';

function sendEmail($to, $subject, $template, $variables = []) {
    $mail = new PHPMailer(true);

    try {
        // Load the template
        $templatePath = __DIR__ . "/templates/$template.html";
        if (!file_exists($templatePath)) {
            throw new Exception("Template not found: $template");
        }

        $body = file_get_contents($templatePath);

        // Replace variables
        foreach ($variables as $key => $value) {
            print_r($key);
            $body = str_replace("{{" . $key . "}}", strval($value), $body);
        }

        // Add environment-based dynamic replacements
        $body = str_replace("{{website_url}}", strval($_ENV['WEBSITE_URL']), $body);
        $body = str_replace("{{business_name}}", strval($_ENV['BUSINESS_NAME']), $body);

        // SMTP Configuration
        $mail->isSMTP();
        $mail->Host = $_ENV['SMTP_HOST'];
        $mail->SMTPAuth = true;
        $mail->Username = $_ENV['SMTP_USER'];
        $mail->Password = $_ENV['SMTP_PASS'];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = $_ENV['SMTP_PORT'];

        // Email Settings
        $mail->setFrom($_ENV['SMTP_USER'], $_ENV['BUSINESS_NAME']);
        $mail->addAddress($to);
        $mail->Subject = $subject;
        $mail->isHTML(true);
        $mail->Body = $body;

        $mail->send();
        echo "Email sent successfully to $to";
    } catch (Exception $e) {
        echo "Error: {$mail->ErrorInfo}";
    }
}
?>
