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

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

// Set content type to JSON
header('Content-Type: application/json');

try {
    // Get POST data
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        echo json_encode(['success' => false, 'message' => 'Invalid JSON input']);
        exit;
    }
    
    $school_id = $input['school_id'] ?? 0;
    $academic_year = $input['academic_year'] ?? '';
    $term = $input['term'] ?? '';
    
    // Validate inputs
    if (empty($school_id) || empty($academic_year) || empty($term)) {
        echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
        exit;
    }
    
    // Validate school_id matches user's school
    if ($school_id != $_SESSION["school_id"]) {
        echo json_encode(['success' => false, 'message' => 'Invalid school access']);
        exit;
    }
    
    // Fetch exams from database
    $sql = "SELECT exam_id, exam_name, term, year 
            FROM exams 
            WHERE school_id = ? AND year = ? AND term = ? 
            ORDER BY exam_name ASC";
    
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("iss", $school_id, $academic_year, $term);
        
        if ($stmt->execute()) {
            $result = $stmt->get_result();
            $exams = [];
            
            while ($row = $result->fetch_assoc()) {
                $exams[] = [
                    'exam_id' => $row['exam_id'],
                    'exam_name' => htmlspecialchars($row['exam_name']),
                    'term' => htmlspecialchars($row['term']),
                    'year' => htmlspecialchars($row['year'])
                ];
            }
            
            echo json_encode([
                'success' => true, 
                'exams' => $exams,
                'count' => count($exams)
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Database query failed: ' . $conn->error]);
        }
        $stmt->close();
    } else {
        echo json_encode(['success' => false, 'message' => 'Database preparation failed: ' . $conn->error]);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}

$conn->close();
?>