<?php
require_once __DIR__ . '/../auth.php';
if (function_exists('require_login')) require_login('../login.php');
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../receiver_subscriber_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)) {
    echo json_encode(['ok'=>false,'message'=>'db not ready'], JSON_UNESCAPED_UNICODE); exit;
}

// Applies the current receiver/subscriber matching from existing caches only.
// It does not poll MikroTik or any receiver; it reads the already collected receiver MAC caches.
$force = !empty($_GET['force']) || !empty($_POST['force']);
$ttl = $force ? 0 : max(30, min(900, (int)($_GET['ttl'] ?? $_POST['ttl'] ?? 120)));
$snap = function_exists('ua_receiver_match_snapshot') ? ua_receiver_match_snapshot($conn, $ttl, true) : ['ok'=>false,'message'=>'receiver matcher unavailable'];

$summary = (array)($snap['summary'] ?? []);
echo json_encode([
    'ok' => !empty($snap['ok']),
    'message' => !empty($snap['ok']) ? 'تم تطبيق المطابقة من الكاش الحالي بدون أوامر إضافية.' : (string)($snap['message'] ?? 'تعذر تطبيق المطابقة'),
    'ts' => (int)($snap['ts'] ?? time()),
    'age' => (int)($snap['age'] ?? 0),
    'summary' => $summary,
    'stale_cleanup' => (array)($snap['stale_cleanup'] ?? []),
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
