<?php
/**
 * Public poster proxy for Telegram Inline results.
 * URL: /bot/poster.php?id=GAME_ID&v=CACHE_BUSTER
 * The bot token is never exposed to the browser/Telegram client.
 */
require_once __DIR__ . '/config.php';

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0 || !defined('BOT_TOKEN')) {
    http_response_code(404);
    exit;
}

$gamesFile = __DIR__ . '/data/games.json';
if (!is_file($gamesFile)) {
    http_response_code(404);
    exit;
}

$games = json_decode((string)file_get_contents($gamesFile), true);
$poster = '';
if (is_array($games)) {
    foreach ($games as $game) {
        if ((int)($game['id'] ?? 0) === $id) {
            $poster = trim((string)($game['poster'] ?? ''));
            break;
        }
    }
}
if ($poster === '') {
    http_response_code(404);
    exit;
}

$ch = curl_init('https://api.telegram.org/bot' . BOT_TOKEN . '/getFile');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => ['file_id' => $poster],
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT => 12,
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response ?: '', true);
$filePath = $data['result']['file_path'] ?? '';
if (empty($data['ok']) || $filePath === '') {
    http_response_code(404);
    exit;
}

$fileUrl = 'https://api.telegram.org/file/bot' . BOT_TOKEN . '/' . ltrim($filePath, '/');
$ch = curl_init($fileUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT => 15,
]);
$body = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode < 200 || $httpCode >= 300 || $body === false || $body === '') {
    http_response_code(404);
    exit;
}

if (!$contentType || strpos($contentType, 'image/') !== 0) {
    $contentType = 'image/jpeg';
}
header('Content-Type: ' . $contentType);
header('Cache-Control: public, max-age=86400, immutable');
header('X-Content-Type-Options: nosniff');
header('Content-Length: ' . strlen($body));
echo $body;
