<?php
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../helpers.php';
require_once __DIR__ . '/../mikrotik_lib.php';

require_login();
if(function_exists('require_perm')) require_perm('can_settings');

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

try {
  // ✅ Use library test helper (works regardless of mt_api_connect() signature)
  if(function_exists('mt_api_test')){
    $r = mt_api_test();
    $ok = !empty($r['ok']);
    echo json_encode([
      'ok'        => $ok,
      'connected' => $ok,
      'message'   => $r['msg'] ?? ''
    ], JSON_UNESCAPED_UNICODE);
  } else {
    // Fallback: attempt connect without passing $conn
    $api = mt_api_connect();
    if($api && method_exists($api,'disconnect')) { @ $api->disconnect(); }
    echo json_encode(['ok'=>true,'connected'=>true], JSON_UNESCAPED_UNICODE);
  }
} catch (Throwable $e) {
  echo json_encode(['ok'=>false,'connected'=>false,'error'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
