<?php
declare(strict_types=1);

require_once __DIR__ . '/slot_games_lib.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: public, max-age=300');
header('X-Content-Type-Options: nosniff');

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'GET') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

function mocker_slot_json_out(array $payload, int $code = 200): void
{
    http_response_code($code);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

$providerRaw = strtolower(trim((string) ($_GET['provider'] ?? '')));
$provider = preg_replace('/[^a-z0-9_-]/', '', $providerRaw);

$providersOut = mocker_slot_list_providers();

if ($provider === '') {
    $provider = $providersOut[0]['id'] ?? 'pragmaticplay';
}

if (!mocker_slot_provider_is_allowed($provider)) {
    mocker_slot_json_out([
        'ok' => false,
        'error' => 'provider',
        'providers' => $providersOut,
    ], 400);
}

$providerLabel = mocker_slot_provider_label($provider);

$url = MOCKER_SLOT_API_ROULETTE . '?provider=' . rawurlencode($provider);
$raw = mocker_slot_http_get($url);
$games = mocker_slot_resolve_games($provider, $raw);

if ($games === []) {
    $payload = [
        'ok' => false,
        'error' => $raw === null ? 'fetch' : 'empty',
        'provider' => $provider,
        'providers' => $providersOut,
    ];
    if (isset($_GET['debug']) && (string) $_GET['debug'] !== '0') {
        $rawPath = mocker_slot_games_cache_path($provider) . '.raw.txt';
        $payload['debug'] = [
            'hadRaw' => $raw !== null,
            'rawLength' => $raw !== null ? strlen($raw) : 0,
            'rawSaved' => is_readable($rawPath),
            'rawPreview' => $raw !== null ? substr($raw, 0, 400) : null,
        ];
    }
    mocker_slot_json_out($payload, 200);
}

$fromApi = $raw !== null && is_array(json_decode($raw, true));
$cached = !$fromApi && mocker_slot_read_games_cache($provider) !== [];

mocker_slot_json_out([
    'ok' => true,
    'provider' => $provider,
    'providerLabel' => $providerLabel,
    'games' => $games,
    'providers' => $providersOut,
    'fromApi' => $fromApi,
    'cached' => $cached,
    'fallback' => !$fromApi && !$cached,
]);
