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

require '../vendor/autoload.php'; // Make sure PHPMailer is installed via Composer

// Load SMTP settings from the session or fallback to the config file
$smtpConfig = isset($_SESSION['smtp_settings']) ? $_SESSION['smtp_settings'] : require 'smtp_config.php';

function sendEmail($to, $subject, $body) {
    global $smtpConfig;

    $mail = new PHPMailer(true);
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = $smtpConfig['smtp_host'];
        $mail->Port = $smtpConfig['smtp_port'];
        $mail->SMTPSecure = $smtpConfig['smtp_encryption'];
        $mail->SMTPAuth = true;
        $mail->Username = $smtpConfig['smtp_username'];
        $mail->Password = $smtpConfig['smtp_password'];

        // Recipients
        $mail->setFrom($smtpConfig['smtp_username']);
        $mail->addAddress($to);

        // Content
        $mail->Subject = $subject;
        $mail->Body    = $body;

        // Send email
        $mail->send();
        return 'Message has been sent';
    } catch (Exception $e) {
        return "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}
