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

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

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

// Get POST data
$input = json_decode(file_get_contents('php://input'), true);
$school_id = $input['school_id'] ?? null;

// Validate school ID
if (!$school_id || $school_id != $_SESSION['school_id']) {
    echo json_encode(['success' => false, 'message' => 'Invalid school ID']);
    exit;
}

try {
    // Query to get distinct grading scale names for the school
    $sql = "SELECT DISTINCT grade_name 
            FROM grading_scales 
            WHERE school_id = ? 
            ORDER BY grade_name ASC";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $school_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $grading_scales = [];
    while ($row = $result->fetch_assoc()) {
        $grading_scales[] = [
            'grade_name' => $row['grade_name']
        ];
    }
    
    $stmt->close();
    
    echo json_encode([
        'success' => true,
        'grading_scales' => $grading_scales,
        'count' => count($grading_scales)
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}

$conn->close();
?>
