<?php
require_once __DIR__.'/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => false, 'public' => true]);
require_once __DIR__.'/../../engine/Logger.php';
try {
  $ministry = $_GET['ministry']??'';
  $where = 'is_active=1';
  $params = [];
  if($ministry){$where.=' AND ministry=?';$params[]=$ministry;}
  $st = db()->prepare("SELECT * FROM sdpay_gov_services WHERE {$where} ORDER BY ministry,service_name_ar");
  $st->execute($params);
  $services = $st->fetchAll();
  $grouped = [];
  foreach($services as $s){ $grouped[$s['ministry']][] = $s; }
  echo json_encode(['ok'=>true,'data'=>$services,'grouped'=>$grouped], JSON_UNESCAPED_UNICODE);
} catch(Throwable $e){http_response_code(500);echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);}
