<?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_settings','can_mikrotik_sync','can_edit_subscriber']);
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__ . '/../receiver_match_refresh_lib.php';
header('Content-Type: application/json; charset=utf-8');
@ini_set('display_errors','0');
@set_time_limit(300);
try {
    $conn = $GLOBALS['conn'] ?? null;
    if (!($conn instanceof mysqli)) throw new RuntimeException('DB connection unavailable');
    $mode = strtolower((string)($_GET['mode'] ?? $_POST['mode'] ?? 'full'));
    if ($mode === 'cache') {
        $snap = ua_receiver_match_rebuild_from_cache($conn, 'manual_cache_rebuild');
        echo json_encode(['ok'=>!empty($snap['ok']),'mode'=>'cache','snapshot'=>$snap], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        exit;
    }
    $out = ua_receiver_match_scan_all($conn, 'manual_full_refresh', true);
    echo json_encode($out, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok'=>false,'message'=>$e->getMessage()], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}
