<?php
session_start();
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    header("Location: login.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Buscar Filme/Série</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body, html {
            height: 100%;
            font-family: Arial, sans-serif;
            background-color: #0f1f0f;
            color: #cceccc;
        }

        .form-container {
            max-width: 500px;
            margin: 30px auto 20px auto;
            padding: 30px;
            background-color: #142a14;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 0 20px #1f4d1f;
        }

        h1 {
            color: #80ff80;
            text-shadow: 0 0 5px #339933;
            margin-bottom: 20px;
        }

        input[type="text"], select {
            padding: 12px;
            width: 100%;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            margin-bottom: 20px;
            background: #1a3d1a;
            color: #cceccc;
        }

        button {
            padding: 12px 20px;
            font-size: 16px;
            background: #33cc33;
            color: #000;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            width: 100%;
            box-shadow: 0 0 10px #33cc33;
            transition: all 0.3s ease;
        }

        button:hover {
            background: #28a428;
            box-shadow: 0 0 15px #33cc33;
        }

        .results-container {
            margin: 30px auto;
            max-width: 400px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .card {
            background-color: #1e3b1e;
            border-radius: 10px;
            padding: 10px;
            margin-bottom: 20px;
            text-align: center;
            width: 100%;
            box-shadow: 0 0 10px #295429;
        }

        .card img {
            width: 100%;
            border-radius: 8px;
        }

        .card p {
            margin-top: 10px;
            font-size: 16px;
            color: #aaffaa;
        }

        .card form {
            margin-top: 10px;
        }

        .card form select {
            padding: 8px;
            font-size: 14px;
            border: none;
            border-radius: 5px;
            margin-top: 10px;
            background: #1a3d1a;
            color: #cceccc;
        }

        .card form button {
            width: auto;
            background-color: #2ecc71;
            color: #fff;
        }

        .card form button:hover {
            background-color: #27ae60;
        }
    </style>
</head>
<body>

<div class="form-container">
    <h1>Buscar Filme ou Série</h1>
    <form method="GET">
        <input type="text" name="query" placeholder="Digite o nome do título" value="<?= isset($_GET['query']) ? htmlspecialchars($_GET['query']) : '' ?>" required>
        <button type="submit">🔍 Buscar</button>
    </form>
</div>

<?php
if (isset($_GET['query'])) {
    $apiKey = '855ee921df930db2f2a9669eda268032';
    $language = 'pt-BR';
    $query = urlencode($_GET['query']);
    $url = "https://api.themoviedb.org/3/search/multi?api_key=$apiKey&language=$language&query=$query";

    // Usar cURL para a chamada à API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($response === false || !empty($curlError)) {
        error_log("Erro cURL ao acessar a API ($url): $curlError");
        echo "<p style='text-align:center; color: #ffdddd;'>Erro ao acessar a API: $curlError</p>";
        exit;
    }

    if ($httpCode !== 200) {
        $errorData = json_decode($response, true);
        $errorMessage = $errorData['status_message'] ?? 'Erro desconhecido (código HTTP: ' . $httpCode . ')';
        error_log("Erro na API ($url): $errorMessage");
        echo "<p style='text-align:center; color: #ffdddd;'>Erro na API: $errorMessage</p>";
        exit;
    }

    $data = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("Erro ao decodificar JSON da API ($url): " . json_last_error_msg());
        echo "<p style='text-align:center; color: #ffdddd;'>Erro ao processar a resposta da API: " . json_last_error_msg() . "</p>";
        exit;
    }

    if (!empty($data['results'])) {
        // Ordenar os resultados pelos mais recentes (com base na data de lançamento ou primeira exibição)
        usort($data['results'], function($a, $b) {
            $dateA = $a['release_date'] ?? $a['first_air_date'] ?? '';
            $dateB = $b['release_date'] ?? $b['first_air_date'] ?? '';
            return strtotime($dateB) - strtotime($dateA);
        });

        echo "<div class='results-container'>";

        foreach ($data['results'] as $item) {
            if (!empty($item['poster_path'])) {
                $posterUrl = "https://image.tmdb.org/t/p/w342" . $item['poster_path'];
                $titulo = htmlspecialchars($item['title'] ?? $item['name'] ?? 'Título Desconhecido');
                $id = intval($item['id']);
                $mediaType = $item['media_type'];
                $tipo = 'filme';
                if ($mediaType === 'tv') {
                    $nome = strtolower($item['name']);
                    if (strpos($nome, 'naruto') !== false || strpos($nome, 'bleach') !== false || strpos($nome, 'one piece') !== false || strpos($nome, 'attack on titan') !== false) {
                        $tipo = 'anime';
                    } elseif (strpos($nome, 'novela') !== false || strpos($nome, 'amor') !== false || strpos($nome, 'família') !== false) {
                        $tipo = 'novela';
                    } else {
                        $tipo = 'serie';
                    }
                } elseif ($mediaType === 'movie') {
                    $tipo = 'filme';
                }

                echo "<div class='card'>
                        <img src='$posterUrl' alt='$titulo'>
                        <p>$titulo</p>
                        <form action='gerar_banner.php' method='GET'>
                            <input type='hidden' name='id' value='$id'>
                            <input type='hidden' name='tipo' value='$tipo'>
                            <select name='layout'>
                                <option value='vertical'>Vertical</option>
                                <option value='horizontal'>Horizontal</option>
                            </select>
                            <br>
                            <button type='submit'>✅ Usar esta capa</button>
                        </form>
                      </div>";
            }
        }

        echo "</div>";
    } else {
        echo "<p style='text-align:center;'>Nenhum resultado encontrado.</p>";
    }
}
?>

</body>
</html>