<?php
session_start();
require_once 'db_connection.php';

/* =========================
   CHECK LOGIN
========================= */
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /* =========================
       SANITIZE INPUTS
    ========================= */
    $student_id = filter_input(INPUT_POST, 'student_id', FILTER_VALIDATE_INT);
    $subjects   = $_POST['subject_id'] ?? [];
    $class_id   = filter_input(INPUT_POST, 'class_id', FILTER_VALIDATE_INT);
    $session    = trim($_POST['session'] ?? '');
    $term       = trim($_POST['term'] ?? '');

    /* =========================
       VALIDATION
    ========================= */
    if (!$student_id || !$class_id || empty($session) || empty($term) || empty($subjects)) {
        header("Location: add_enrollment.php?error=All fields are required");
        exit();
    }

    $success = 0;
    $duplicates = 0;
    $failed = 0;

    /* =========================
       LOOP THROUGH SUBJECTS
    ========================= */
    foreach ($subjects as $subject_id) {

        $subject_id = (int) $subject_id;

        /* =========================
           CHECK DUPLICATE
        ========================= */
        $check = $conn->prepare("
            SELECT enrollment_id 
            FROM enrollments 
            WHERE student_id = ? 
            AND subject_id = ? 
            AND class_id = ? 
            AND session = ? 
            AND term = ?
        ");

        $check->bind_param("iiiss", $student_id, $subject_id, $class_id, $session, $term);
        $check->execute();
        $check->store_result();

        if ($check->num_rows > 0) {
            $duplicates++;
            $check->close();
            continue;
        }

        $check->close();

        /* =========================
           INSERT ENROLLMENT
        ========================= */
        $stmt = $conn->prepare("
            INSERT INTO enrollments 
            (student_id, subject_id, class_id, session, term) 
            VALUES (?, ?, ?, ?, ?)
        ");

        $stmt->bind_param("iiiss", $student_id, $subject_id, $class_id, $session, $term);

        if ($stmt->execute()) {
            $success++;
        } else {
            $failed++;
        }

        $stmt->close();
    }

    /* =========================
       RESPONSE MESSAGE
    ========================= */
    $message = "Enrollment complete: $success added, $duplicates skipped, $failed failed";

    header("Location: add_enrollment.php?success=" . urlencode($message));
    exit();
}

$conn->close();
?>