<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode([]); exit; }
header('Content-Type: application/json');
$conn = getDBConnection();
$paperId = (int) ($_POST['paper_id'] ?? 0);
$className = trim((string) ($_POST['class_name'] ?? ''));
if (!$conn instanceof mysqli || $paperId <= 0 || $className === '') { echo json_encode([]); exit; }
$stmt = $conn->prepare("SELECT er.*, s.first_name, s.last_name, s.student_id AS student_code, s.id AS base_student_id
                        FROM students s
                        LEFT JOIN exam_results er ON er.student_id = s.id AND er.paper_id = ?
                        WHERE s.class = ?
                        ORDER BY s.first_name, s.last_name");
$stmt->bind_param('is', $paperId, $className);
$stmt->execute();
$result = $stmt->get_result();
$rows = [];
while ($row = $result->fetch_assoc()) { $rows[] = $row; }
$stmt->close();
echo json_encode($rows);
