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

// Run quick API tests for routers saved in DB
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']);
    exit;
  }
  comms_ensure_tables($conn);

  $routers = comms_get_routers($conn);
  $items = [];
  foreach ($routers as $r) {
    $err = '';
    $api = comms_mt_connect($r, $err);
    if ($api) {
      comms_mt_safe_disconnect($api);
      $items[] = ['name'=>$r['name'].' ('.$r['role'].')','ok'=>true];
    } else {
      $items[] = ['name'=>$r['name'].' ('.$r['role'].')','ok'=>false,'msg'=>$err];
    }
  }

  $deep = comms_test_all($conn);
  if (!empty($deep['ok']) && !empty($deep['results']) && is_array($deep['results'])) {
    foreach ($deep['results'] as $row) {
      $items[] = [
        'name' => (string)($row['ar'] ?? ($row['k'] ?? 'اختبار')),
        'ok' => !empty($row['ok']),
        'msg' => (string)($row['v'] ?? ''),
      ];
    }
  } elseif (empty($items)) {
    echo json_encode(['ok'=>false,'msg'=>$deep['msg'] ?? 'لا توجد راوترات معرفة للاختبار.'], JSON_UNESCAPED_UNICODE);
    exit;
  }

  echo json_encode(['ok'=>true,'items'=>$items,'results'=>$deep['results'] ?? []], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
  echo json_encode(['ok'=>false,'msg'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
