<?php
require_once __DIR__ . '/../includes/app_config.php';
streambox_no_cache_headers();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

$config = streambox_config_read();
$url = trim((string)($config['games_api_url'] ?? ''));
$cacheFile = __DIR__ . '/cache/games_last.json';
if (!is_dir(dirname($cacheFile))) @mkdir(dirname($cacheFile), 0755, true);

function fetch_games_remote(string $url): ?string {
    if (!filter_var($url, FILTER_VALIDATE_URL) || !preg_match('#^https?://#i', $url)) return null;
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CONNECTTIMEOUT => 6,
            CURLOPT_TIMEOUT => 12,
            CURLOPT_USERAGENT => 'StreamBoxPanel/1.0',
            CURLOPT_HTTPHEADER => ['Accept: application/json'],
        ]);
        $body = curl_exec($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if (is_string($body) && $body !== '' && $code >= 200 && $code < 300) return $body;
    }
    $ctx = stream_context_create(['http' => [
        'method' => 'GET', 'timeout' => 12, 'ignore_errors' => true,
        'header' => "Accept: application/json\r\nUser-Agent: StreamBoxPanel/1.0\r\n"
    ]]);
    $body = @file_get_contents($url, false, $ctx);
    return is_string($body) && $body !== '' ? $body : null;
}

$body = fetch_games_remote($url);
$decoded = is_string($body) ? json_decode($body, true) : null;
if (is_array($decoded)) {
    @file_put_contents($cacheFile, $body, LOCK_EX);
    echo $body;
    exit;
}

if (is_file($cacheFile)) {
    header('X-StreamBox-Games-Source: cache');
    readfile($cacheFile);
    exit;
}

http_response_code(502);
echo json_encode(['jogos' => [], 'error' => 'games_api_unavailable'], JSON_UNESCAPED_UNICODE);
