<?php

// Use PHPMailer classes from the vendor directory
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require_once __DIR__ . '/../vendor/autoload.php';

/**
 * Sends an email using PHPMailer with SMTP.
 *
 * @param string $recipient_email The email address of the recipient.
 * @param string $subject The subject of the email.
 * @param string $body The HTML content of the email.
 * @param string $recipient_name The name of the recipient (optional).
 * @return bool True if the email was sent successfully, false otherwise.
 */
function send_email($recipient_email, $subject, $body, $recipient_name = '') {

    // --- CONFIGURATION: FILL IN YOUR SMTP DETAILS HERE ---
    define('SMTP_HOST', 'smtp.example.com');      // e.g., 'smtp.gmail.com' or your host's mail server
    define('SMTP_USERNAME', 'your-email@example.com'); // Your email address
    define('SMTP_PASSWORD', 'your-email-password');    // Your email password or App Password
    define('SMTP_PORT', 587);                     // 587 for TLS, 465 for SSL
    define('SMTP_FROM_EMAIL', 'no-reply@yourdomain.com'); // The "From" email address
    define('SMTP_FROM_NAME', 'DXP Admin Support');     // The "From" name
    // ---------------------------------------------------

    $mail = new PHPMailer(true);

    try {
        // Server settings
        // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable for detailed error output
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USERNAME;
        $mail->Password   = SMTP_PASSWORD;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Or PHPMailer::ENCRYPTION_SMTPS
        $mail->Port       = SMTP_PORT;

        // Recipients
        $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
        $mail->addAddress($recipient_email, $recipient_name);
        $mail->addReplyTo(SMTP_USERNAME, 'Support');

        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = strip_tags($body); // Plain text version for non-HTML mail clients

        $mail->send();
        return true;
    } catch (Exception $e) {
        // You can log the error for debugging: error_log("Message could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}
