<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

$exam_id = $_GET['exam_id'] ?? '';

if (!$exam_id) {
    http_response_code(400);
    echo json_encode(['error' => 'Exam ID required']);
    exit();
}

try {
    $stmt = $pdo->prepare("
        SELECT es.subject_id, s.name as subject_name, s.code as subject_code,
               es.exam_date, es.start_time, es.end_time, es.room_number
        FROM exam_subjects es
        JOIN subjects s ON es.subject_id = s.id
        WHERE es.exam_id = ?
        ORDER BY es.exam_date, es.start_time
    ");
    $stmt->execute([$exam_id]);
    $subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format dates for display
    foreach ($subjects as &$subject) {
        $subject['exam_date'] = date('d/m/Y', strtotime($subject['exam_date']));
    }
    
    header('Content-Type: application/json');
    echo json_encode($subjects);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>