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

// Quick test: RouterOS API connection
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);

  $raw = file_get_contents('php://input');
  $data = json_decode($raw, true);
  if (!is_array($data)) {
    echo json_encode(['ok'=>false,'msg'=>'Invalid JSON']);
    exit;
  }

  $router = [
    'host' => trim((string)($data['host'] ?? '')),
    'api_port' => (int)($data['api_port'] ?? 8728),
    'username' => trim((string)($data['username'] ?? '')),
    'password' => (string)($data['password'] ?? ''),
  ];

  if ($router['host'] === '' || $router['username'] === '') {
    echo json_encode(['ok'=>false,'msg'=>'Missing host/username']);
    exit;
  }

  $err = '';
  $api = comms_mt_connect($router, $err);
  if (!$api) {
    echo json_encode(['ok'=>false,'msg'=>$err ?: 'Connect failed']);
    exit;
  }

  // light command to validate session
  try { $api->comm('/system/resource/print'); } catch (Throwable $e) {}
  comms_mt_safe_disconnect($api);
  echo json_encode(['ok'=>true]);
} catch (Throwable $e) {
  echo json_encode(['ok'=>false,'msg'=>$e->getMessage()]);
}
