<?php
// tmdb_proxy.php
require_once __DIR__ . '/auth.php';
require_login(); // garante que apenas usuários logados usem

header('Content-Type: application/json; charset=utf-8');

$action = $_GET['action'] ?? '';
$type = $_GET['type'] ?? 'movie'; // 'movie' ou 'tv'

if (!defined('TMDB_API_KEY') || !TMDB_API_KEY) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'TMDB API key não configurada']);
    exit;
}

function tmdb_get($url, $query = []) {
    $query['api_key'] = TMDB_API_KEY;
    $q = http_build_query($query);
    $full = rtrim($url, '?') . '?' . $q;
    $ch = curl_init($full);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_USERAGENT, 'LOB-TMDB-Proxy/1.0');
    $r = curl_exec($ch);
    $err = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($r === false) return ['error' => $err, 'code' => 500];
    return ['body' => $r, 'code' => $code];
}

if ($action === 'search') {
    $q = trim($_GET['q'] ?? '');
    if ($q === '') {
        echo json_encode(['success'=>false,'message'=>'Query vazia']);
        exit;
    }
    // Decide endpoint
    if ($type === 'tv') {
        $url = 'https://api.themoviedb.org/3/search/tv';
    } else {
        $url = 'https://api.themoviedb.org/3/search/movie';
    }
    $res = tmdb_get($url, ['query'=>$q, 'language'=>'pt-BR', 'page'=>1, 'include_adult'=>false]);
    if (isset($res['error'])) {
        http_response_code(500);
        echo json_encode(['success'=>false,'message'=>$res['error']]);
        exit;
    }
    header('Content-Type: application/json; charset=utf-8');
    echo $res['body'];
    exit;
}

if ($action === 'details') {
    $id = intval($_GET['id'] ?? 0);
    if ($id <= 0) {
        echo json_encode(['success'=>false,'message'=>'ID inválido']);
        exit;
    }
    if ($type === 'tv') {
        $url = "https://api.themoviedb.org/3/tv/{$id}";
    } else {
        $url = "https://api.themoviedb.org/3/movie/{$id}";
    }
    $res = tmdb_get($url, ['language'=>'pt-BR']);
    if (isset($res['error'])) {
        http_response_code(500);
        echo json_encode(['success'=>false,'message'=>$res['error']]);
        exit;
    }
    echo $res['body'];
    exit;
}

// Proxy de imagem (poster) para evitar problemas de CORS/taint do canvas
if ($action === 'poster') {
    $path = $_GET['path'] ?? '';
    if ($path === '') {
        http_response_code(400);
        echo json_encode(['success'=>false,'message'=>'Path vazio']);
        exit;
    }

    // Segurança: só permitir paths iniciando com '/'
    if ($path[0] !== '/') {
        http_response_code(400);
        echo json_encode(['success'=>false,'message'=>'Path inválido']);
        exit;
    }

    // Qual tamanho usar? podemos usar original ou w780
    $size = $_GET['size'] ?? 'w780'; // ou 'original'
    $url = TMDB_IMAGE_BASE . '/' . $size . $path;

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_USERAGENT, 'LOB-TMDB-ImageProxy/1.0');
    $img = curl_exec($ch);
    $err = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $ctype = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    curl_close($ch);

    if ($img === false || $code >= 400) {
        http_response_code(502);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['success'=>false,'message'=>'Erro ao buscar poster: '.$err]);
        exit;
    }

    header('Content-Type: ' . ($ctype ?: 'image/jpeg'));
    header('Cache-Control: max-age=86400, public');
    echo $img;
    exit;
}

http_response_code(400);
echo json_encode(['success'=>false,'message'=>'Ação inválida']);
exit;