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

$gp_id = strtoupper(trim((string)($_GET['gp_id'] ?? '')));
$block_id = strtoupper(trim((string)($_GET['block_id'] ?? '')));
if ($gp_id !== '') {
  try {
    $st = $pdo->prepare("SELECT id, name FROM schools WHERE gp_id=? ORDER BY name ASC");
    $st->execute([$gp_id]);
    echo json_encode($st->fetchAll(), JSON_UNESCAPED_UNICODE);
  } catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(["error" => "schools api failed"]);
  }
  exit;
}
if ($block_id !== '') {
  try {
    $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]);
    echo json_encode($st->fetchAll(), JSON_UNESCAPED_UNICODE);
  } catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(["error" => "schools api failed"]);
  }
  exit;
}
echo json_encode([]);
