<?php
require_once __DIR__ . '/../auth.php';
if (function_exists('require_login')) require_login('login.php');
if (function_exists('require_any_perm')) require_any_perm(['can_view_dashboard_sectors','can_view_dashboard_summary']);
if (session_status() === PHP_SESSION_ACTIVE) { @session_write_close(); }
require_once __DIR__ . '/../db_bootstrap.php';
if (function_exists('ensure_db')) ensure_db(true);
require_once __DIR__ . '/../airmax_monitor_lib.php';
require_once __DIR__ . '/../receiver_subscriber_match_lib.php';
require_once __DIR__ . '/../device_subscriber_confirmation_lib.php';
require_once __DIR__ . '/noc_card_cache.php';

header('Content-Type: application/json; charset=utf-8');
@ini_set('display_errors','0');
while (ob_get_level()>0) { @ob_end_clean(); }
ob_start();

try {
    $conn = $GLOBALS['conn'] ?? null;
    if (!($conn instanceof mysqli)) noc_json_response(['ok'=>false,'items'=>[]],500);

    $cacheKey = 'noc_sectors_card';
    $cachePath = noc_cache_file($cacheKey);
    $cache = noc_load_json_file($cachePath, ['ok'=>true,'items'=>[],'last_update'=>0,'next_idx'=>0,'summary'=>['total'=>0,'down'=>0,'total_stations'=>0]]);

    $devices = array_values(array_filter(airmax_get_all($conn, true), static fn($d) => !(function_exists('airmax_device_is_station') ? airmax_device_is_station($d) : in_array(($d['device_type'] ?? ''), ['station','powerbeam'], true))));
    foreach ($devices as $d) {
        $id = (int)($d['id'] ?? 0);
        if (!isset($cache['items'][$id])) {
            $cache['items'][$id] = [
                'id'=>$id,'name'=>(string)($d['name'] ?? '—'),'host'=>(string)($d['host'] ?? ''),
                'model'=>'—','cpu'=>null,'memory'=>null,'quality'=>null,'capacity'=>null,
                'clients'=>0,'stations'=>0,'state'=>'WARN','uptime'=>''
            ];
        }
    }

    $now = time();
    if ($devices && ((int)($cache['last_update'] ?? 0) < $now - 60)) {
        $lock = noc_try_lock($cacheKey);
        if ($lock) {
            $idx = (int)($cache['next_idx'] ?? 0);
            $d = $devices[$idx % count($devices)];
            $rid = (int)($d['id'] ?? 0);
            $cached = airmax_json_read(airmax_result_cache_path($d), null);
            $age = is_array($cached) ? ($now - (int)($cached['ts'] ?? 0)) : 999999;
            if ($age > 180) {
                airmax_probe_and_persist($conn, $rid);
                $cached = airmax_json_read(airmax_result_cache_path($d), null);
            }
            $old = $cache['items'][$rid] ?? [];
            if (is_array($cached) && isset($cached['out']['probe'])) {
                $p = $cached['out']['probe'];
                $metrics = is_array($p['metrics'] ?? null) ? $p['metrics'] : [];
                $cache['items'][$rid] = [
                    'id'=>$rid,
                    'host'=>(string)($d['host'] ?? ''),
                    'name'=>(string)($d['name'] ?? '—'),
                    'model'=>(string)(($metrics['model'] ?? ($old['model'] ?? '—')) ?: '—'),
                    'cpu'=>isset($metrics['cpu']) && $metrics['cpu'] !== '' ? (float)$metrics['cpu'] : ($old['cpu'] ?? null),
                    'memory'=>isset($metrics['memory']) && $metrics['memory'] !== '' ? (float)$metrics['memory'] : ($old['memory'] ?? null),
                    'quality'=>isset($metrics['quality']) && $metrics['quality'] !== '' ? (float)$metrics['quality'] : ($old['quality'] ?? null),
                    'capacity'=>isset($metrics['capacity']) && $metrics['capacity'] !== '' ? (float)$metrics['capacity'] : ($old['capacity'] ?? null),
                    'clients'=>0,
                    'stations'=>0,
                    'uptime'=>(string)(($metrics['uptime'] ?? ($old['uptime'] ?? '')) ?: ''),
                    'state'=>(string)($p['state'] ?? 'DOWN'),
                ];
            }

            $cache['next_idx'] = $idx + 1;
            $cache['last_update'] = $now;

            $list = [];
            foreach ($devices as $dd) {
                $iid = (int)($dd['id'] ?? 0);
                $list[] = $cache['items'][$iid] ?? [
                    'id'=>$iid,'name'=>(string)($dd['name'] ?? '—'),'host'=>(string)($dd['host'] ?? ''),
                    'model'=>'—','cpu'=>null,'memory'=>null,'quality'=>null,'capacity'=>null,
                    'clients'=>0,'stations'=>0,'state'=>'WARN','uptime'=>''
                ];
            }
            $down = 0; $stationSum = 0;
            foreach ($list as $it) {
                if (in_array(strtoupper((string)($it['state'] ?? '')), ['OFFLINE','DOWN'], true)) $down++;
                // Access/Sector cards are not used for subscriber counts.
                $stationSum += 0;
            }
            $cache['summary'] = ['total'=>count($list),'down'=>$down,'total_stations'=>$stationSum];
            noc_save_json_file($cachePath, $cache);
            noc_unlock($lock);
        }
    }

    $list = [];
    foreach ($devices as $d) {
        $id = (int)($d['id'] ?? 0);
        $oldItem = is_array($cache['items'][$id] ?? null) ? $cache['items'][$id] : [];
        $item = function_exists('airmax_dashboard_item_from_cache')
            ? airmax_dashboard_item_from_cache($d, $oldItem)
            : ($oldItem ?: [
                'id'=>$id,'name'=>(string)($d['name'] ?? '—'),'host'=>(string)($d['host'] ?? ''),
                'model'=>'—','cpu'=>null,'memory'=>null,'quality'=>null,'capacity'=>null,
                'clients'=>0,'stations'=>0,'state'=>'WARN','uptime'=>''
            ]);
        $item['clients'] = (int)($item['clients'] ?? 0);
        $item['stations'] = 0;
        $list[] = $item;
    }

    $rxSnapshot = function_exists('ua_receiver_match_snapshot') ? ua_receiver_match_snapshot($conn, 60, true) : [];
    $rxByDevice = function_exists('ua_receiver_match_by_device') ? ua_receiver_match_by_device($rxSnapshot) : [];
    $down = 0; $stationSum = 0; $downChecks=[];
    foreach ($list as &$it) {
        $iid = (int)($it['id'] ?? 0);
        if (isset($rxByDevice[$iid])) {
            $m = $rxByDevice[$iid];
            $matched = (int)($m['matched_count'] ?? 0);
            $it['raw_macs'] = (int)($m['raw_mac_count'] ?? ($it['stations'] ?? $it['clients'] ?? 0));
            $it['raw_clients'] = (int)($it['clients'] ?? 0);
            $it['matched_clients'] = $matched;
            $it['unknown_macs'] = (int)($m['unknown_count'] ?? 0);
            $it['ambiguous_macs'] = (int)($m['ambiguous_count'] ?? 0);
            $it['clients'] = $matched;
            $it['stations'] = $matched;
            $it['count_source'] = 'receiver_mac_match';
        }
        if (in_array(strtoupper((string)($it['state'] ?? '')), ['OFFLINE','DOWN'], true)) {$down++;$downChecks[]=['group'=>'sectors','id'=>(int)($it['id']??0)];}
        // Access/Sector cards are not used for subscriber counts.
                $stationSum += 0;
    }
    unset($it);
    $confirmed=ua_device_subscriber_confirm_batch($conn,$downChecks);$alertDown=0;
    foreach($list as &$it){$key='sectors:id:'.(int)($it['id']??0);if(isset($confirmed['items'][$key])){$it['subscriber_confirmation']=$confirmed['items'][$key];if(!empty($confirmed['items'][$key]['allow_alert']))$alertDown++;}}
    unset($it);
    $summary = [
        'total'=>count($list),
        'down'=>$down,
        'alert_down'=>$alertDown,
        'total_stations'=>$stationSum,
        'unknown_total'=>(int)($rxSnapshot['summary']['unknown_total'] ?? 0),
        'ambiguous_total'=>(int)($rxSnapshot['summary']['ambiguous_total'] ?? 0),
        'count_source'=>'receiver_mac_match',
        'count_label'=>'مطابقة MAC المستقبلات مع مشتركي MikroTik'
    ];
    noc_json_response(['ok'=>true,'items'=>$list,'summary'=>$summary,'last_update'=>$cache['last_update'] ?? 0],200);
} catch (Throwable $e) {
    noc_json_response(['ok'=>true,'items'=>[],'summary'=>['total'=>0,'down'=>0,'total_stations'=>0],'error'=>'fallback'],200);
}
