<?php
require_once __DIR__ . '/../auth.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,'error'=>'DB not ready'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    exit;
}
airmax_seed_defaults($conn);
airmax_ensure_probe_schema($conn);

$id = (int)($_GET['id'] ?? 0);
$fresh = !empty($_GET['fresh']);

if ($id > 0) {
    $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,'error'=>'device not found'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        exit;
    }
    if ($fresh) {
        @unlink(airmax_result_cache_path($device));
        @unlink(airmax_route_cache_path($device));
        $out = airmax_probe_and_persist($conn, $id);
    } else {
        $cached = airmax_json_read(airmax_result_cache_path($device), null);
        $out = (is_array($cached) && isset($cached['out'])) ? $cached['out'] : airmax_probe_and_persist($conn, $id);
    }
    echo json_encode($out, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    exit;
}

$devices = [];
foreach (airmax_get_all($conn, true) as $d) {
    $cached = airmax_json_read(airmax_result_cache_path($d), null);
    if (is_array($cached) && isset($cached['out']['probe'])) {
        $p = $cached['out']['probe'];
        $devices[] = [
            'id'=>(int)($d['id'] ?? 0),
            'name'=>(string)($d['name'] ?? ''),
            'host'=>(string)($d['host'] ?? ''),
            'clients'=>(int)($p['metrics']['clients'] ?? 0),
            'signal'=>$p['metrics']['signal'] ?? 0,
            'ccq'=>$p['metrics']['ccq'] ?? 0,
            'status'=>!empty($p['up']) ? 'UP' : 'DOWN',
        ];
    } else {
        $devices[] = [
            'id'=>(int)($d['id'] ?? 0),
            'name'=>(string)($d['name'] ?? ''),
            'host'=>(string)($d['host'] ?? ''),
            'clients'=>0,'signal'=>0,'ccq'=>0,'status'=>'WARN'
        ];
    }
}
echo json_encode(['ok'=>true,'devices'=>$devices], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
