<?php
declare(strict_types=1);

$sessionId = preg_replace('/[^A-Za-z0-9,-]/', '', (string)($argv[1] ?? 'codexrouteragenttest')) ?: 'codexrouteragenttest';
session_id($sessionId);
session_start();
require_once dirname(__DIR__) . '/db_bootstrap.php';
ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) throw new RuntimeException('Database unavailable.');
$result = $conn->query("SELECT id FROM agents WHERE COALESCE(is_active,1)=1 ORDER BY id LIMIT 1");
$agentId = (int)(($result ? $result->fetch_assoc() : [])['id'] ?? 0);
if ($agentId <= 0) throw new RuntimeException('No active agent is available.');
$_SESSION['agent_portal_' . $agentId] = ['logged'=>1, 'test_fixture'=>1];
$_SESSION['agent_portal_last_agent'] = $agentId;
$renderPrint = in_array('--render-print', $argv, true);
if (in_array('--render', $argv, true) || $renderPrint) {
    $subscriberId = 609;
    $setupId = 0;
    if ($renderPrint) {
        $setupResult = $conn->query('SELECT id,subscriber_id FROM subscriber_router_setups ORDER BY id DESC LIMIT 1');
        $setupRow = $setupResult ? $setupResult->fetch_assoc() : null;
        $setupId = (int)($setupRow['id'] ?? 0);
        $subscriberId = (int)($setupRow['subscriber_id'] ?? 0);
        if ($setupId <= 0 || $subscriberId <= 0) throw new RuntimeException('No router setup is available for print rendering.');
    }
    $_GET = ['agent'=>$agentId, 'subscriber_id'=>$subscriberId] + ($setupId > 0 ? ['setup_id'=>$setupId] : []);
    $_POST = [];
    $_SERVER['REQUEST_METHOD'] = 'GET';
    $_SERVER['SCRIPT_NAME'] = '/mikrotik/admin/subscriber_router_setup.php';
    ob_start();
    require dirname(__DIR__) . '/subscriber_router_setup.php';
    $html = (string)ob_get_clean();
    if (!str_contains($html, 'data-router-form') || !str_contains($html, 'ap-shell')) {
        throw new RuntimeException('Agent router setup did not render in the agent shell.');
    }
    if ($renderPrint && (!str_contains($html, 'data-thermal-sheet') || !preg_match('/ars-paper-(?:80mm|58mm)/', $html) || !str_contains($html, 'ars-print-brand'))) {
        throw new RuntimeException('Thermal QR print sheet did not render.');
    }
    echo json_encode(['ok'=>true, 'agent_id'=>$agentId, 'agent_shell'=>true, 'thermal_print'=>$renderPrint], JSON_UNESCAPED_UNICODE) . PHP_EOL;
} else {
    session_write_close();
    echo $agentId . PHP_EOL;
}
