<?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__ . '/auth.php';
require_once __DIR__ . '/output_devices_lib.php';
require_once __DIR__ . '/output_fleet_lib.php';

header('Content-Type: application/json; charset=utf-8');
$conn = $GLOBALS['conn'] ?? ensure_db(true);
if (!($conn instanceof mysqli)) {
    http_response_code(500);
    echo json_encode(['ok'=>false,'error'=>'database_unavailable'], JSON_UNESCAPED_UNICODE);
    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'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (isset($_GET['health'])) {
    $routes = ua_output_load_routes($conn, (string)$actor['scope']);
    $host = '127.0.0.1';
    $token = '';
    foreach ($routes as $route) {
        if (trim((string)($route['agent_host'] ?? '')) !== '') {
            $host = (string)$route['agent_host'];
            $token = (string)($route['agent_token'] ?? '');
            break;
        }
    }
    $result = ua_output_agent_request($host, $token, 'health');
    if (!$result['ok']) http_response_code(503);
    echo $result['body'] !== '' ? $result['body'] : json_encode(['ok'=>false,'error'=>$result['error']], JSON_UNESCAPED_UNICODE);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || (function_exists('ua_csrf_verify') && !ua_csrf_verify())) {
    http_response_code(403);
    echo json_encode(['ok'=>false,'error'=>'invalid_request'], JSON_UNESCAPED_UNICODE);
    exit;
}
$input = json_decode((string)file_get_contents('php://input'), true);
if (!is_array($input)) $input = [];
$actor = ua_output_authorized_scope($conn, (string)($input['scope_key'] ?? ''));
if (empty($actor['authorized'])) {
    http_response_code(401);
    echo json_encode(['ok'=>false,'error'=>'AUTH_REQUIRED'], JSON_UNESCAPED_UNICODE);
    exit;
}
$scopeKey = (string)$actor['scope'];
$action = strtolower(trim((string)($input['action'] ?? 'print')));
if ($action === 'discover') {
    $host = trim((string)($input['agent_host'] ?? '127.0.0.1'));
    $token = trim((string)($input['agent_token'] ?? ''));
    $kind = strtolower(trim((string)($input['device_type'] ?? 'printer'))) === 'scanner' ? 'scanners' : 'printers';
    $result = ua_output_agent_request($host, $token, $kind);
    if (!$result['ok']) {
        http_response_code($result['status'] === 401 ? 401 : 502);
        echo json_encode(['ok'=>false,'error'=>$result['status'] === 401 ? 'invalid_output_agent_token' : ($result['error'] ?: 'output_agent_unreachable')], JSON_UNESCAPED_UNICODE);
        exit;
    }
    echo json_encode(['ok'=>true,'devices'=>array_values((array)$result['data'])], JSON_UNESCAPED_UNICODE);
    exit;
}
$commandKey = trim((string)($input['command_key'] ?? ''));
$html = (string)($input['html'] ?? '');
if ($html === '' || strlen($html) > 12 * 1024 * 1024) {
    http_response_code(413);
    echo json_encode(['ok'=>false,'error'=>'invalid_print_document'], JSON_UNESCAPED_UNICODE);
    exit;
}

// Fleet routing is authoritative when configured by the main installation.
$fleet = ua_output_fleet_dispatch($conn, $commandKey, $scopeKey, $input);
if (!empty($fleet['ok'])) {
    ua_output_log_job($conn, $commandKey, 'sent', 'تم الإرسال عبر شبكة الطابعات إلى ' . (string)($fleet['printer'] ?? ''), (string)($input['reference_id'] ?? ''), $scopeKey);
    echo $fleet['body'] !== '' ? $fleet['body'] : json_encode(['ok'=>true,'printer'=>$fleet['printer']??''], JSON_UNESCAPED_UNICODE);
    exit;
}
if (ua_install_link_approved()) {
    $central = ua_output_fleet_central_request($input + ['command_key'=>$commandKey]);
    if (!empty($central['ok'])) {
        ua_output_log_job($conn, $commandKey, 'sent', 'تم الإرسال عبر مركز الطباعة الرئيسي', (string)($input['reference_id'] ?? ''), $scopeKey);
        echo $central['body']; exit;
    }
}
$route = ua_output_route($conn, $commandKey, $scopeKey);
if (!$route || ($route['type'] ?? '') !== 'printer' || empty($route['is_enabled']) || trim((string)$route['device_name']) === '') {
    http_response_code(422);
    echo json_encode(['ok'=>false,'error'=>'printer_route_unavailable'], JSON_UNESCAPED_UNICODE);
    exit;
}
$agentPayload = json_encode([
    'printer'=>(string)$route['device_name'],
    'copies'=>max(1, (int)$route['copies']),
    'paper'=>(string)$route['paper_size'],
    'title'=>mb_substr((string)($input['title'] ?? $route['label']), 0, 180),
    'command_key'=>$commandKey,
    'source_url'=>(string)($input['source_url'] ?? ''),
    'html'=>$html,
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
$result = ua_output_agent_request((string)$route['agent_host'], (string)$route['agent_token'], 'print', 'POST', $agentPayload, 30);
if (!$result['ok']) {
    ua_output_log_job($conn, $commandKey, 'failed', $result['error'] ?: ('HTTP ' . $result['status']), (string)($input['reference_id'] ?? ''), $scopeKey);
    http_response_code(502);
}
echo $result['body'] !== '' ? $result['body'] : json_encode(['ok'=>$result['ok'],'error'=>$result['error']], JSON_UNESCAPED_UNICODE);
