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

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

function send_email($to_email, $to_name, $subject, $body_html, $body_plain = '') {
    $mail = new PHPMailer(true);

    try {
        // Server config
        $mail->isSMTP();
        $mail->Host       = 'mail.tandddrivingacademy.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'no-reply@tandddrivingacademy.com';
        $mail->Password   = '!ResetPassword1!';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = 465;

        // Recipients
        $mail->setFrom('no-reply@tandddrivingacademy.com', 'T&D Driving Academy');
        $mail->addAddress($to_email, $to_name);

        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body_html;
        $mail->AltBody = $body_plain ?: strip_tags($body_html);

        $mail->send();
        error_log("Email sent to $to_email at " . date("Y-m-d H:i:s") . "\n", 3, __DIR__ . "/../logs/email.log");
        return true;

    } catch (Exception $e) {
        error_log("Email error: " . $mail->ErrorInfo);
        return false;
    }
}
