<?php
require_once __DIR__ . '/../auth.php';
if (function_exists('require_login')) require_login('../login.php');
if (function_exists('require_perm')) @require_perm('can_view_subscribers');
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../router_port_match_lib.php';
if (function_exists('ensure_db')) ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
header('Content-Type: application/json; charset=utf-8');
if (!($conn instanceof mysqli)) {
    http_response_code(500);
    echo json_encode(['ok'=>false,'message'=>'DB not ready'], JSON_UNESCAPED_UNICODE);
    exit;
}
$routerId = (int)($_POST['router_id'] ?? $_GET['router_id'] ?? 0);
$iface = trim((string)($_POST['interface'] ?? $_GET['interface'] ?? ''));
if ($routerId <= 0 || $iface === '') {
    http_response_code(400);
    echo json_encode(['ok'=>false,'message'=>'اختر الراوتر والمنفذ أولاً.'], JSON_UNESCAPED_UNICODE);
    exit;
}
try {
    $res = ua_rpm_match_port($conn, $routerId, $iface);
    if (!empty($res['ok']) && !empty($res['persisted']['ok']) && function_exists('ua_receiver_match_snapshot')) {
        $snap = ua_receiver_match_snapshot($conn, 0, true);
        $res['snapshot_rebuilt'] = !empty($snap['ok']);
        $res['snapshot_summary'] = (array)($snap['summary'] ?? []);
        if (function_exists('airmax_invalidate_noc_card_cache')) @airmax_invalidate_noc_card_cache();
    }
    echo json_encode($res, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok'=>false,'message'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
