<?php
// send_email.php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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

// Load .env variables if not already loaded
if (file_exists(__DIR__ . '/../auth/load_env.php')) {
    require_once __DIR__ . '/../auth/load_env.php';
}

/**
 * Send email using Brevo SMTP via PHPMailer
 *
 * @param string $to_email Recipient email
 * @param string $to_name Recipient name
 * @param string $subject Email subject
 * @param string $body HTML body of the email
 * @param string|null $alt_body Optional plain text version
 * @return bool|string Returns true on success, or error message on failure
 */
function send_email($to_email, $to_name, $subject, $body, $alt_body = null) {
    try {
        $mail = new PHPMailer(true);

        // SMTP configuration
        $mail->isSMTP();
        $mail->Host       = $_ENV['BREVO_SMTP_HOST'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $_ENV['BREVO_SMTP_USER'];
        $mail->Password   = $_ENV['BREVO_SMTP_PASS'];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = (int)$_ENV['BREVO_SMTP_PORT'];

        // Sender
        $mail->setFrom($_ENV['BREVO_FROM_EMAIL'], $_ENV['BREVO_FROM_NAME']);

        // Primary recipient
        $mail->addAddress($to_email, $to_name);

        // Always BCC to system email for tracking
        if (!empty($_ENV['SYSTEM_EMAIL'])) {
            $mail->addBCC($_ENV['SYSTEM_EMAIL']);
        }

        // Email content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = $alt_body ?? strip_tags($body);

        $mail->send();
        return true;

    } catch (Exception $e) {
        return "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}