<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

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

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

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

    try {
        // Set up Twig
        $loader = new FilesystemLoader(__DIR__ . '/templates');
        $twig = new Environment($loader, [
            'cache' => __DIR__ . '/cache', // Optional: Enable Twig cache
            'auto_reload' => true,
        ]);

        // Render the Twig template
        $body = $twig->render($template . '.html.twig', $variables);

        // 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 Charset and Settings
        $mail->CharSet = 'UTF-8'; // Ensure correct encoding
        $mail->setFrom($_ENV['SMTP_USER'], $_ENV['BUSINESS_NAME']);
                // Handle multiple recipients
                if (is_array($to)) {
                    foreach ($to as $recipient) {
                        $mail->addAddress($recipient);
                    }
                } else {
                    $mail->addAddress($to); // Single recipient
                }
        $mail->Subject = $subject;
        $mail->isHTML(true);
        $mail->Body = $body;

        $mail->send();
        foreach ($to as $recipient) {
            echo "Email sent successfully to $recipient\n";
        }
    } catch (Exception $e) {
        echo "Error: {$mail->ErrorInfo}";
    }
}


?>
