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

ini_set('display_errors', 1);
error_reporting(E_ALL);

$apiKey = '855ee921df930db2f2a9669eda268032';
$language = 'pt-BR';
$defaultPoster = __DIR__ . '/img/default_poster.jpg';
$font = __DIR__ . '/Montserrat-Bold.ttf';
$logoDir = __DIR__ . '/logo';
$imgDir = __DIR__ . '/img';
$botaoPath = __DIR__ . '/img/botao.png';

// --- Troca de logo ---
if (!is_dir($logoDir)) mkdir($logoDir, 0777, true);
$logoAtual = null;
$logos = glob($logoDir . '/*');
if ($logos && count($logos) > 0) {
    // Sempre pega a logo mais recente
    usort($logos, function($a, $b){ return filemtime($b) - filemtime($a); });
    $logoAtual = $logos[0];
} else {
    // Se não houver logo, use o padrão (você pode colocar uma logo padrão em /logo/logo.png)
    $logoAtual = __DIR__ . '/img/logo.png';
}
$logoRodapeDir = __DIR__ . '/logo_rodape';
if (!is_dir($logoRodapeDir)) mkdir($logoRodapeDir, 0777, true);

$logoRodapeAtual = null;
$logosRodape = glob($logoRodapeDir . '/*');
if ($logosRodape && count($logosRodape) > 0) {
    usort($logosRodape, fn($a, $b) => filemtime($b) - filemtime($a));
    $logoRodapeAtual = $logosRodape[0];
} else {
    $logoRodapeAtual = __DIR__ . '/img/logo_rodape.png'; // logo padrão
}

// --- Upload da nova logo ---
$logoMsg = '';
if (isset($_POST['trocar_logo']) && isset($_FILES['nova_logo']) && $_FILES['nova_logo']['error'] === UPLOAD_ERR_OK) {
    $ext = strtolower(pathinfo($_FILES['nova_logo']['name'], PATHINFO_EXTENSION));
    if (in_array($ext, ['png','jpg','jpeg'])) {
        $destino = $logoDir . '/logo_' . time() . '.' . $ext;
        if (move_uploaded_file($_FILES['nova_logo']['tmp_name'], $destino)) {
            $logoAtual = $destino;
            $logoMsg = 'Logo trocada com sucesso!';
        } else {
            $logoMsg = 'Erro ao salvar a nova logo.';
        }
    } else {
        $logoMsg = 'Apenas PNG ou JPG são aceitos.';
    }
}

// --- Limpar cache (apagar banners) ---
$apagarMsg = '';
if (isset($_POST['apagar_banners'])) {
    $apagados = 0;
    foreach (glob($imgDir . '/*Banner*') as $arq) {
        if (is_file($arq)) {
            unlink($arq);
            $apagados++;
        }
    }
    $apagarMsg = $apagados . ' banners apagados!';
}

// --- Banner principal ---
$imageWidth = 1000;
$baseImageHeight = 2000;

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT) ?: 550;
$tipo = filter_input(INPUT_GET, 'tipo', FILTER_DEFAULT) ?: 'filme';

function getJson($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $resp = curl_exec($ch);
    curl_close($ch);
    return json_decode($resp, true);
}

function loadImageWithCurl($url, $defaultImage) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $data = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($data === false || $httpCode !== 200) return $defaultImage;
    $tmp = tempnam(sys_get_temp_dir(), 'poster_');
    file_put_contents($tmp, $data);
    return $tmp;
}

function loadImageAuto($file) {
    $info = @getimagesize($file);
    if (!$info) return false;
    switch ($info['mime']) {
        case 'image/jpeg': return @imagecreatefromjpeg($file);
        case 'image/png': return @imagecreatefrompng($file);
        case 'image/gif': return @imagecreatefromgif($file);
        default: return false;
    }
}

function calcularAlturaSinopse($font, $fontSize, $text, $boxW) {
    $words = explode(' ', $text);
    $lines = [];
    $line = '';
    foreach ($words as $word) {
        $test = trim($line . ' ' . $word);
        $bbox = imagettfbbox($fontSize, 0, $font, $test);
        $textWidth = $bbox[2] - $bbox[0];
        if ($textWidth <= $boxW) {
            $line = $test;
        } else {
            $lines[] = $line;
            $line = $word;
        }
    }
    $lines[] = $line;
    $lineHeight = $fontSize + 10;
    $totalHeight = count($lines) * $lineHeight;
    return [$totalHeight, $lines, $lineHeight];
}

function wrapTextMultilineAutoFont($image, $font, $fontSize, $lines, $boxX, $boxY, $boxW, $boxH, $color, $shadow = false) {
    $lineHeight = $fontSize + 10;
    $totalHeight = count($lines) * $lineHeight;
    $y = $boxY + ($boxH - $totalHeight) / 2 + $fontSize;
    foreach ($lines as $line) {
        $bbox = imagettfbbox($fontSize, 0, $font, $line);
        $textWidth = $bbox[2] - $bbox[0];
        $x = $boxX + ($boxW - $textWidth) / 2;
        if ($shadow) {
            $black = imagecolorallocate($image, 0,0,0);
            imagettftext($image, $fontSize, 0, $x+2, $y+2, $black, $font, $line);
        }
        imagettftext($image, $fontSize, 0, $x, $y, $color, $font, $line);
        $y += $lineHeight;
    }
}

function imagefilledroundedrectangle($im, $x1, $y1, $x2, $y2, $radius, $color) {
    imagefilledrectangle($im, $x1+$radius, $y1, $x2-$radius, $y2, $color);
    imagefilledrectangle($im, $x1, $y1+$radius, $x2, $y2-$radius, $color);
    imagefilledellipse($im, $x1+$radius, $y1+$radius, $radius*2, $radius*2, $color);
    imagefilledellipse($im, $x2-$radius, $y1+$radius, $radius*2, $radius*2, $color);
    imagefilledellipse($im, $x1+$radius, $y2-$radius, $radius*2, $radius*2, $color);
    imagefilledellipse($im, $x2-$radius, $y2-$radius, $radius*2, $radius*2, $color);
}

// --- DADOS DO TMDB ---
$tipoEndpoint = ($tipo === 'filme') ? 'movie' : 'tv';
$conteudoUrl = "https://api.themoviedb.org/3/$tipoEndpoint/$id?api_key=$apiKey&language=$language";
$conteudo = getJson($conteudoUrl);
$sinopse = $conteudo['overview'] ?? 'Sem sinopse disponível.';
$poster = !empty($conteudo['poster_path']) ? "https://image.tmdb.org/t/p/w342" . $conteudo['poster_path'] : null;

// --- CARREGUE O POSTER ---
$posterFile = $poster ? loadImageWithCurl($poster, $defaultPoster) : $defaultPoster;
$bgPoster = loadImageAuto($posterFile);

// --- POSICIONAMENTO DOS ELEMENTOS ---
$logoW = (int)($imageWidth * 0.36);
$logoH = (int)($baseImageHeight * 0.12);
$logoY = 44;
$logoX = (int)(($imageWidth - $logoW) / 2);

$capMaxH = (int)($baseImageHeight * 0.50);
$capMaxW = (int)($imageWidth * 0.62);
if ($bgPoster) {
    $srcW = imagesx($bgPoster);
    $srcH = imagesy($bgPoster);
    $ratio = min($capMaxW / $srcW, $capMaxH / $srcH);
    $capW = (int)($srcW * $ratio);
    $capH = (int)($srcH * $ratio);
    $capX = (int)(($imageWidth - $capW) / 2);
    $capY = $logoY + $logoH + 32;
}

$sinopseGap = 36;
$sinopseBoxX = (int)($imageWidth * 0.10);
$sinopseBoxW = $imageWidth - (int)($imageWidth * 0.20);
$sinopseFontSize = (int)($imageWidth * 0.023);
list($sinopseTotalHeight, $sinopseLines, $lineHeight) = calcularAlturaSinopse($font, $sinopseFontSize, $sinopse, $sinopseBoxW);
$sinopseBoxH = $sinopseTotalHeight + (int)($baseImageHeight * 0.04);
$sinopseCardH = $sinopseBoxH + (int)($baseImageHeight * 0.04);

$sinopseCardX1 = (int)($imageWidth * 0.07);
$sinopseCardX2 = $imageWidth - (int)($imageWidth * 0.07);

$sinopseCardY = $capY + $capH + 48;
$sinopseCardY2 = $sinopseCardY + $sinopseCardH;
$sinopseBoxY = $sinopseCardY + (int)($baseImageHeight * 0.02);

// --- BOTÃO PNG MAIOR (cálculo inicial com baseImageHeight) ---
$botaoMaxW = (int)($imageWidth * 0.80);
$botaoMaxH = (int)($baseImageHeight * 0.14);
$botaoGap = 48;
$botaoImg = imagecreatefrompng($botaoPath);
imagealphablending($botaoImg, true);
imagesavealpha($botaoImg, true);
$botaoOrigW = imagesx($botaoImg);
$botaoOrigH = imagesy($botaoImg);
$botaoRatio = min($botaoMaxW / $botaoOrigW, $botaoMaxH / $botaoOrigH, 1);
$botaoW = (int)($botaoOrigW * $botaoRatio);
$botaoH = (int)($botaoOrigH * $botaoRatio);
$botaoX = (int)(($imageWidth - $botaoW) / 2);
$botaoY = $sinopseCardY2 + $botaoGap;

// --- AJUSTE ALTURA FINAL ---
$finalBannerBottom = $botaoY + $botaoH + 60;
$imageHeight = max($baseImageHeight, $finalBannerBottom);

// --- Recalcule o tamanho do botão PNG com o valor correto de $imageHeight ---
$botaoMaxH = (int)($imageHeight * 0.14);
$botaoRatio = min($botaoMaxW / $botaoOrigW, $botaoMaxH / $botaoOrigH, 1);
$botaoW = (int)($botaoOrigW * $botaoRatio);
$botaoH = (int)($botaoOrigH * $botaoRatio);
$botaoX = (int)(($imageWidth - $botaoW) / 2);
$botaoY = $sinopseCardY2 + $botaoGap;

// --- CRIE A IMAGEM FINAL COM A ALTURA REAL ---
$image = imagecreatetruecolor($imageWidth, $imageHeight);

// --- FUNDO: POSTER DESFOCADO E ESCURECIDO (EFEITO NETFLIX) ---
if ($bgPoster) {
    $bgBlur = imagecreatetruecolor($imageWidth, $imageHeight);
    imagecopyresampled($bgBlur, $bgPoster, 0, 0, 0, 0, $imageWidth, $imageHeight, imagesx($bgPoster), imagesy($bgPoster));
    for ($i = 0; $i < 3; $i++) { // menos blur = mais rápido
        imagefilter($bgBlur, IMG_FILTER_GAUSSIAN_BLUR);
    }
    $escurecer = imagecolorallocatealpha($bgBlur, 0, 0, 0, 60);
    imagefilledrectangle($bgBlur, 0, 0, $imageWidth, $imageHeight, $escurecer);
    imagecopy($image, $bgBlur, 0, 0, 0, 0, $imageWidth, $imageHeight);
    imagedestroy($bgBlur);
} else {
    $black = imagecolorallocate($image, 0,0,0);
    imagefilledrectangle($image, 0, 0, $imageWidth, $imageHeight, $black);
}

// --- DEGRADÊ PRETO UNIFORME EM TODA A ALTURA ---
for ($i = 0; $i < $imageHeight; $i++) {
    $fade = imagecolorallocatealpha(
        $image,
        0, 0, 0,
        (int)(127 * ($i / $imageHeight))
    );
    imagefilledrectangle($image, 0, $i, $imageWidth, $i, $fade);
}

// --- LOGO ---
$logoImg = @imagecreatefrompng($logoAtual);
if ($logoImg) {
    imagecopyresampled($image, $logoImg, $logoX, $logoY, 0, 0, $logoW, $logoH, imagesx($logoImg), imagesy($logoImg));
    imagedestroy($logoImg);
}

// --- CAPA CENTRALIZADA (poster nítido com sombra) ---
if ($bgPoster) {
    $shadowColor = imagecolorallocatealpha($image, 0, 0, 0, 80);
    imagefilledellipse($image, $capX + $capW/2, $capY + $capH + 16, $capW * 0.92, 44, $shadowColor);
    imagecopyresampled($image, $bgPoster, $capX, $capY, 0, 0, $capW, $capH, $srcW, $srcH);
}

// --- SINOPSE (discreta, sem borda, logo após a capa) ---
$white = imagecolorallocate($image, 255,255,255);
$sinopseCardColor = imagecolorallocatealpha($image, 20, 20, 20, 85);
imagefilledroundedrectangle($image, $sinopseCardX1, $sinopseCardY, $sinopseCardX2, $sinopseCardY2, 22, $sinopseCardColor);
wrapTextMultilineAutoFont($image, $font, $sinopseFontSize, $sinopseLines, $sinopseBoxX, $sinopseBoxY, $sinopseBoxW, $sinopseTotalHeight, $white, true);

// --- LOGO NO RODAPÉ ---
$logoRodapeW = (int)($imageWidth * 0.36);
$logoRodapeH = (int)($imageHeight * 0.08);
$logoRodapeX = (int)(($imageWidth - $logoRodapeW) / 2);
$logoRodapeY = $botaoY - ($logoRodapeH + 20); // posição acima dos botões

$logoRodapeImg = @imagecreatefrompng($logoRodapeAtual);
if ($logoRodapeImg) {
    imagecopyresampled($image, $logoRodapeImg, $logoRodapeX, $logoRodapeY, 0, 0, $logoRodapeW, $logoRodapeH, imagesx($logoRodapeImg), imagesy($logoRodapeImg));
    imagedestroy($logoRodapeImg);
}
// --- BOTÃO PNG MAIOR ---
imagecopyresampled($image, $botaoImg, $botaoX, $botaoY, 0, 0, $botaoW, $botaoH, $botaoOrigW, $botaoOrigH);
imagedestroy($botaoImg);

// --- SALVA O BANNER COM COMPACTAÇÃO ---
if (!is_dir($imgDir)) mkdir($imgDir, 0777, true);
$nomeArquivo = 'img/' . $id . '_' . $tipo . '_Banner.png';
imagepng($image, $nomeArquivo, 8); // compressão para carregar mais rápido
imagedestroy($image);
if ($posterFile !== $defaultPoster) @unlink($posterFile);

// --- EXIBE HTML ---
$protocolo = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$url = $protocolo . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url = dirname($url) . '/' . $nomeArquivo;
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Pôster Gerado</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@600&display=swap" rel="stylesheet">
<style>
body {
    background: #000;
    color: #fff;
    font-family: 'Montserrat', Arial, sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    min-height: 100vh;
    margin: 0;
}
.banner-container {
    background: rgba(0,0,0,0.85);
    box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.22);
    border-radius: 24px;
    padding: 32px 24px 24px 24px;
    margin-top: 32px;
    max-width: 98vw;
    width: 340px;
    display: flex;
    flex-direction: column;
    align-items: center;
    backdrop-filter: blur(8px);
}
img {
    max-width: 100%;
    border-radius: 18px;
    box-shadow: 0 4px 16px #0007;
    margin-bottom: 24px;
}
.buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    justify-content: center;
    margin-top: 20px;
}
.button {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 24px;
    background: linear-gradient(90deg,#E50914 60%,#b00610 100%);
    color: #fff;
    border: none;
    border-radius: 8px;
    font-weight: bold;
    font-size: 1rem;
    cursor: pointer;
    text-decoration: none;
    box-shadow: 0 2px 8px #E5091433;
    transition: background 0.2s, transform 0.2s;
}
.button:hover {
    background: linear-gradient(90deg,#b00610 60%,#E50914 100%);
    transform: translateY(-2px) scale(1.04);
}
.form-logo {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 18px;
    gap: 6px;
}
input[type="file"] {
    color: #fff;
    background: #222;
    border-radius: 6px;
    padding: 6px;
}
input[type="submit"] {
    background: linear-gradient(90deg,#E50914 60%,#b00610 100%);
    color: #fff;
    border: none;
    border-radius: 8px;
    font-weight: bold;
    font-size: 1rem;
    padding: 8px 18px;
    cursor: pointer;
    margin-top: 6px;
    box-shadow: 0 2px 8px #E5091433;
    transition: background 0.2s, transform 0.2s;
}
input[type="submit"]:hover {
    background: linear-gradient(90deg,#b00610 60%,#E50914 100%);
    transform: translateY(-2px) scale(1.04);
}
.msg {
    color: #fff;
    font-size: 0.98rem;
    margin-bottom: 10px;
    text-align: center;
}
@media (max-width: 600px) {
    .banner-container { width: 98vw; padding: 12px 2vw; }
}
</style>
</head>
<body>
<div class="banner-container">
    <?php if ($logoMsg) echo '<div class="msg">'.$logoMsg.'</div>'; ?>
    <?php if ($apagarMsg) echo '<div class="msg">'.$apagarMsg.'</div>'; ?>
    <form class="form-logo" method="post" enctype="multipart/form-data">
        <label for="nova_logo" style="color:#fff;">Trocar Logo:</label>
        <input type="file" name="nova_logo" id="nova_logo" accept="image/png, image/jpeg">
        <input type="submit" name="trocar_logo" value="Trocar Logo">
    </form>
    <form class="form-logo" method="post" style="margin-bottom:22px;">
        <input type="submit" name="apagar_banners" value="Limpar Banners">
    </form>
        <form class="form-logo" method="post" enctype="multipart/form-data">
        <label for="nova_logo_rodape" style="color:#fff;">Trocar Logomarca 2:</label>
        <input type="file" name="nova_logo_rodape" id="nova_logo_rodape" accept="image/png, image/jpeg">
        <input type="submit" name="trocar_logo_rodape" value="Trocar Logomarca 2">
    </form>
    <img src="<?= $nomeArquivo ?>" alt="Banner">
    <div class="buttons">
        <a class="button" href="<?= $nomeArquivo ?>" target="_blank" title="Ver imagem em nova aba">
            Ver Imagem
        </a>
        <a class="button" href="<?= $nomeArquivo ?>" download title="Baixar imagem">
            Baixar
        </a>
        <a class="button" href="index.php" title="Criar novo banner">
            Novo Banner
        </a>
        <a class="button" href="https://wa.me/?text=<?= urlencode('Confira esse pôster: ' . $url) ?>" target="_blank" title="Compartilhar no WhatsApp">
            WhatsApp
        </a>
    </div>
</div>
</body>
</html>
