<?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');

$gp_id    = strtoupper(trim((string)($_GET['gp_id'] ?? '')));
$block_id = strtoupper(trim((string)($_GET['block_id'] ?? '')));

try {

    if ($gp_id !== '') {
        // GP ভিত্তিক filter
        $st = $pdo->prepare("
            SELECT id, name 
            FROM schools 
            WHERE gp_id=? 
            ORDER BY name ASC
        ");
        $st->execute([$gp_id]);
    }
    elseif ($block_id !== '') {
        // Block ভিত্তিক filter (GP skip করলে)
        $st = $pdo->prepare("
            SELECT s.id, s.name
            FROM schools s
            JOIN gps g ON g.id = s.gp_id
            WHERE g.block_id=?
            ORDER BY s.name ASC
        ");
        $st->execute([$block_id]);
    }
    else {
        echo json_encode([]);
        exit;
    }

    echo json_encode($st->fetchAll(), JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(["error"=>"schools_failed"]);
}
