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

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

// For debugging - you can enable this temporarily
$debug = true;

try {
    // Check if user is logged in and has admin role
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 1) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
        exit;
    }

    $input = json_decode(file_get_contents('php://input'), true);
    
    if ($debug) {
        error_log("get_exams.php - Raw input: " . file_get_contents('php://input'));
        error_log("get_exams.php - Decoded input: " . print_r($input, true));
    }
    
    $school_id = $input['school_id'] ?? $_SESSION["school_id"];
    $academic_year = $input['academic_year'] ?? '';
    $term = $input['term'] ?? '';

    if ($debug) {
        error_log("get_exams.php - school_id: $school_id, academic_year: $academic_year, term: $term");
    }

    $exams = [];

    if (!isset($conn) || !($conn instanceof mysqli)) {
        echo json_encode(['success' => false, 'message' => 'Database connection failed']);
        exit;
    }

    if (empty($academic_year) || empty($term)) {
        echo json_encode(['success' => false, 'message' => 'Academic year and term are required', 'academic_year' => $academic_year, 'term' => $term]);
        exit;
    }

    $sql = "SELECT exam_id, exam_name, term, year FROM exams WHERE school_id = ? AND year = ? AND term = ? ORDER BY exam_name ASC";
    
    if ($debug) {
        error_log("get_exams.php - SQL: $sql");
    }
    
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("iss", $school_id, $academic_year, $term);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $exams[] = [
                'exam_id' => $row['exam_id'],
                'exam_name' => $row['exam_name'],
                'term' => $row['term'],
                'year' => $row['year']
            ];
        }
        $stmt->close();
        
        if ($debug) {
            error_log("get_exams.php - Found " . count($exams) . " exams");
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to prepare SQL statement: ' . $conn->error]);
        exit;
    }
    
    $conn->close();

    echo json_encode([
        'success' => true,
        'exams' => $exams,
        'count' => count($exams)
    ]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>