<?php
declare(strict_types=1);

require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../config/auth.php';

require_login();
header('Content-Type: application/json; charset=utf-8');

$school_id = trim((string)($_GET['school_id'] ?? ''));
if ($school_id === '') {
    http_response_code(400);
    echo json_encode(['error' => 'school_id is required']);
    exit;
}

try {
    $st = $pdo->prepare("
        SELECT 
            s.id, 
            s.name, 
            s.address, 
            s.category,
            s.contact_no,
            s.whatsapp_no,
            g.id AS gp_id, 
            g.name AS gp_name,
            b.id AS block_id, 
            b.name AS block_name,
            b.district_id AS district_id,
            d.name AS district_name
        FROM schools s
        JOIN gps g ON g.id = s.gp_id
        JOIN blocks b ON b.id = g.block_id
        LEFT JOIN districts d ON d.id = b.district_id
        WHERE s.id = ?
        LIMIT 1
    ");
    
    $st->execute([$school_id]);
    $school = $st->fetch(PDO::FETCH_ASSOC);
    
    if (!$school) {
        http_response_code(404);
        echo json_encode(['error' => 'School not found']);
        exit;
    }
    
    echo json_encode($school, JSON_UNESCAPED_UNICODE);
    
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}