<?php
/**
 * GERADOR VODS - VERSÃO MULTI-REVENDA FINAL (COM CARDS E EDIÇÃO)
 */

session_start();

// ========== CONFIGURAÇÕES ==========
define('API_KEY', 'a688ebacd173967acc7359daa726e3d3');
define('API_URL', 'https://api.themoviedb.org/3');
define('ADMIN_USER', 'admin');
define('ADMIN_PASS', 'admin123');
define('RESELLERS_FILE', 'resellers.json');

// Garantir pastas
$folders = ['assets/img/resellers', 'resellers_banners', 'banners', 'assets/fonts'];
foreach($folders as $f) { if(!is_dir($f)) mkdir($f, 0777, true); }

// ========== FUNÇÕES ==========
function apiRequest($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

function getDetails($type, $id) {
    return apiRequest(API_URL . '/' . $type . '/' . $id . '?api_key=' . API_KEY . '&language=pt-BR');
}

function imagefilledroundedrectangle($img, $x1, $y1, $x2, $y2, $radius, $color) {
    imagefilledrectangle($img, $x1 + $radius, $y1, $x2 - $radius, $y2, $color);
    imagefilledrectangle($img, $x1, $y1 + $radius, $x2, $y2 - $radius, $color);
    $t = $radius * 2;
    imagefilledarc($img, $x1 + $radius, $y1 + $radius, $t, $t, 180, 270, $color, IMG_ARC_PIE);
    imagefilledarc($img, $x2 - $radius, $y1 + $radius, $t, $t, 270, 360, $color, IMG_ARC_PIE);
    imagefilledarc($img, $x1 + $radius, $y2 - $radius, $t, $t, 90, 180, $color, IMG_ARC_PIE);
    imagefilledarc($img, $x2 - $radius, $y2 - $radius, $t, $t, 0, 90, $color, IMG_ARC_PIE);
}

function getResellers() {
    if (!file_exists(RESELLERS_FILE)) file_put_contents(RESELLERS_FILE, json_encode(['resellers' => []]));
    $d = json_decode(file_get_contents(RESELLERS_FILE), true);
    return $d['resellers'] ?? [];
}

function saveResellers($r) {
    file_put_contents(RESELLERS_FILE, json_encode(['resellers' => array_values($r)], JSON_PRETTY_PRINT));
}

function getLogo($user) {
    if ($user == 'admin') {
        foreach (['png','jpg','jpeg','webp'] as $e) {
            if(file_exists("assets/img/logo.{$e}")) {
                return "assets/img/logo.{$e}";
            }
        }
        return null;
    }
    foreach (['png','jpg','jpeg','webp'] as $e) {
        if(file_exists("assets/img/resellers/{$user}.{$e}")) {
            return "assets/img/resellers/{$user}.{$e}";
        }
    }
    return null;
}

function checkExpiration($user) {
    $resellers = getResellers();
    foreach ($resellers as $r) {
        if ($r['user'] == $user && isset($r['expires'])) {
            $expires = strtotime($r['expires']);
            $now = time();
            $daysLeft = floor(($expires - $now) / 86400);
            return ['expires' => $r['expires'], 'days' => $daysLeft, 'expired' => $daysLeft < 0];
        }
    }
    return null;
}

// ========== GERADOR DE BANNER ==========
function generateBanner($style, $type, $id, $mode, $overview, $size, $user) {
    $details = getDetails($type, $id);
    if (!$details) return false;

    $title = $details['title'] ?? $details['name'] ?? 'Sem Título';
    $ov = $overview ?: ($details['overview'] ?? 'Sinopse não disponível');
    $poster = $details['poster_path'];
    $backdrop = $details['backdrop_path'];
    $rating = number_format($details['vote_average'] ?? 0, 1);
    $year = date('Y', strtotime($details['release_date'] ?? $details['first_air_date'] ?? 'now'));

    $s = ['vertical'=>['w'=>1080,'h'=>1350], 'horizontal'=>['w'=>1280,'h'=>720], 'square'=>['w'=>1080,'h'=>1080]];
    $sz = $s[$size] ?? $s['vertical'];
    $w = $sz['w']; $h = $sz['h'];
    
    $url = ($mode == 'horizontal') ? ($backdrop ? "https://image.tmdb.org/t/p/original$backdrop" : "https://image.tmdb.org/t/p/original$poster") : ($poster ? "https://image.tmdb.org/t/p/original$poster" : "https://image.tmdb.org/t/p/original$backdrop");

    $img = imagecreatetruecolor($w, $h);
    $bg = imagecolorallocate($img, 15, 18, 28);
    imagefilledrectangle($img, 0, 0, $w, $h, $bg);

    $data = @file_get_contents($url, false, stream_context_create(['ssl'=>['verify_peer'=>false]]));
    if ($data) {
        $base = @imagecreatefromstring($data);
        if ($base) {
            $sw = imagesx($base); $sh = imagesy($base);
            $r = max($w/$sw, $h/$sh);
            $nw = (int)($sw*$r); $nh = (int)($sh*$r);
            imagecopyresampled($img, $base, (int)(($w-$nw)/2), ($mode=='vertical'?0:(int)(($h-$nh)/2)), 0, 0, $nw, $nh, $sw, $sh);
            imagedestroy($base);
        }
    }

    $lp = getLogo($user);
    if ($lp) {
        $ld = @file_get_contents($lp);
        if ($ld) {
            $l = @imagecreatefromstring($ld);
            if ($l) {
                imagealphablending($l, true); imagesavealpha($l, true);
                $lw = imagesx($l); $lh = imagesy($l);
                $lr = min(($w*0.3)/$lw, ($h*0.3)/$lh);
                imagecopyresampled($img, $l, 40, 40, 0, 0, (int)($lw*$lr), (int)($lh*$lr), $lw, $lh);
                imagedestroy($l);
            }
        }
    }

    $branco = imagecolorallocate($img, 255, 255, 255);
    $dourado = imagecolorallocate($img, 241, 196, 15);
    $ft = imagecolorallocatealpha($img, 0, 0, 0, 90);
    
    $f_bold = __DIR__ . '/assets/fonts/Roboto-Bold.ttf';
    $f_reg = __DIR__ . '/assets/fonts/Roboto-Regular.ttf';
    
    if (!file_exists($f_bold) || !file_exists($f_reg)) {
        $fontUrl = 'https://github.com/google/fonts/raw/main/apache/roboto/Roboto-Regular.ttf';
        $fontBoldUrl = 'https://github.com/google/fonts/raw/main/apache/roboto/Roboto-Bold.ttf';
        @file_put_contents($f_reg, file_get_contents($fontUrl));
        @file_put_contents($f_bold, file_get_contents($fontBoldUrl));
    }

    if (file_exists($f_bold) && file_exists($f_reg)) {
        imagefilledroundedrectangle($img, 50, $h-450, $w-50, $h-50, 25, $ft);
        
        $titleText = mb_strtoupper($title, 'UTF-8');
        $fontSize = 45;
        $bbox = imagettfbbox($fontSize, 0, $f_bold, $titleText);
        $textWidth = $bbox[2] - $bbox[0];
        if ($textWidth > ($w - 180)) {
            $fontSize = floor($fontSize * (($w - 180) / $textWidth));
        }
        imagettftext($img, $fontSize, 0, 90, $h-350, $branco, $f_bold, $titleText);
        
        imagettftext($img, 22, 0, 90, $h-300, $dourado, $f_reg, "★ $rating | $year");
        
        $sinopse = strip_tags($ov);
        $sinopse = trim(preg_replace('/\s+/', ' ', $sinopse));
        $words = explode(' ', $sinopse);
        $lines = [];
        $currentLine = '';
        $maxWidth = $w - 180;
        
        foreach ($words as $word) {
            $testLine = $currentLine ? $currentLine . ' ' . $word : $word;
            $bbox = imagettfbbox(20, 0, $f_reg, $testLine);
            $lineWidth = $bbox[2] - $bbox[0];
            if ($lineWidth <= $maxWidth) {
                $currentLine = $testLine;
            } else {
                if ($currentLine) $lines[] = $currentLine;
                $currentLine = $word;
            }
        }
        if ($currentLine) $lines[] = $currentLine;
        
        $lines = array_slice($lines, 0, 3);
        if (count($lines) == 3 && str_word_count($sinopse) > 20) {
            $lines[2] = rtrim($lines[2]) . '...';
        }
        
        $yPos = $h-250;
        foreach ($lines as $line) {
            imagettftext($img, 20, 0, 90, $yPos, $branco, $f_reg, $line);
            $yPos += 30;
        }
    }

    $d = ($user == 'admin') ? "banners" : "resellers_banners/$user";
    if (!is_dir($d)) mkdir($d, 0777, true);
    $n = "$d/".time().".jpg";
    imagejpeg($img, $n, 90);
    imagedestroy($img);
    return $n;
}

// ========== LÓGICA ==========
$p = $_GET['page'] ?? 'home';
$a = $_GET['action'] ?? '';
$is_admin = isset($_SESSION['admin_logged']);
$is_reseller = isset($_SESSION['reseller_logged']);
$u = $_SESSION['reseller_user'] ?? null;

// BLOQUEIO POR VENCIMENTO - REFORÇADO
if ($is_reseller && $u) {
    $expiration = checkExpiration($u);
    if ($expiration && $expiration['expired']) {
        session_destroy();
        header('Location: ?page=login&expired=1');
        exit;
    }
}

// BLOQUEIA TODAS AS AÇÕES SE EXPIRADO (EXCETO LOGOUT)
if ($is_reseller && $u && $a != 'logout') {
    $expiration = checkExpiration($u);
    if ($expiration && $expiration['expired']) {
        session_destroy();
        header('Location: ?page=login&expired=1');
        exit;
    }
}

if ($a == 'login') {
    $user = $_POST['user'] ?? ''; $pass = $_POST['pass'] ?? '';
    if ($user == ADMIN_USER && $pass == ADMIN_PASS) {
        $_SESSION['admin_logged'] = true; $_SESSION['reseller_user'] = 'admin';
        header('Location: ?page=home'); exit;
    } else {
        foreach (getResellers() as $r) {
            if ($r['user'] == $user && $r['pass'] == $pass) {
                $exp = checkExpiration($user);
                if ($exp && $exp['expired']) {
                    header('Location: ?page=login&expired=1');
                    exit;
                }
                $_SESSION['reseller_logged'] = true; $_SESSION['reseller_user'] = $user;
                header('Location: ?page=home'); exit;
            }
        }
    }
}
if ($a == 'logout') { session_destroy(); header('Location: ?page=home'); exit; }

if ($a == 'uploadLogo' && ($is_admin || $is_reseller)) {
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
        $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
        if ($u == 'admin') {
            foreach(['png','jpg','jpeg','webp'] as $e) @unlink("assets/img/logo.{$e}");
            $path = "assets/img/logo.{$ext}";
        } else {
            foreach(['png','jpg','jpeg','webp'] as $e) @unlink("assets/img/resellers/{$u}.{$e}");
            $path = "assets/img/resellers/{$u}.{$ext}";
        }
        move_uploaded_file($_FILES['logo']['tmp_name'], $path);
    }
    header('Location: ' . $_SERVER['HTTP_REFERER']); exit;
}

if ($a == 'addReseller' && $is_admin) {
    $r = getResellers();
    $r[] = [
        'user'=>$_POST['user'], 
        'pass'=>$_POST['pass'], 
        'name'=>$_POST['name'],
        'expires'=>$_POST['expires']
    ];
    saveResellers($r);
    header('Location: ?page=admin'); exit;
}

if ($a == 'updateReseller' && $is_admin) {
    $r = getResellers();
    $id = $_GET['id'];
    if (isset($r[$id])) {
        $r[$id]['name'] = $_POST['name'];
        $r[$id]['user'] = $_POST['user'];
        $r[$id]['pass'] = $_POST['pass'];
        $r[$id]['expires'] = $_POST['expires'];
        saveResellers($r);
    }
    header('Location: ?page=admin'); exit;
}

if ($a == 'delReseller' && $is_admin) {
    $r = getResellers();
    if (isset($r[$_GET['id']])) {
        $user = $r[$_GET['id']]['user'];
        $dir = "resellers_banners/$user";
        if (is_dir($dir)) {
            array_map('unlink', glob("$dir/*.jpg"));
            rmdir($dir);
        }
        foreach(['png','jpg','jpeg','webp'] as $e) @unlink("assets/img/resellers/{$user}.{$e}");
    }
    unset($r[$_GET['id']]);
    saveResellers($r);
    header('Location: ?page=admin'); exit;
}

if ($a == 'generate' && ($is_admin || $is_reseller)) {
    $file = generateBanner($_GET['style'], $_GET['type'], $_GET['id'], $_GET['mode'], $_POST['overview'], $_GET['size'], $u);
    echo json_encode(['success'=>!!$file, 'file'=>$file]); exit;
}

if ($a == 'delBanner' && ($is_admin || $is_reseller)) {
    $f = $_GET['file'];
    $allowed = false;
    if ($u == 'admin' && strpos($f, 'banners/') === 0) {
        $allowed = true;
    } else if ($u != 'admin' && strpos($f, "resellers_banners/$u/") === 0) {
        $allowed = true;
    }
    if ($allowed) @unlink($f);
    header('Location: ' . $_SERVER['HTTP_REFERER']); exit;
}

if ($a == 'deleteAllBanners' && ($is_admin || $is_reseller)) {
    $d = ($u == 'admin') ? "banners" : "resellers_banners/$u";
    if (is_dir($d)) {
        $files = glob("$d/*.jpg");
        foreach ($files as $f) @unlink($f);
    }
    header('Location: ?page=galeria'); exit;
}

$logo = null;
if ($is_admin || $is_reseller) {
    $logo = getLogo($u);
}
$expiration = null;
if ($is_reseller && $u) {
    $expiration = checkExpiration($u);
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GERADOR VODS</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --bg: #0d1117; 
            --card: #161b22; 
            --border: #30363d; 
            --text: #e6edf3; 
            --primary: #58a6ff; 
            --danger: #ff4d4d; 
            --warning: #f1c40f;
            --success: #2ea043;
        }
        * { box-sizing: border-box; }
        body { background: var(--bg); color: var(--text); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; }
        .nav { background: var(--card); padding: 15px 30px; display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid var(--primary); flex-wrap: wrap; gap: 10px; }
        .container { max-width: 1200px; margin: 30px auto; padding: 0 20px; }
        .btn { padding: 10px 18px; border-radius: 6px; border: none; cursor: pointer; font-weight: bold; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; font-size: 14px; transition: 0.3s; }
        .btn-p { background: var(--primary); color: #fff; }
        .btn-p:hover { opacity: 0.8; transform: translateY(-2px); }
        .btn-d { background: var(--success); color: #fff; }
        .btn-d:hover { background: #3fb950; transform: translateY(-2px); }
        .btn-danger { background: var(--danger); color: #fff; }
        .btn-danger:hover { background: #e63946; transform: translateY(-2px); }
        .btn-warning { background: var(--warning); color: #000; }
        .btn-warning:hover { background: #f39c12; transform: translateY(-2px); }
        .btn-edit { background: #6c757d; color: #fff; }
        .btn-edit:hover { background: #5a6268; transform: translateY(-2px); }
        .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 20px; }
        .card { background: var(--card); border-radius: 10px; overflow: hidden; border: 1px solid var(--border); transition: 0.3s; }
        .card:hover { border-color: var(--primary); transform: translateY(-5px); box-shadow: 0 8px 25px rgba(88, 166, 255, 0.1); }
        .card img { width: 100%; height: 320px; object-fit: cover; }
        .card-body { padding: 15px; }
        .modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.85); align-items: center; justify-content: center; z-index: 1000; padding: 20px; }
        .modal-content { background: var(--card); padding: 30px; border-radius: 15px; width: 100%; max-width: 500px; border: 1px solid var(--border); max-height: 90vh; overflow-y: auto; }
        input, select, textarea { width: 100%; padding: 12px; margin: 10px 0; background: #000; border: 1px solid var(--border); color: #fff; border-radius: 6px; box-sizing: border-box; }
        input:focus, select:focus, textarea:focus { outline: 2px solid var(--primary); border-color: var(--primary); }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 15px; text-align: left; border-bottom: 1px solid var(--border); }
        th { color: var(--primary); }
        .actions { display: flex; gap: 8px; flex-wrap: wrap; }
        .warning-badge { 
            background: var(--warning); 
            color: #000; 
            padding: 4px 12px; 
            border-radius: 12px; 
            font-size: 12px; 
            font-weight: bold;
            animation: blink 1s infinite;
        }
        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.3; }
        }
        .expired-badge {
            background: var(--danger);
            color: #fff;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }
        .alert-box {
            background: rgba(241, 196, 15, 0.2);
            border: 1px solid var(--warning);
            border-radius: 10px;
            padding: 15px 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .alert-box i { color: var(--warning); font-size: 24px; }
        .header-actions { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
        @keyframes spin { to { transform: rotate(360deg); } }

        /* CARDS REVENDAS */
        .reseller-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 25px;
            margin-top: 30px;
        }
        .reseller-card {
            background: var(--card);
            border-radius: 15px;
            border: 1px solid var(--border);
            padding: 25px;
            transition: 0.3s;
            position: relative;
            overflow: hidden;
        }
        .reseller-card:hover {
            transform: translateY(-5px);
            border-color: var(--primary);
            box-shadow: 0 8px 30px rgba(88, 166, 255, 0.15);
        }
        .reseller-card .header {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 15px;
        }
        .reseller-card .avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: var(--border);
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            border: 2px solid var(--primary);
        }
        .reseller-card .avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .reseller-card .avatar i {
            font-size: 30px;
            color: var(--primary);
        }
        .reseller-card .name {
            font-size: 18px;
            font-weight: bold;
            color: var(--text);
        }
        .reseller-card .username {
            color: #8b949e;
            font-size: 14px;
        }
        .reseller-card .info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin: 15px 0;
            padding: 15px 0;
            border-top: 1px solid var(--border);
            border-bottom: 1px solid var(--border);
        }
        .reseller-card .info-item {
            text-align: center;
        }
        .reseller-card .info-item .label {
            color: #8b949e;
            font-size: 12px;
        }
        .reseller-card .info-item .value {
            font-size: 18px;
            font-weight: bold;
            color: var(--text);
        }
        .reseller-card .status-badge {
            display: inline-block;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: bold;
        }
        .reseller-card .status-badge.active {
            background: rgba(46, 160, 67, 0.2);
            color: var(--success);
        }
        .reseller-card .status-badge.warning {
            background: rgba(241, 196, 15, 0.2);
            color: var(--warning);
            animation: blink 1s infinite;
        }
        .reseller-card .status-badge.expired {
            background: rgba(255, 77, 77, 0.2);
            color: var(--danger);
        }
        .reseller-card .actions {
            display: flex;
            gap: 8px;
            margin-top: 15px;
            justify-content: flex-end;
        }
        .reseller-card .actions .btn {
            padding: 8px 15px;
            font-size: 13px;
        }

        /* Responsivo */
        @media (max-width: 768px) {
            .nav { padding: 10px 15px; flex-direction: column; align-items: stretch; }
            .nav > div:first-child { justify-content: center; }
            .nav > div:last-child { justify-content: center; flex-wrap: wrap; }
            .container { padding: 0 10px; margin: 15px auto; }
            .reseller-grid { grid-template-columns: 1fr; }
            table { font-size: 12px; }
            th, td { padding: 8px; }
            .modal-content { padding: 20px; margin: 10px; }
            .btn { font-size: 12px; padding: 8px 12px; }
        }
        @media (max-width: 480px) {
            .reseller-card .info { grid-template-columns: 1fr; }
            .reseller-card .actions { flex-direction: column; }
            .reseller-card .actions .btn { width: 100%; justify-content: center; }
        }
    </style>
</head>
<body>

<nav class="nav">
    <div style="display:flex; align-items:center; gap:15px;">
        <?php if ($logo): ?>
            <img src="<?= $logo ?>" height="45" style="max-height:45px; width:auto;">
        <?php endif; ?>
        <span style="font-weight:bold; font-size:22px; color:var(--primary);">GERADOR VODS</span>
    </div>
    <div style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
        <a href="?page=home" class="btn" style="color:#fff;"><i class="fas fa-home"></i> Início</a>
        <?php if ($is_admin): ?>
            <a href="?page=admin" class="btn" style="color:#fff;"><i class="fas fa-users"></i> Revendas</a>
        <?php endif; ?>
        <?php if ($is_admin || $is_reseller): ?>
            <a href="?page=galeria" class="btn" style="color:#fff;"><i class="fas fa-images"></i> Meus Banners</a>
            <a href="?page=perfil" class="btn" style="color:#fff;"><i class="fas fa-image"></i> Minha Logo</a>
            <?php if ($expiration && $expiration['days'] >= 0 && $expiration['days'] <= 5): ?>
                <span class="warning-badge"><i class="fas fa-clock"></i> Expira em <?= $expiration['days'] ?> dias</span>
            <?php endif; ?>
            <a href="?action=logout" class="btn" style="color:var(--danger);"><i class="fas fa-sign-out-alt"></i> Sair</a>
        <?php else: ?>
            <a href="?page=login" class="btn btn-p"><i class="fas fa-lock"></i> Login</a>
        <?php endif; ?>
    </div>
</nav>

<div class="container">
    <?php if (isset($_GET['expired'])): ?>
        <div class="alert-box" style="border-color:var(--danger); background:rgba(255,77,77,0.2);">
            <i class="fas fa-exclamation-triangle" style="color:var(--danger);"></i>
            <div>
                <strong style="color:var(--danger);">Sua conta expirou!</strong>
                <p style="margin:5px 0 0 0; color:#8b949e;">Entre em contato com o administrador para renovar.</p>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($p == 'home'): ?>
        <form action="" method="GET" style="margin-bottom:30px; display:flex; gap:10px; flex-wrap:wrap;">
            <input type="hidden" name="page" value="home">
            <input type="text" name="search" placeholder="Pesquisar filmes ou séries..." value="<?= $_GET['search']??'' ?>" style="margin:0; flex:1; min-width:200px;">
            <button type="submit" class="btn btn-p"><i class="fas fa-search"></i> Buscar</button>
        </form>
        <div class="grid">
            <?php
            $q = urlencode($_GET['search'] ?? '');
            $url = $q ? API_URL."/search/multi?api_key=".API_KEY."&language=pt-BR&query=$q" : API_URL."/trending/all/week?api_key=".API_KEY."&language=pt-BR";
            $data = apiRequest($url);
            foreach ($data['results'] ?? [] as $item):
                if (!($item['poster_path']??'')) continue;
            ?>
                <div class="card">
                    <img src="https://image.tmdb.org/t/p/w500<?= $item['poster_path'] ?>">
                    <div class="card-body">
                        <div style="font-weight:bold; margin-bottom:15px; height:40px; overflow:hidden;"><?= $item['title']??$item['name'] ?></div>
                        <?php if ($is_admin || $is_reseller): ?>
                            <button onclick="openModal('<?= isset($item['title'])?'movie':'tv' ?>', '<?= $item['id'] ?>', `<?= addslashes($item['overview']??'') ?>`)" class="btn btn-p" style="width:100%; justify-content:center;"><i class="fas fa-magic"></i> Gerar Banner</button>
                        <?php else: ?>
                            <p style="text-align:center; font-size:12px; color:#8b949e;"><i class="fas fa-lock"></i> Login para gerar</p>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

    <?php elseif ($p == 'admin' && $is_admin): ?>
        <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px;">
            <h2>Gerenciar Revendas</h2>
            <button onclick="document.getElementById('modalReseller').style.display='flex'" class="btn btn-p"><i class="fas fa-plus"></i> Nova Revenda</button>
        </div>

        <!-- CARDS DAS REVENDAS -->
        <div class="reseller-grid">
            <?php foreach(getResellers() as $id => $r): 
                $bannerCount = count(glob("resellers_banners/{$r['user']}/*.jpg"));
                $exp = checkExpiration($r['user']);
                $statusClass = 'active';
                $statusText = 'Ativo';
                if ($exp) {
                    if ($exp['expired']) {
                        $statusClass = 'expired';
                        $statusText = 'Expirado';
                    } elseif ($exp['days'] <= 5) {
                        $statusClass = 'warning';
                        $statusText = $exp['days'] . ' dias';
                    } else {
                        $statusClass = 'active';
                        $statusText = $exp['days'] . ' dias';
                    }
                } else {
                    $statusText = 'Sem data';
                }
                $logoReseller = getLogo($r['user']);
            ?>
                <div class="reseller-card">
                    <div class="header">
                        <div class="avatar">
                            <?php if ($logoReseller): ?>
                                <img src="<?= $logoReseller ?>" alt="<?= htmlspecialchars($r['name']) ?>">
                            <?php else: ?>
                                <i class="fas fa-store"></i>
                            <?php endif; ?>
                        </div>
                        <div>
                            <div class="name"><?= htmlspecialchars($r['name']) ?></div>
                            <div class="username"><i class="fas fa-user"></i> <?= htmlspecialchars($r['user']) ?></div>
                        </div>
                    </div>
                    
                    <div class="info">
                        <div class="info-item">
                            <div class="label"><i class="fas fa-images"></i> Banners</div>
                            <div class="value"><?= $bannerCount ?></div>
                        </div>
                        <div class="info-item">
                            <div class="label"><i class="fas fa-calendar-alt"></i> Vencimento</div>
                            <div class="value" style="font-size:14px;">
                                <?= date('d/m/Y', strtotime($r['expires'] ?? 'now')) ?>
                            </div>
                        </div>
                    </div>

                    <div style="display:flex; justify-content:space-between; align-items:center;">
                        <span class="status-badge <?= $statusClass ?>"><?= $statusText ?></span>
                        <span style="color:#8b949e; font-size:12px;">ID: #<?= $id+1 ?></span>
                    </div>

                    <div class="actions">
                        <button onclick="editReseller(<?= $id ?>, '<?= addslashes($r['name']) ?>', '<?= addslashes($r['user']) ?>', '<?= addslashes($r['pass']) ?>', '<?= $r['expires'] ?? '' ?>')" class="btn btn-edit">
                            <i class="fas fa-edit"></i> Editar
                        </button>
                        <a href="?action=delReseller&id=<?= $id ?>" class="btn btn-danger" onclick="return confirm('Excluir esta revenda e todos os seus banners?')">
                            <i class="fas fa-trash"></i> Excluir
                        </a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

    <?php elseif ($p == 'galeria' && ($is_admin || $is_reseller)): ?>
        <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px; margin-bottom:20px;">
            <h2>Meus Banners Gerados</h2>
            <div class="header-actions">
                <a href="?page=home" class="btn btn-p"><i class="fas fa-plus"></i> Novo Banner</a>
                <button onclick="if(confirm('Tem certeza que deseja excluir TODOS os seus banners?')) location.href='?action=deleteAllBanners'" class="btn btn-danger"><i class="fas fa-trash-alt"></i> Excluir Todos</button>
            </div>
        </div>
        
        <?php
        $d = ($u == 'admin') ? "banners" : "resellers_banners/$u";
        $files = glob("$d/*.jpg");
        array_multisort(array_map('filemtime', $files), SORT_DESC, $files);
        ?>
        
        <?php if (empty($files)): ?>
            <div style="background:var(--card); padding:60px; text-align:center; border-radius:15px; border:1px solid var(--border);">
                <i class="fas fa-images" style="font-size:60px; color:#30363d; margin-bottom:20px;"></i>
                <p style="font-size:18px; color:#8b949e;">Você ainda não gerou nenhum banner.</p>
                <a href="?page=home" class="btn btn-p" style="margin-top:15px;"><i class="fas fa-plus"></i> Gerar Banner</a>
            </div>
        <?php else: ?>
            <div class="grid">
                <?php foreach ($files as $f): 
                    $filename = basename($f);
                ?>
                    <div class="card">
                        <img src="<?= $f ?>">
                        <div class="card-body" style="display:flex; gap:10px; flex-wrap:wrap;">
                            <a href="<?= $f ?>" download="<?= $filename ?>" class="btn btn-d" style="flex:1; justify-content:center; min-width:80px;"><i class="fas fa-download"></i> Baixar</a>
                            <a href="?action=delBanner&file=<?= $f ?>" class="btn btn-danger" style="flex:1; justify-content:center; min-width:80px;" onclick="return confirm('Excluir este banner?')"><i class="fas fa-trash"></i> Excluir</a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

    <?php elseif ($p == 'perfil' && ($is_admin || $is_reseller)): ?>
        <h2>Minha Logo Personalizada</h2>
        <div style="background:var(--card); padding:40px; border-radius:15px; text-align:center; border:1px solid var(--border);">
            <?php if ($logo): ?>
                <div style="background:#000; padding:20px; display:inline-block; border-radius:10px; margin-bottom:20px;">
                    <img src="<?= $logo ?>" style="max-width:300px; max-height:150px; width:auto;">
                </div>
                <p style="color:#8b949e; margin-bottom:20px;">Esta logo aparecerá em todos os seus banners.</p>
            <?php else: ?>
                <p style="color:#8b949e; margin-bottom:20px;">Você ainda não tem uma logo configurada.</p>
                <p style="color:#8b949e; font-size:14px; margin-bottom:20px;">Sua logo aparecerá em todos os banners que você gerar.</p>
            <?php endif; ?>
            <form action="?action=uploadLogo" method="POST" enctype="multipart/form-data" style="max-width:400px; margin:0 auto;">
                <input type="file" name="logo" accept="image/png,image/jpeg,image/webp" required>
                <button type="submit" class="btn btn-p" style="width:100%; justify-content:center; padding:15px;"><i class="fas fa-upload"></i> Atualizar Minha Logo</button>
            </form>
            <?php if ($logo): ?>
                <p style="color:#8b949e; font-size:12px; margin-top:15px;">Formatos suportados: PNG, JPG, JPEG, WEBP</p>
            <?php endif; ?>
        </div>

    <?php elseif ($p == 'login'): ?>
        <div style="max-width:400px; margin:100px auto; background:var(--card); padding:40px; border-radius:20px; text-align:center; border:1px solid var(--border);">
            <i class="fas fa-lock" style="font-size:50px; color:var(--primary); margin-bottom:20px;"></i>
            <h2>Acesso ao Sistema</h2>
            <?php if (isset($_GET['expired'])): ?>
                <div style="background:rgba(255,77,77,0.2); border:1px solid var(--danger); border-radius:8px; padding:10px; margin-bottom:15px;">
                    <p style="color:var(--danger); margin:0;"><i class="fas fa-exclamation-triangle"></i> Sua conta expirou! Entre em contato com o administrador.</p>
                </div>
            <?php endif; ?>
            <form action="?action=login" method="POST">
                <input type="text" name="user" placeholder="Usuário" required>
                <input type="password" name="pass" placeholder="Senha" required>
                <button type="submit" class="btn btn-p" style="width:100%; justify-content:center; padding:15px;">Entrar</button>
            </form>
        </div>
    <?php endif; ?>
</div>

<!-- Modal Gerar Banner -->
<div id="modalGerar" class="modal">
    <div class="modal-content">
        <h3 style="margin-top:0;"><i class="fas fa-magic" style="color:var(--primary);"></i> Configurar Banner</h3>
        <form id="formGerar">
            <label>Estilo</label>
            <select name="style">
                <option value="banner1">Padrão</option>
            </select>
            <label>Formato</label>
            <select name="size">
                <option value="vertical">Vertical (Story - 1080x1350)</option>
                <option value="horizontal">Horizontal (Feed - 1280x720)</option>
                <option value="square">Quadrado (1080x1080)</option>
            </select>
            <label>Sinopse (opcional)</label>
            <textarea name="overview" id="overview" rows="5" placeholder="Deixe em branco para usar a sinopse original do TMDB"></textarea>
            <button type="submit" class="btn btn-p" style="width:100%; justify-content:center; padding:15px;"><i class="fas fa-magic"></i> GERAR AGORA</button>
            <button type="button" onclick="document.getElementById('modalGerar').style.display='none'" class="btn" style="width:100%; justify-content:center; margin-top:10px; color:#fff; background:transparent; border:1px solid var(--border);">Cancelar</button>
        </form>
    </div>
</div>

<!-- Modal Nova Revenda -->
<div id="modalReseller" class="modal">
    <div class="modal-content">
        <h3 style="margin-top:0;"><i class="fas fa-store" style="color:var(--primary);"></i> Nova Revenda</h3>
        <form action="?action=addReseller" method="POST">
            <input type="text" name="name" placeholder="Nome da Revenda" required>
            <input type="text" name="user" placeholder="Usuário" required>
            <input type="password" name="pass" placeholder="Senha" required>
            <label>Data de Vencimento</label>
            <input type="date" name="expires" required>
            <button type="submit" class="btn btn-p" style="width:100%; justify-content:center;"><i class="fas fa-plus"></i> Criar Revenda</button>
            <button type="button" onclick="document.getElementById('modalReseller').style.display='none'" class="btn" style="width:100%; justify-content:center; margin-top:10px; color:#fff; background:transparent; border:1px solid var(--border);">Cancelar</button>
        </form>
    </div>
</div>

<!-- Modal Editar Revenda -->
<div id="modalEditReseller" class="modal">
    <div class="modal-content">
        <h3 style="margin-top:0;"><i class="fas fa-edit" style="color:var(--primary);"></i> Editar Revenda</h3>
        <form action="" method="POST" id="formEditReseller">
            <input type="text" name="name" id="edit_name" placeholder="Nome da Revenda" required>
            <input type="text" name="user" id="edit_user" placeholder="Usuário" required>
            <input type="password" name="pass" id="edit_pass" placeholder="Senha" required>
            <label>Data de Vencimento</label>
            <input type="date" name="expires" id="edit_expires" required>
            <button type="submit" class="btn btn-p" style="width:100%; justify-content:center;"><i class="fas fa-save"></i> Salvar Alterações</button>
            <button type="button" onclick="document.getElementById('modalEditReseller').style.display='none'" class="btn" style="width:100%; justify-content:center; margin-top:10px; color:#fff; background:transparent; border:1px solid var(--border);">Cancelar</button>
        </form>
    </div>
</div>

<!-- Loader -->
<div id="loader" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.9); z-index:2000; align-items:center; justify-content:center; flex-direction:column;">
    <div style="width:50px; height:50px; border:5px solid #30363d; border-top-color:var(--primary); border-radius:50%; animation:spin 1s linear infinite;"></div>
    <p style="margin-top:20px; font-weight:bold; color:#fff;">Gerando seu banner...</p>
    <p style="color:#8b949e; font-size:14px;">Isso pode levar alguns segundos</p>
</div>

<script>
let cur = {};

function openModal(t, id, s) {
    cur = { t, id };
    document.getElementById('overview').value = s;
    document.getElementById('modalGerar').style.display = 'flex';
}

function editReseller(id, name, user, pass, expires) {
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_user').value = user;
    document.getElementById('edit_pass').value = pass;
    document.getElementById('edit_expires').value = expires;
    document.getElementById('formEditReseller').action = `?action=updateReseller&id=${id}`;
    document.getElementById('modalEditReseller').style.display = 'flex';
}

document.getElementById('formGerar').onsubmit = async (e) => {
    e.preventDefault();
    document.getElementById('loader').style.display = 'flex';
    const fd = new FormData(e.target);
    const sz = fd.get('size');
    try {
        const res = await fetch(`?action=generate&type=${cur.t}&id=${cur.id}&style=${fd.get('style')}&size=${sz}&mode=${sz}`, {
            method: 'POST',
            body: fd
        });
        const j = await res.json();
        document.getElementById('loader').style.display = 'none';
        if (j.success) {
            window.location.href = '?page=galeria';
        } else {
            alert('Erro ao gerar o banner. Tente novamente.');
        }
    } catch (err) {
        document.getElementById('loader').style.display = 'none';
        alert('Erro na comunicação com o servidor.');
    }
};

window.onclick = (e) => { 
    if(e.target.className == 'modal') {
        e.target.style.display = 'none';
    }
};
</script>
</body>
</html>