<?php
ini_set('display_errors', '0');

require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/api_common.php';

api_require_login();
if (function_exists('require_any_perm')) {
  require_any_perm(['can_settings','can_mikrotik_sync']);
} elseif (function_exists('require_perm')) {
  require_perm('can_settings');
}

require_once __DIR__ . '/../comms_admin_lib.php';

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

try {
  $conn = ensure_db(false);
  if (!$conn || !($conn instanceof mysqli)) {
    echo json_encode(['ok'=>false,'code'=>'DB','msg'=>'Database connection not initialized'], JSON_UNESCAPED_UNICODE);
    exit;
  }

  comms_ensure_tables($conn);
  $result = comms_detect_topology($conn);
  $links = is_array($result) ? ($result['links'] ?? []) : [];

  echo json_encode([
    'ok' => !empty($result['ok']),
    'msg' => $result['msg'] ?? '',
    'links' => $links,
    'result' => $result,
  ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['ok'=>false,'msg'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
