<?php
declare(strict_types=1);
require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../config/auth.php";

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

$school_id = trim((string)($_GET['school_id'] ?? ''));
if ($school_id === '') { 
    echo json_encode(null); 
    exit; 
}

try {
    // First check if contact_no and whatsapp_no columns exist
    $columns = $pdo->query("SHOW COLUMNS FROM schools")->fetchAll(PDO::FETCH_COLUMN);
    
    $contact_field = in_array('contact_no', $columns) ? 's.contact_no' : 'NULL AS contact_no';
    $whatsapp_field = in_array('whatsapp_no', $columns) ? 's.whatsapp_no' : 'NULL AS whatsapp_no';
    
    $st = $pdo->prepare("
        SELECT 
            s.id, 
            s.name, 
            s.address, 
            s.category,
            s.gp_id AS gp_id,
            {$contact_field},
            {$whatsapp_field},
            g.name AS gp_name, 
            g.block_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) {
        echo json_encode(null);
        exit;
    }
    
    echo json_encode($school, JSON_UNESCAPED_UNICODE);
    
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(["error" => "school_details api failed: " . $e->getMessage()]);
}