<?php
require_once 'config.php'; // Adjust path as needed
header('Content-Type: application/json');

$class_id = isset($_GET['class_id']) ? intval($_GET['class_id']) : 0;
$subject_id = isset($_GET['subject_id']) ? intval($_GET['subject_id']) : 0;
$exam_id = isset($_GET['exam_id']) ? intval($_GET['exam_id']) : 0;

$response_data = ['students' => []];

if ($class_id > 0 && $subject_id > 0 && $exam_id > 0 && isset($conn) && $conn instanceof mysqli) {
    // Fetch students in the specified class
    $sql_students = "SELECT id, username FROM users WHERE class_id = ? AND role = " . ROLE_STUDENT . " ORDER BY username ASC";
    $students = [];
    if ($stmt_students = $conn->prepare($sql_students)) {
        $stmt_students->bind_param("i", $class_id);
        $stmt_students->execute();
        $result_students = $stmt_students->get_result();
        while ($row = $result_students->fetch_assoc()) {
            $students[$row['id']] = ['id' => $row['id'], 'username' => htmlspecialchars($row['username']), 'score' => null];
        }
        $stmt_students->close();
    }

    // Fetch existing marks for these students for the given exam and subject
    if (!empty($students)) {
        $student_ids = implode(',', array_keys($students));
        $sql_marks = "SELECT student_id, score FROM marks WHERE exam_id = ? AND subject_id = ? AND student_id IN ($student_ids)";
        if ($stmt_marks = $conn->prepare($sql_marks)) {
            $stmt_marks->bind_param("ii", $exam_id, $subject_id);
            $stmt_marks->execute();
            $result_marks = $stmt_marks->get_result();
            while ($row = $result_marks->fetch_assoc()) {
                if (isset($students[$row['student_id']])) {
                    $students[$row['student_id']]['score'] = $row['score'];
                }
            }
            $stmt_marks->close();
        }
    }
    $response_data['students'] = array_values($students); // Convert associative array back to indexed
    $conn->close();
}
echo json_encode($response_data);
?>