<?php
require_once __DIR__ . '/../auth.php';
if (function_exists('require_login')) require_login('login.php');
require_once __DIR__ . '/../db_bootstrap.php';
if (function_exists('ensure_db')) ensure_db(true);
require_once __DIR__ . '/../airmax_monitor_lib.php';
header('Content-Type: application/json; charset=utf-8');
@set_time_limit(20);

$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) {
    echo json_encode(['ok' => false, 'status' => 'failed', 'message' => 'DB not ready'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}
airmax_seed_defaults($conn);
airmax_ensure_probe_schema($conn);

$id = (int)($_GET['id'] ?? 0);
$force = !empty($_GET['force']);
if ($id <= 0) {
    echo json_encode(['ok' => false, 'status' => 'failed', 'message' => 'device id required'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$rows = airmax_get_all($conn, false);
$device = null;
foreach ($rows as $row) {
    if ((int)($row['id'] ?? 0) === $id) { $device = $row; break; }
}
if (!$device) {
    echo json_encode(['ok' => false, 'status' => 'failed', 'message' => 'device not found'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if ($force) {
    @unlink(airmax_result_cache_path($device));
    @unlink(airmax_route_cache_path($device));
}

$out = airmax_probe_and_persist($conn, $id);
echo json_encode($out, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
