<?php
// get_exam_details.php (now in the main folder)

header('Content-Type: application/json');

// Include your database connection file, now assuming it's in the same directory
require_once 'config.php'; 

$response = ['success' => false, 'message' => 'An unknown error occurred.'];

if (isset($_GET['exam_id']) && is_numeric($_GET['exam_id'])) {
    $examId = $_GET['exam_id'];

    // Start a try-catch block for database operations
    try {
        // Prepare statement to fetch exam details - CHANGED 'academic_year' to 'year'
        $stmt = $conn->prepare("SELECT exam_id, exam_name, term, year FROM exams WHERE exam_id = ?");
        if ($stmt === false) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        $stmt->bind_param("i", $examId);
        $stmt->execute();
        $result = $stmt->get_result();
        $exam = $result->fetch_assoc();
        $stmt->close();

        if ($exam) {
            // Fetch associated classes
            $stmt_classes = $conn->prepare("SELECT class_id FROM exam_classes WHERE exam_id = ?");
            if ($stmt_classes === false) {
                throw new Exception("Prepare failed (classes): " . $conn->error);
            }
            $stmt_classes->bind_param("i", $examId);
            $stmt_classes->execute();
            $result_classes = $stmt_classes->get_result();
            $classes_linked = [];
            while ($row = $result_classes->fetch_assoc()) {
                $classes_linked[] = $row['class_id'];
            }
            $stmt_classes->close();

            // Fetch associated subjects
            $stmt_subjects = $conn->prepare("SELECT subject_id FROM exam_subjects WHERE exam_id = ?");
            if ($stmt_subjects === false) {
                throw new Exception("Prepare failed (subjects): " . $conn->error);
            }
            $stmt_subjects->bind_param("i", $examId);
            $stmt_subjects->execute();
            $result_subjects = $stmt_subjects->get_result();
            $subjects_linked = [];
            while ($row = $result_subjects->fetch_assoc()) {
                $subjects_linked[] = $row['subject_id'];
            }
            $stmt_subjects->close();

            // Combine all data
            $exam['classes_linked'] = $classes_linked;
            $exam['subjects_linked'] = $subjects_linked;

            $response = ['success' => true, 'data' => $exam];

        } else {
            $response = ['success' => false, 'message' => 'Exam not found.'];
        }

    } catch (Exception $e) {
        // Log the error for debugging (e.g., to a file or server logs)
        error_log("Error in get_exam_details.php: " . $e->getMessage());
        $response = ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
    }
} else {
    $response = ['success' => false, 'message' => 'Invalid or missing exam ID.'];
}

echo json_encode($response);
$conn->close();
?>