<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/output_devices_lib.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');

$conn = $GLOBALS['conn'] ?? ensure_db(true);
if (!($conn instanceof mysqli)) {
    http_response_code(500);
    echo json_encode(['ok'=>false, 'error'=>'database_unavailable']);
    exit;
}

$actor = ua_output_authorized_scope($conn, (string)($_GET['scope_key'] ?? ''));
if (empty($actor['authorized'])) {
    http_response_code(401);
    echo json_encode(['ok'=>false, 'error'=>'AUTH_REQUIRED']);
    exit;
}

$commandKey = trim((string)($_GET['command_key'] ?? ''));
$route = ua_output_route($conn, $commandKey, (string)$actor['scope']);
if (!$route || (string)($route['type'] ?? '') !== 'printer') {
    http_response_code(404);
    echo json_encode(['ok'=>false, 'error'=>'unknown_print_command']);
    exit;
}

echo json_encode([
    'ok'=>true,
    'route'=>[
        'commandKey'=>$commandKey,
        'deviceName'=>(string)$route['device_name'],
        'agentHost'=>(string)$route['agent_host'],
        'agentToken'=>(string)$route['agent_token'],
        'paperSize'=>(string)$route['paper_size'],
        'copies'=>max(1, (int)$route['copies']),
        'enabled'=>(bool)$route['is_enabled'],
        'scopeKey'=>(string)$actor['scope'],
    ],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
