<?php
/**
 * GERADOR VODS - VERSÃO COMPLETA COM ESTATÍSTICAS E PIX
 */

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');
define('STATS_FILE', 'stats.json');
define('PIX_FILE', 'pix_config.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;
}

// ========== FUNÇÕES DE ESTATÍSTICAS ==========
function getStats() {
    if (!file_exists(STATS_FILE)) {
        $default = [
            'downloads' => [],
            'generated' => [],
            'banners' => []
        ];
        file_put_contents(STATS_FILE, json_encode($default, JSON_PRETTY_PRINT));
    }
    return json_decode(file_get_contents(STATS_FILE), true);
}

function saveStats($stats) {
    file_put_contents(STATS_FILE, json_encode($stats, JSON_PRETTY_PRINT));
}

function registerDownload($user, $bannerFile) {
    $stats = getStats();
    $today = date('Y-m-d');
    
    // Registra download
    if (!isset($stats['downloads'][$user])) $stats['downloads'][$user] = [];
    if (!isset($stats['downloads'][$user][$today])) $stats['downloads'][$user][$today] = 0;
    $stats['downloads'][$user][$today]++;
    
    // Registra banner mais baixado
    if (!isset($stats['banners'][$bannerFile])) $stats['banners'][$bannerFile] = 0;
    $stats['banners'][$bannerFile]++;
    
    saveStats($stats);
}

function registerGeneration($user) {
    $stats = getStats();
    $today = date('Y-m-d');
    
    if (!isset($stats['generated'][$user])) $stats['generated'][$user] = [];
    if (!isset($stats['generated'][$user][$today])) $stats['generated'][$user][$today] = 0;
    $stats['generated'][$user][$today]++;
    
    saveStats($stats);
}

function getUserStats($user) {
    $stats = getStats();
    $result = [
        'total_downloads' => 0,
        'total_generated' => 0,
        'daily_downloads' => [],
        'daily_generated' => [],
        'weekly_downloads' => [],
        'weekly_generated' => [],
        'monthly_downloads' => [],
        'monthly_generated' => [],
        'top_banners' => []
    ];
    
    // Downloads do usuário
    if (isset($stats['downloads'][$user])) {
        $result['total_downloads'] = array_sum($stats['downloads'][$user]);
        $result['daily_downloads'] = $stats['downloads'][$user];
        
        // Últimos 7 dias
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $result['weekly_downloads'][$date] = $stats['downloads'][$user][$date] ?? 0;
        }
        
        // Últimos 30 dias (mensal)
        for ($i = 29; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $result['monthly_downloads'][$date] = $stats['downloads'][$user][$date] ?? 0;
        }
    }
    
    // Gerações do usuário
    if (isset($stats['generated'][$user])) {
        $result['total_generated'] = array_sum($stats['generated'][$user]);
        $result['daily_generated'] = $stats['generated'][$user];
        
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $result['weekly_generated'][$date] = $stats['generated'][$user][$date] ?? 0;
        }
        
        for ($i = 29; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $result['monthly_generated'][$date] = $stats['generated'][$user][$date] ?? 0;
        }
    }
    
    // Top banners do usuário
    if (isset($stats['banners'])) {
        $userBanners = [];
        foreach ($stats['banners'] as $banner => $count) {
            if (strpos($banner, $user) !== false) {
                $userBanners[$banner] = $count;
            }
        }
        arsort($userBanners);
        $result['top_banners'] = array_slice($userBanners, 0, 10);
    }
    
    return $result;
}

function getRanking() {
    $stats = getStats();
    $ranking = [];
    
    // Calcula total por usuário
    foreach ($stats['downloads'] as $user => $days) {
        $ranking[$user] = [
            'total_downloads' => array_sum($days),
            'total_generated' => isset($stats['generated'][$user]) ? array_sum($stats['generated'][$user]) : 0
        ];
    }
    
    // Ordena por downloads
    uasort($ranking, function($a, $b) {
        return $b['total_downloads'] - $a['total_downloads'];
    });
    
    return $ranking;
}

// ========== FUNÇÕES PIX ==========
function getPixConfig() {
    if (!file_exists(PIX_FILE)) {
        $default = ['config' => []];
        file_put_contents(PIX_FILE, json_encode($default, JSON_PRETTY_PRINT));
    }
    return json_decode(file_get_contents(PIX_FILE), true);
}

function savePixConfig($config) {
    file_put_contents(PIX_FILE, json_encode($config, JSON_PRETTY_PRINT));
}

function getPixForUser($user) {
    $config = getPixConfig();
    return $config['config'][$user] ?? 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);
    
    // Registra geração
    registerGeneration($user);
    
    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
if ($is_reseller && $u) {
    $expiration = checkExpiration($u);
    if ($expiration && $expiration['expired']) {
        session_destroy();
        header('Location: ?page=login&expired=1');
        exit;
    }
}

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;
}

// AÇÕES DE PIX
if ($a == 'savePix' && $is_admin) {
    $config = getPixConfig();
    $config['config'][$_POST['reseller_user']] = [
        'pix_key' => $_POST['pix_key'],
        'pix_name' => $_POST['pix_name'],
        'pix_city' => $_POST['pix_city']
    ];
    savePixConfig($config);
    header('Location: ?page=admin_pix'); exit;
}

if ($a == 'removePix' && $is_admin) {
    $config = getPixConfig();
    unset($config['config'][$_GET['user']]);
    savePixConfig($config);
    header('Location: ?page=admin_pix'); exit;
}

// DOWNLOAD COM ESTATÍSTICA
if ($a == 'downloadBanner' && ($is_admin || $is_reseller)) {
    $file = $_GET['file'];
    if (file_exists($file)) {
        registerDownload($u, basename($file));
        header('Content-Type: image/jpeg');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        readfile($file);
        exit;
    }
}

$logo = null;
if ($is_admin || $is_reseller) {
    $logo = getLogo($u);
}
$expiration = null;
if ($is_reseller && $u) {
    $expiration = checkExpiration($u);
}

// Dados para estatísticas
$userStats = null;
$ranking = null;
if ($is_admin || $is_reseller) {
    $userStats = getUserStats($u);
    if ($is_admin) {
        $ranking = getRanking();
    }
}
?>
<!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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <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 Estatísticas */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-card {
            background: var(--card);
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            border: 1px solid var(--border);
            transition: 0.3s;
        }
        .stat-card:hover {
            border-color: var(--primary);
            transform: translateY(-3px);
        }
        .stat-card .number {
            font-size: 32px;
            font-weight: bold;
            color: var(--primary);
        }
        .stat-card .label {
            color: #8b949e;
            font-size: 14px;
            margin-top: 5px;
        }
        .stat-card .icon {
            font-size: 24px;
            color: var(--primary);
            margin-bottom: 10px;
        }

        .chart-container {
            background: var(--card);
            border-radius: 12px;
            padding: 20px;
            border: 1px solid var(--border);
            margin-bottom: 20px;
        }
        .chart-container canvas {
            max-height: 300px;
        }

        .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;
        }

        /* Ranking */
        .ranking-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 10px 15px;
            background: var(--card);
            border-radius: 8px;
            margin-bottom: 8px;
            border: 1px solid var(--border);
            transition: 0.3s;
        }
        .ranking-item:hover {
            border-color: var(--primary);
        }
        .ranking-item .position {
            font-size: 20px;
            font-weight: bold;
            color: var(--primary);
            min-width: 40px;
        }
        .ranking-item .position.gold { color: #ffd700; }
        .ranking-item .position.silver { color: #c0c0c0; }
        .ranking-item .position.bronze { color: #cd7f32; }
        .ranking-item .info {
            flex: 1;
        }
        .ranking-item .info .name {
            font-weight: bold;
        }
        .ranking-item .info .details {
            color: #8b949e;
            font-size: 12px;
        }
        .ranking-item .stats {
            display: flex;
            gap: 20px;
        }
        .ranking-item .stats span {
            font-size: 14px;
        }
        .ranking-item .stats .num {
            font-weight: bold;
            color: var(--primary);
        }

        /* PIX */
        .pix-box {
            background: var(--card);
            border-radius: 12px;
            padding: 20px;
            border: 1px solid var(--border);
            text-align: center;
            max-width: 400px;
            margin: 20px auto;
        }
        .pix-box .pix-key {
            font-size: 20px;
            font-weight: bold;
            color: var(--primary);
            margin: 10px 0;
        }
        .pix-box .pix-qr {
            max-width: 200px;
            margin: 10px auto;
        }
        .pix-box .pix-qr img {
            width: 100%;
            height: auto;
        }

        @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; }
            .stats-grid { grid-template-columns: 1fr 1fr; }
            table { font-size: 12px; }
            th, td { padding: 8px; }
            .modal-content { padding: 20px; margin: 10px; }
            .btn { font-size: 12px; padding: 8px 12px; }
            .ranking-item { flex-direction: column; align-items: stretch; text-align: center; }
            .ranking-item .stats { justify-content: center; }
        }
        @media (max-width: 480px) {
            .stats-grid { grid-template-columns: 1fr; }
            .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>
            <a href="?page=admin_stats" class="btn" style="color:#fff;"><i class="fas fa-chart-bar"></i> Estatísticas</a>
            <a href="?page=admin_pix" class="btn" style="color:#fff;"><i class="fas fa-qrcode"></i> PIX</a>
        <?php endif; ?>
        <?php if ($is_admin || $is_reseller): ?>
            <a href="?page=galeria" class="btn" style="color:#fff;"><i class="fas fa-images"></i> Banners</a>
            <a href="?page=stats" class="btn" style="color:#fff;"><i class="fas fa-chart-line"></i> Minhas Stats</a>
            <a href="?page=perfil" class="btn" style="color:#fff;"><i class="fas fa-image"></i> 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): ?>
        <h2>Gerenciar Revendas</h2>
        <button onclick="document.getElementById('modalReseller').style.display='flex'" class="btn btn-p" style="margin-bottom:20px;"><i class="fas fa-plus"></i> Nova Revenda</button>

        <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']);
                $stats = getUserStats($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-download"></i> Downloads</div>
                            <div class="value"><?= $stats['total_downloads'] ?? 0 ?></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 class="info-item">
                            <div class="label"><i class="fas fa-star"></i> Ranking</div>
                            <div class="value">#<?= array_search($r['user'], array_keys(getRanking())) + 1 ?></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 == 'admin_stats' && $is_admin): ?>
        <h2><i class="fas fa-chart-bar" style="color:var(--primary);"></i> Estatísticas Gerais</h2>
        
        <!-- Cards de Estatísticas -->
        <div class="stats-grid">
            <?php
            $totalResellers = count(getResellers());
            $totalBanners = count(glob("banners/*.jpg")) + count(glob("resellers_banners/*/*.jpg"));
            $totalDownloads = array_sum(array_map('array_sum', getStats()['downloads'] ?? []));
            $totalGenerated = array_sum(array_map('array_sum', getStats()['generated'] ?? []));
            ?>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-users"></i></div>
                <div class="number"><?= $totalResellers ?></div>
                <div class="label">Total de Revendas</div>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-images"></i></div>
                <div class="number"><?= $totalBanners ?></div>
                <div class="label">Total de Banners</div>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-download"></i></div>
                <div class="number"><?= $totalDownloads ?></div>
                <div class="label">Total de Downloads</div>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-magic"></i></div>
                <div class="number"><?= $totalGenerated ?></div>
                <div class="label">Total Gerado</div>
            </div>
        </div>

        <!-- Gráficos -->
        <div style="display:grid; grid-template-columns: 1fr 1fr; gap:20px;">
            <div class="chart-container">
                <h3>Downloads por Dia (Últimos 7 dias)</h3>
                <canvas id="adminWeeklyDownloadsChart"></canvas>
            </div>
            <div class="chart-container">
                <h3>Gerações por Dia (Últimos 7 dias)</h3>
                <canvas id="adminWeeklyGeneratedChart"></canvas>
            </div>
        </div>

        <!-- Ranking de Revendas -->
        <div class="chart-container">
            <h3><i class="fas fa-trophy" style="color:var(--warning);"></i> Ranking de Revendas</h3>
            <?php 
            $ranking = getRanking();
            $position = 1;
            foreach ($ranking as $user => $data): 
                $resellers = getResellers();
                $name = $user;
                foreach ($resellers as $r) {
                    if ($r['user'] == $user) {
                        $name = $r['name'];
                        break;
                    }
                }
                $posClass = '';
                if ($position == 1) $posClass = 'gold';
                elseif ($position == 2) $posClass = 'silver';
                elseif ($position == 3) $posClass = 'bronze';
            ?>
                <div class="ranking-item">
                    <div class="position <?= $posClass ?>">#<?= $position++ ?></div>
                    <div class="info">
                        <div class="name"><?= htmlspecialchars($name) ?></div>
                        <div class="details">@<?= htmlspecialchars($user) ?></div>
                    </div>
                    <div class="stats">
                        <span><i class="fas fa-download"></i> <span class="num"><?= $data['total_downloads'] ?></span></span>
                        <span><i class="fas fa-magic"></i> <span class="num"><?= $data['total_generated'] ?></span></span>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

    <?php elseif ($p == 'admin_pix' && $is_admin): ?>
        <h2><i class="fas fa-qrcode" style="color:var(--primary);"></i> Configuração de PIX por Revenda</h2>
        <p style="color:#8b949e;">Configure qual PIX cada revenda verá no painel.</p>

        <div style="display:grid; gap:20px;">
            <?php foreach(getResellers() as $r): 
                $pixConfig = getPixForUser($r['user']);
            ?>
                <div style="background:var(--card); border-radius:12px; padding:20px; border:1px solid var(--border);">
                    <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px;">
                        <div>
                            <strong style="font-size:18px;"><?= htmlspecialchars($r['name']) ?></strong>
                            <span style="color:#8b949e; margin-left:10px;">@<?= htmlspecialchars($r['user']) ?></span>
                        </div>
                        <?php if ($pixConfig): ?>
                            <span style="background:var(--success); color:#fff; padding:4px 12px; border-radius:12px; font-size:12px;">
                                <i class="fas fa-check"></i> Configurado
                            </span>
                        <?php else: ?>
                            <span style="background:#8b949e; color:#fff; padding:4px 12px; border-radius:12px; font-size:12px;">
                                <i class="fas fa-times"></i> Sem PIX
                            </span>
                        <?php endif; ?>
                    </div>

                    <?php if ($pixConfig): ?>
                        <div style="margin-top:10px; padding:10px; background:#000; border-radius:8px;">
                            <p><strong>Chave PIX:</strong> <?= htmlspecialchars($pixConfig['pix_key']) ?></p>
                            <p><strong>Nome:</strong> <?= htmlspecialchars($pixConfig['pix_name']) ?></p>
                            <p><strong>Cidade:</strong> <?= htmlspecialchars($pixConfig['pix_city']) ?></p>
                            <a href="?action=removePix&user=<?= $r['user'] ?>" class="btn btn-danger" style="padding:5px 12px; font-size:12px;" onclick="return confirm('Remover PIX desta revenda?')">
                                <i class="fas fa-trash"></i> Remover
                            </a>
                        </div>
                    <?php else: ?>
                        <form action="?action=savePix" method="POST" style="margin-top:10px; display:grid; grid-template-columns: 1fr 1fr; gap:10px;">
                            <input type="hidden" name="reseller_user" value="<?= $r['user'] ?>">
                            <input type="text" name="pix_key" placeholder="Chave PIX (email, CPF, telefone)" required style="grid-column: span 2;">
                            <input type="text" name="pix_name" placeholder="Nome do titular" required>
                            <input type="text" name="pix_city" placeholder="Cidade" required>
                            <button type="submit" class="btn btn-p" style="grid-column: span 2;"><i class="fas fa-save"></i> Salvar PIX</button>
                        </form>
                    <?php endif; ?>
                </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="?action=downloadBanner&file=<?= $f ?>" 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 == 'stats' && ($is_admin || $is_reseller)): ?>
        <h2><i class="fas fa-chart-line" style="color:var(--primary);"></i> Minhas Estatísticas</h2>

        <!-- Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="icon"><i class="fas fa-magic"></i></div>
                <div class="number"><?= $userStats['total_generated'] ?? 0 ?></div>
                <div class="label">Total de Banners Gerados</div>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-download"></i></div>
                <div class="number"><?= $userStats['total_downloads'] ?? 0 ?></div>
                <div class="label">Total de Downloads</div>
            </div>
        </div>

        <!-- Gráficos -->
        <div style="display:grid; grid-template-columns: 1fr 1fr; gap:20px;">
            <div class="chart-container">
                <h3>Downloads (Últimos 7 dias)</h3>
                <canvas id="weeklyDownloadsChart"></canvas>
            </div>
            <div class="chart-container">
                <h3>Gerações (Últimos 7 dias)</h3>
                <canvas id="weeklyGeneratedChart"></canvas>
            </div>
        </div>

        <!-- Top Banners -->
        <?php if (!empty($userStats['top_banners'])): ?>
            <div class="chart-container">
                <h3><i class="fas fa-crown" style="color:var(--warning);"></i> Banners Mais Baixados</h3>
                <?php foreach ($userStats['top_banners'] as $banner => $count): ?>
                    <div class="ranking-item">
                        <div class="info">
                            <div class="name"><?= basename($banner) ?></div>
                        </div>
                        <div class="stats">
                            <span><i class="fas fa-download"></i> <span class="num"><?= $count ?></span> downloads</span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <!-- PIX da Revenda -->
        <?php 
        $pix = getPixForUser($u);
        if ($pix): 
        ?>
            <div class="chart-container" style="border-color:var(--success);">
                <h3><i class="fas fa-qrcode" style="color:var(--success);"></i> PIX para Pagamento</h3>
                <div class="pix-box">
                    <p style="color:#8b949e;">Use a chave abaixo para realizar o pagamento</p>
                    <div class="pix-key"><?= htmlspecialchars($pix['pix_key']) ?></div>
                    <p style="color:#8b949e; font-size:14px;">
                        <?= htmlspecialchars($pix['pix_name']) ?> - <?= htmlspecialchars($pix['pix_city']) ?>
                    </p>
                    <p style="color:#8b949e; font-size:12px; margin-top:10px;">
                        <i class="fas fa-info-circle"></i> Entre em contato com o administrador para confirmar o pagamento
                    </p>
                </div>
            </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>

<!-- Modais -->
<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>

<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>

<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';
    }
};

// GRÁFICOS
<?php if ($is_admin && $p == 'admin_stats'): ?>
// Gráficos Admin
const ctx1 = document.getElementById('adminWeeklyDownloadsChart').getContext('2d');
const ctx2 = document.getElementById('adminWeeklyGeneratedChart').getContext('2d');

// Coleta dados de todos os usuários
let adminWeeklyDownloads = {};
let adminWeeklyGenerated = {};
<?php
$allStats = getStats();
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $adminWeeklyDownloads[$date] = 0;
    $adminWeeklyGenerated[$date] = 0;
    foreach ($allStats['downloads'] as $user => $days) {
        $adminWeeklyDownloads[$date] += $days[$date] ?? 0;
    }
    foreach ($allStats['generated'] as $user => $days) {
        $adminWeeklyGenerated[$date] += $days[$date] ?? 0;
    }
}
?>

new Chart(ctx1, {
    type: 'bar',
    data: {
        labels: <?= json_encode(array_keys($adminWeeklyDownloads)) ?>,
        datasets: [{
            label: 'Downloads',
            data: <?= json_encode(array_values($adminWeeklyDownloads)) ?>,
            backgroundColor: 'rgba(88, 166, 255, 0.5)',
            borderColor: 'rgba(88, 166, 255, 1)',
            borderWidth: 2
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { labels: { color: '#e6edf3' } }
        },
        scales: {
            x: { ticks: { color: '#8b949e' } },
            y: { ticks: { color: '#8b949e', stepSize: 1 } }
        }
    }
});

new Chart(ctx2, {
    type: 'bar',
    data: {
        labels: <?= json_encode(array_keys($adminWeeklyGenerated)) ?>,
        datasets: [{
            label: 'Gerações',
            data: <?= json_encode(array_values($adminWeeklyGenerated)) ?>,
            backgroundColor: 'rgba(46, 160, 67, 0.5)',
            borderColor: 'rgba(46, 160, 67, 1)',
            borderWidth: 2
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { labels: { color: '#e6edf3' } }
        },
        scales: {
            x: { ticks: { color: '#8b949e' } },
            y: { ticks: { color: '#8b949e', stepSize: 1 } }
        }
    }
});
<?php endif; ?>

<?php if (($is_admin || $is_reseller) && $p == 'stats'): ?>
// Gráficos do Usuário
const ctx3 = document.getElementById('weeklyDownloadsChart').getContext('2d');
const ctx4 = document.getElementById('weeklyGeneratedChart').getContext('2d');

const weeklyDownloads = <?= json_encode($userStats['weekly_downloads'] ?? []) ?>;
const weeklyGenerated = <?= json_encode($userStats['weekly_generated'] ?? []) ?>;

new Chart(ctx3, {
    type: 'bar',
    data: {
        labels: Object.keys(weeklyDownloads),
        datasets: [{
            label: 'Downloads',
            data: Object.values(weeklyDownloads),
            backgroundColor: 'rgba(88, 166, 255, 0.5)',
            borderColor: 'rgba(88, 166, 255, 1)',
            borderWidth: 2
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { labels: { color: '#e6edf3' } }
        },
        scales: {
            x: { ticks: { color: '#8b949e' } },
            y: { ticks: { color: '#8b949e', stepSize: 1 } }
        }
    }
});

new Chart(ctx4, {
    type: 'bar',
    data: {
        labels: Object.keys(weeklyGenerated),
        datasets: [{
            label: 'Gerações',
            data: Object.values(weeklyGenerated),
            backgroundColor: 'rgba(46, 160, 67, 0.5)',
            borderColor: 'rgba(46, 160, 67, 1)',
            borderWidth: 2
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { labels: { color: '#e6edf3' } }
        },
        scales: {
            x: { ticks: { color: '#8b949e' } },
            y: { ticks: { color: '#8b949e', stepSize: 1 } }
        }
    }
});
<?php endif; ?>
</script>
</body>
</html>