<?php
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';

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;
}
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;
}
$key = (string)($input['command_key'] ?? '');
$registry = ua_output_command_registry();
if (!isset($registry[$key])) {
    http_response_code(422);
    echo json_encode(['ok'=>false,'error'=>'unknown_command'], JSON_UNESCAPED_UNICODE);
    exit;
}
$allowedStatuses = ['created','sent','dialog','fallback','failed','completed'];
$status = (string)($input['status'] ?? 'created');
if (!in_array($status, $allowedStatuses, true)) $status = 'created';
$message = mb_substr(trim((string)($input['message'] ?? '')), 0, 500);
$reference = mb_substr(trim((string)($input['reference_id'] ?? '')), 0, 120);
ua_output_log_job($conn, $key, $status, $message, $reference, (string)$actor['scope']);
echo json_encode(['ok'=>true], JSON_UNESCAPED_UNICODE);
