<?php
require_once 'config.php';

function sendEmail($to, $subject, $body, $isHTML = true) {
    // Using PHPMailer (recommended) or native mail()
    require_once 'vendor/autoload.php'; // If using Composer
    
    $mail = new PHPMailer\PHPMailer\PHPMailer();
    
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host       = EMAIL_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = EMAIL_USERNAME;
        $mail->Password   = EMAIL_PASSWORD;
        $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = EMAIL_PORT;
        
        // Recipients
        $mail->setFrom(EMAIL_FROM, 'JV Overseas Education');
        $mail->addAddress($to);
        
        // Content
        $mail->isHTML($isHTML);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        
        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Email sending failed: " . $mail->ErrorInfo);
        return false;
    }
}

function sendPasswordResetEmail($email, $token) {
    $resetLink = SITE_URL . "/dashboard/reset-password.php?token=" . urlencode($token);
    
    $subject = "Password Reset Request";
    $body = "
        <h2>Password Reset</h2>
        <p>You requested a password reset for your JV Overseas Education account.</p>
        <p>Please click the link below to reset your password:</p>
        <p><a href='$resetLink'>$resetLink</a></p>
        <p>If you didn't request this, please ignore this email.</p>
    ";
    
    return sendEmail($email, $subject, $body);
}

function sendApplicationStatusEmail($studentEmail, $universityName, $status) {
    $subject = "Application Status Update: $universityName";
    $body = "
        <h2>Application Status Update</h2>
        <p>Your application to $universityName has been updated to: <strong>$status</strong></p>
        <p>Log in to your dashboard for more details.</p>
    ";
    
    return sendEmail($studentEmail, $subject, $body);
}
?>