<?php
/**
 * api/tmdb.php — GET /api/tmdb?path=<ruta_tmdb>&<otros_params>
 *
 * Proxy server-side a la API de TMDB. Inyecta la api_key desde settings
 * (tmdb_api_key) para que la clave NUNCA salga al cliente. La app pasa solo
 * la ruta relativa (p. ej. "movie/popular") y los parámetros extra.
 *
 * Ejemplo:  /api/tmdb?path=movie/550&language=es-ES
 *   -> https://api.themoviedb.org/3/movie/550?api_key=<KEY>&language=es-ES
 */

declare(strict_types=1);

require_once __DIR__ . '/../lib/helpers.php';
require_once __DIR__ . '/../lib/settings.php';

const TMDB_BASE = 'https://api.themoviedb.org/3/';

// Solo GET (proxy de lectura).
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET') {
    json_out(['error' => 'method_not_allowed'], 405);
}

// Ruta relativa de TMDB. Validar para evitar SSRF / path traversal.
$path = trim((string) ($_GET['path'] ?? ''));
$path = ltrim($path, '/');
if ($path === '' || !preg_match('#^[A-Za-z0-9/_\-.,]+$#', $path) || str_contains($path, '..')) {
    json_out(['error' => 'invalid_path'], 400);
}

$apiKey = settings_get('tmdb_api_key', '');
if ($apiKey === '') {
    json_out(['error' => 'tmdb_not_configured'], 503);
}

// Pasar parámetros extra (todos salvo "path"), forzando nuestra api_key.
$extra = $_GET;
unset($extra['path'], $extra['api_key']);
$query = array_merge(['api_key' => $apiKey], $extra);

$url = TMDB_BASE . $path . '?' . http_build_query($query);

$result = tmdb_fetch($url);
if ($result === null) {
    json_out(['error' => 'tmdb_unreachable'], 502);
}

[$status, $payload] = $result;

// Reenviar el JSON de TMDB tal cual, con su código de estado.
http_response_code($status >= 200 && $status < 600 ? $status : 502);
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
echo $payload;
exit;

/**
 * Descarga la URL (curl si está disponible; si no, file_get_contents).
 * Devuelve [statusCode, cuerpo] o null si no se pudo contactar.
 *
 * @return array{0:int,1:string}|null
 */
function tmdb_fetch(string $url): ?array
{
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 10,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_HTTPHEADER     => ['Accept: application/json'],
        ]);
        $body = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_error($ch);
        curl_close($ch);
        if ($body === false || $body === '' || $status === 0) {
            error_log('[api/tmdb] curl error: ' . $err);
            return null;
        }
        return [$status, (string) $body];
    }

    // Fallback sin curl.
    $ctx = stream_context_create([
        'http' => [
            'method'        => 'GET',
            'timeout'       => 10,
            'ignore_errors' => true,
            'header'        => "Accept: application/json\r\n",
        ],
    ]);
    $body = @file_get_contents($url, false, $ctx);
    if ($body === false) {
        error_log('[api/tmdb] file_get_contents falló para TMDB.');
        return null;
    }
    $status = 200;
    if (isset($http_response_header[0]) && preg_match('#\s(\d{3})\s#', $http_response_header[0], $m)) {
        $status = (int) $m[1];
    }
    return [$status, (string) $body];
}
