<?php
header('Content-Type: application/json');

$url = 'https://api.casinoscores.com/svc-evolution-game-events/api/autoroulette?limit=1'; // fetch 1 latest spin
$response = file_get_contents($url);

// Remove problematic lone UTF-16 surrogate escapes
$response_clean = preg_replace('/\\\\u(d8|d9|da|db|dc|dd|de|df)[0-9a-f]{2}/i', '', $response);

$data = json_decode($response_clean, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    // Return empty array on JSON error
    echo json_encode([]);
    exit;
}

if ($data && isset($data[0]['data']['result']['outcome']['number'])) {
    $number = $data[0]['data']['result']['outcome']['number'];
    $settledAt = $data[0]['data']['settledAt'] ?? gmdate("Y-m-d\TH:i:s\Z"); // fallback

    // Output wrapped as expected by JS
    echo json_encode([
        [
            "data" => [
                "settledAt" => $settledAt,
                "result" => [
                    "outcome" => [
                        "number" => $number
                    ]
                ]
            ]
        ]
    ]);
    exit;
}

// Return empty array if data not available
echo json_encode([]);
