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

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

// 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);
$school_id = $input['school_id'] ?? $_SESSION["school_id"];

$classes = [];

if (isset($conn) && $conn instanceof mysqli) {
    $sql = "SELECT class_id, class_name FROM classes WHERE school_id = ? ORDER BY class_name ASC";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $school_id);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $classes[] = [
                'class_id' => $row['class_id'],
                'class_name' => $row['class_name']
            ];
        }
        $stmt->close();
    }
    $conn->close();
}

echo json_encode([
    'success' => true,
    'classes' => $classes
]);
?>