<?php
require __DIR__ . '/email/class.phpmailer.php';
require __DIR__ . '/email/class.smtp.php';
require '../include/config.php'; // Ensure database connection

if (isset($_POST['send'])) {
    $intake = $_POST['intake'];
    $program = $_POST['program'];
    $customMessage = nl2br($_POST['message']);

    // Fetch students in the selected intake & program
    $studentQuery = "SELECT student_name, email FROM students WHERE intake='$intake' AND program='$program'";
    $studentResult = mysqli_query($conn, $studentQuery);

    if (mysqli_num_rows($studentResult) > 0) {
        $mail = new PHPMailer();
        $mail->SMTPDebug = 0;

        try {
                          include "../../email_config.php";

            while ($studentRow = mysqli_fetch_assoc($studentResult)) {
                $email = $studentRow['email'];
                $studentName = $studentRow['student_name'];
                

                if (!empty($email)) {
                    $message = "
                        <div style='font-family:Arial, sans-serif; padding:20px; background:#f4f4f4; border-radius:10px;'>
                            <h3 style='color:#333;'>Message for {$studentName} from Makeni</h3>
                            <p><strong>Intake:</strong> {$intake} <br> <strong>Program:</strong> {$program}</p>
                            <div style='background:white; padding:15px; border-radius:8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);'>
                                <p>{$customMessage}</p>
                            </div>
                            <br>
                            <hr>
                            <center>
                            </center>
                        </div>";

                    $mail->addAddress($email);
                    $mail->isHTML(true);
                    $mail->Subject = "Message from Zamaresults";
                    $mail->Body = $message;

                    if (!$mail->send()) {
                        echo "<div class='alert alert-danger text-center'>Failed to send email to {$email}: " . $mail->ErrorInfo . "</div>";
                    }

                    $mail->clearAddresses(); // Clear previous recipient before sending to the next
                }
            }

            header("Location: email.php?success=Email successfully Sent.");
    exit;
        } catch (Exception $e) {
            echo "<div class='alert alert-danger text-center'>Failed to send emails. Error: " . $e->getMessage() . "</div>";
        }
    } else {
        echo "<div class='alert alert-warning text-center'>No students found for this intake & program.</div>";
    }
}
?>