<?php
// public/admin/api_masters.php
declare(strict_types=1);
require __DIR__ . '/../../includes/db.php';
require __DIR__ . '/../../includes/auth.php';

header('Content-Type: application/json; charset=utf-8');
require_login(['super_admin']); // relax if you want district_admin to use too

function fail($msg, $code=400){
  http_response_code($code);
  echo json_encode(['error'=>$msg]);
  exit;
}

try {
  if (!isset($pdo)) fail('DB not ready', 500);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

  $mode = $_GET['mode'] ?? 'districts';

  if ($mode === 'districts') {
    $rows = $pdo->query('SELECT id, name FROM districts ORDER BY name')->fetchAll();
    echo json_encode(['districts'=>$rows]); exit;
  }

  if ($mode === 'ulbs_by_district') {
    $district_id = isset($_GET['district_id']) ? (int)$_GET['district_id'] : 0;
    if (!$district_id) fail('district_id required', 400);
    $st = $pdo->prepare('SELECT id, name FROM ulbs WHERE district_id = :d ORDER BY name');
    $st->execute(['d'=>$district_id]);
    echo json_encode(['ulbs'=>$st->fetchAll()]); exit;
  }

  fail('Unknown mode', 400);

} catch (Throwable $e) {
  fail($e->getMessage(), 500);
}
