<?php
header('Content-Type: text/plain');

$url = 'https://api.casinoscores.com/svc-evolution-game-events/api/immersiveroulette?limit=1';

// Fetch raw response
$response = file_get_contents($url);

// Sanitize invalid surrogate Unicode before decoding
function strip_invalid_unicode_surrogates($json) {
    // Remove lone high-surrogate \uD800–\uDBFF not followed by low-surrogate
    $json = preg_replace('/\\\\uD[89AB][0-9A-F]{2}(?!\\\\uD[CDEF][0-9A-F]{2})/i', '', $json);
    // Remove lone low-surrogate \uDC00–\uDFFF not preceded by high-surrogate
    $json = preg_replace('/(?<!\\\\uD[89AB][0-9A-F]{2})\\\\uD[CDEF][0-9A-F]{2}/i', '', $json);
    return $json;
}

// Apply cleanup
$response = strip_invalid_unicode_surrogates($response);
$response = mb_convert_encoding($response, 'UTF-8', 'UTF-8');

// Decode safely
$data = json_decode($response, true);

// Check for expected structure
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");

    echo json_encode([
        [
            "data" => [
                "settledAt" => $settledAt,
                "result" => [
                    "outcome" => [
                        "number" => $number
                    ]
                ]
            ]
        ]
    ]);
    exit;
}

// Fallback if no data available
echo json_encode([]);
