<?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();
if (!$conn instanceof mysqli) { echo json_encode([]); exit; }
$sql = "SELECT es.*, ep.title AS paper_title, ep.class_name AS paper_class_name, s.subject_name, st.full_name AS invigilator_name
        FROM exam_schedules es
        LEFT JOIN exam_papers ep ON es.paper_id = ep.id
        LEFT JOIN subjects s ON ep.subject_id = s.id
        LEFT JOIN staff st ON es.invigilator_id = st.id
        ORDER BY es.exam_date ASC, es.start_time ASC";
$result = $conn->query($sql);
$rows = [];
while ($row = $result->fetch_assoc()) { $rows[] = $row; }
echo json_encode($rows);
