<?php
include('session_validator.php');
include('includes/db.php');

// Ensure response is in JSON format
header('Content-Type: application/json');

if (isset($_POST['exam_id']) && isset($_POST['class_ids'])) {
    $examId = $_POST['exam_id'];
    $classIds = $_POST['class_ids'];

    if (!empty($classIds)) {
        // Create placeholders for SQL IN clause
        $placeholders = implode(',', array_fill(0, count($classIds), '?'));
        $query = "SELECT s.student_id, s.regd_id, s.registration_no, s.name, s.class_id, c.class_name, c.section
                  FROM students s
                  JOIN classes c ON s.class_id = c.class_id
                  WHERE s.class_id IN ($placeholders)
                  ORDER BY  s.registration_no, c.class_name, s.name";

        if ($stmt = $conn->prepare($query)) {
            // Bind the class IDs as parameters
            $stmt->bind_param(str_repeat("i", count($classIds)), ...$classIds);

            // Execute the query
            if ($stmt->execute()) {
                $result = $stmt->get_result();
                $students = [];
                while ($row = $result->fetch_assoc()) {
                    $students[] = $row;
                }

                // Return the students as a JSON response
                echo json_encode($students);  // Make sure to use json_encode here
            } else {
                // If there was an issue executing the query
                echo json_encode(["error" => "Query execution failed"]);
            }
        } else {
            // If there was an issue preparing the query
            echo json_encode(["error" => "Database query preparation failed"]);
        }
    } else {
        // Return empty array if classIds is empty
        echo json_encode([]);
    }
} else {
    // Return an error if exam_id or class_ids are not provided
    echo json_encode(["error" => "Required parameters are missing"]);
}
?>
