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

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

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

// Sanitize invalid surrogate Unicode
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;
}

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

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

$result = [];

if (is_array($data)) {
    foreach ($data as $item) {
        if (isset($item['data']['result']['outcome']['number'])) {
            $result[] = [
                "data" => [
                    "settledAt" => $item['data']['settledAt'] ?? gmdate("Y-m-d\TH:i:s\Z"),
                    "result" => [
                        "outcome" => [
                            "number" => $item['data']['result']['outcome']['number']
                        ]
                    ]
                ]
            ];
        }
    }
}

// Output clean JSON
echo json_encode($result);
