<?php

require_once '../auth/auth.php';
require_once '../models/db_connection.php';
if (isset($_POST['enrollStudent'])) {
    // Validate input
    $enID = mysqli_real_escape_string($conn, $_POST['enID']);
    $courseID = mysqli_real_escape_string($conn, $_POST['courseID']);
    $enDate = mysqli_real_escape_string($conn, $_POST['enDate']);
    $checkEnrollment = mysqli_query($conn, "SELECT * FROM student_course WHERE s_id = '$enID' AND course_id = '$courseID'");
    if (mysqli_num_rows($checkEnrollment) > 0) {
        $err = 'Student is already enrolled in this course.';
    } else {
        // Insert into student_course table
        $enroll = mysqli_query($conn, "INSERT INTO student_course (s_id, course_id, en_date) VALUES ('$enID', '$courseID', '$enDate')");

        if ($enroll) {
            // Update student status
            $st = mysqli_query($conn, "UPDATE students SET status = 'enrolled' WHERE en_id = '$enID'");

            if ($st) {
                $succ = 'Student enrolled successfully';
            } else {
                $err = 'Failed to update student status. Please try again.';
            }
        } else {
            echo "<script>
    alert('Enrollment failed: " . mysqli_error($conn) . "');
</script>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Loading Spinner</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .loading-message {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <div class="d-flex flex-column align-items-center justify-content-center vh-100">
        <!-- Bootstrap Spinner -->
        <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
            <span class="visually-hidden">Loading...</span>
        </div>
        <!-- Message -->
        <div class="loading-message">
            Please wait, enrolling student...<br/>
            <?php
            if (isset($succ)) {
                echo $succ;
                echo "<script>
          setTimeout(() => {
              window.location.href = 'view_students.php';
          }, 3000);
      </script>";
            } else {
                echo $err;
                echo "<script>
          setTimeout(() => {
              window.location.href = 'enroll_student.php';
          }, 3000);
      </script>";

            }
            ?>
        </div>
    </div>

    <!-- Bootstrap JS (Optional, for interactive components) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>