<?php
session_start();
require_once 'config.php';

$pdo = getConexaoInterna();

// --- PROTEÇÃO GERAL (Admin e Revenda) ---
if (!isset($_SESSION['user_id'])) {
    die("Acesso negado. Por favor, faça login no painel.");
}

$id_usuario = $_SESSION['user_id'];
$nome_usuario = $_SESSION['username'] ?? 'Usuário';
$role = $_SESSION['user_role'] ?? 'revenda';
$is_admin = ($role === 'admin'); 

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';

try {
    $tabela_existe = $pdo->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($config_painel) {
            $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
            $logo_url = !empty($config_painel['logo_url']) ? $config_painel['logo_url'] : $logo_url;
            $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
        }
    }
} catch (Exception $e) { }

// Busca saldo
try {
    $pdo_ext = getConexaoAtiva();
    $user_credits = $pdo_ext->query("SELECT credits FROM reg_users WHERE id = " . intval($id_usuario))->fetchColumn() ?: 0;
} catch (Exception $e) { $user_credits = 0; }

// =========================================================================
// BANCO DE DADOS: TABELA DE PLAYERS E TABELA DE LIMITES
// =========================================================================
try {
    // Tabela dos Players
    $pdo->exec("CREATE TABLE IF NOT EXISTS `revenda_players` (
        `id` int(11) AUTO_INCREMENT PRIMARY KEY,
        `member_id` int(11) NOT NULL,
        `slug` varchar(50) NOT NULL UNIQUE,
        `nome_marca` varchar(100) DEFAULT 'Meu Player',
        `logo_url` varchar(255) DEFAULT '',
        `cor_fundo` varchar(20) DEFAULT '#121519',
        `cor_botao` varchar(20) DEFAULT '#007bff',
        `data_criacao` timestamp DEFAULT CURRENT_TIMESTAMP
    )");
    
    // Tabela de Limites por Revenda
    $pdo->exec("CREATE TABLE IF NOT EXISTS `revenda_limites` (
        `member_id` int(11) PRIMARY KEY,
        `limite_players` int(11) DEFAULT 1
    )");
} catch (Exception $e) {}

$protocolo = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
$dominio = $_SERVER['HTTP_HOST'];
$base_path = rtrim(dirname($_SERVER['PHP_SELF']), '/');

$mensagem_alerta = "";

// --- AÇÃO: ATUALIZAR LIMITE DA REVENDA (SÓ ADMIN) ---
if ($is_admin && $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action_update_limit'])) {
    $m_id = intval($_POST['limit_member_id']);
    $new_limit = intval($_POST['new_limit']);
    try {
        $stmtLimit = $pdo->prepare("INSERT INTO revenda_limites (member_id, limite_players) VALUES (?, ?) ON DUPLICATE KEY UPDATE limite_players = ?");
        $stmtLimit->execute([$m_id, $new_limit, $new_limit]);
        $mensagem_alerta = "<div class='alert success'><i class='fas fa-check-circle'></i> Limite atualizado com sucesso!</div>";
    } catch (Exception $e) {
        $mensagem_alerta = "<div class='alert danger'><i class='fas fa-exclamation-triangle'></i> Erro ao atualizar limite.</div>";
    }
}

// --- BUSCA O LIMITE E A QUANTIDADE ATUAL DA REVENDA ---
$limite_atual = 1; // Padrão é 1
$total_criados = 0;

if (!$is_admin) {
    // Quantos ele pode criar
    $stmtLim = $pdo->prepare("SELECT limite_players FROM revenda_limites WHERE member_id = ?");
    $stmtLim->execute([$id_usuario]);
    $resLim = $stmtLim->fetch(PDO::FETCH_ASSOC);
    if ($resLim) { $limite_atual = $resLim['limite_players']; }
    
    // Quantos ele já criou
    $stmtCount = $pdo->prepare("SELECT COUNT(*) FROM revenda_players WHERE member_id = ?");
    $stmtCount->execute([$id_usuario]);
    $total_criados = $stmtCount->fetchColumn();
}

$atingiu_limite = (!$is_admin && $total_criados >= $limite_atual);


// --- AÇÃO: SALVAR OU EDITAR PLAYER ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action_save_player'])) {
    $id_player = $_POST['player_id'] ?? '';
    
    $member_id_save = $is_admin ? intval($_POST['member_id']) : $id_usuario;
    $nome_marca = trim($_POST['nome_marca']);
    $cor_fundo = trim($_POST['cor_fundo']);
    $cor_botao = trim($_POST['cor_botao']);
    
    $logo_final = trim($_POST['logo_url_texto']);
    
    if (isset($_FILES['logo_file']) && $_FILES['logo_file']['error'] === UPLOAD_ERR_OK) {
        $pasta_upload = 'uploads_logos/';
        if (!is_dir($pasta_upload)) { mkdir($pasta_upload, 0755, true); }
        
        $extensao = strtolower(pathinfo($_FILES['logo_file']['name'], PATHINFO_EXTENSION));
        $extensoes_permitidas = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (in_array($extensao, $extensoes_permitidas)) {
            $novo_nome = 'logo_' . uniqid() . '.' . $extensao;
            $caminho_completo = $pasta_upload . $novo_nome;
            
            if (move_uploaded_file($_FILES['logo_file']['tmp_name'], $caminho_completo)) {
                $logo_final = $protocolo . $dominio . $base_path . '/' . $caminho_completo;
            } else {
                $mensagem_alerta = "<div class='alert danger'>Erro ao salvar a imagem no servidor.</div>";
            }
        } else {
            $mensagem_alerta = "<div class='alert danger'>Formato não permitido. Use PNG, JPG ou WEBP.</div>";
        }
    }

    if (empty($mensagem_alerta)) {
        try {
            if (!empty($id_player)) {
                // MODO EDIÇÃO
                if (!$is_admin) {
                    $check_dono = $pdo->prepare("SELECT id FROM revenda_players WHERE id = ? AND member_id = ?");
                    $check_dono->execute([$id_player, $id_usuario]);
                    if (!$check_dono->fetch()) { die("Erro: Você não tem permissão para editar este player."); }
                }
                $stmt = $pdo->prepare("UPDATE revenda_players SET member_id = ?, nome_marca = ?, logo_url = ?, cor_fundo = ?, cor_botao = ? WHERE id = ?");
                $stmt->execute([$member_id_save, $nome_marca, $logo_final, $cor_fundo, $cor_botao, $id_player]);
                $mensagem_alerta = "<div class='alert success'><i class='fas fa-check-circle'></i> Player atualizado com sucesso!</div>";
            } else {
                // MODO CRIAÇÃO (VERIFICA O LIMITE AQUI)
                if ($atingiu_limite) {
                    throw new Exception("Você atingiu o limite de {$limite_atual} Web Player(s). Contate o Administrador.");
                }

                $slug = bin2hex(random_bytes(6)); 
                $check = $pdo->prepare("SELECT id FROM revenda_players WHERE slug = ?");
                $check->execute([$slug]);
                if($check->fetch()) { $slug = bin2hex(random_bytes(8)); }

                $stmt = $pdo->prepare("INSERT INTO revenda_players (member_id, slug, nome_marca, logo_url, cor_fundo, cor_botao) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$member_id_save, $slug, $nome_marca, $logo_final, $cor_fundo, $cor_botao]);
                $mensagem_alerta = "<div class='alert success'><i class='fas fa-check-circle'></i> Novo Player criado! Já pode copiar o link anônimo.</div>";
                
                // Atualiza a contagem da revenda na tela
                if(!$is_admin) { $total_criados++; $atingiu_limite = ($total_criados >= $limite_atual); }
            }
        } catch (Exception $e) {
            $mensagem_alerta = "<div class='alert danger'><i class='fas fa-exclamation-triangle'></i> Erro: " . $e->getMessage() . "</div>";
        }
    }
}

// AÇÃO: EXCLUIR PLAYER
if (isset($_GET['delete'])) {
    $id_del = intval($_GET['delete']);
    if ($is_admin) {
        $pdo->prepare("DELETE FROM revenda_players WHERE id = ?")->execute([$id_del]);
    } else {
        $pdo->prepare("DELETE FROM revenda_players WHERE id = ? AND member_id = ?")->execute([$id_del, $id_usuario]);
    }
    header("Location: admin_player_revenda.php");
    exit;
}

// BUSCA LISTA DE REVENDEDORES E CRIA O MAPA DE NOMES
$revendedores = [];
$mapa_nomes = [];
$mapa_limites = [];
if ($is_admin) {
    try {
        $revendedores = $pdo_ext->query("SELECT id, username FROM reg_users WHERE member_group_id != 1 ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC);
        $todos = $pdo_ext->query("SELECT id, username FROM reg_users")->fetchAll(PDO::FETCH_ASSOC);
        foreach($todos as $t) { $mapa_nomes[$t['id']] = $t['username']; }
        
        $limites_db = $pdo->query("SELECT member_id, limite_players FROM revenda_limites")->fetchAll(PDO::FETCH_ASSOC);
        foreach($limites_db as $ld) { $mapa_limites[$ld['member_id']] = $ld['limite_players']; }
    } catch(Exception $e){}
}

// BUSCA OS PLAYERS CRIADOS
if ($is_admin) {
    $players = $pdo->query("SELECT * FROM revenda_players ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
} else {
    $stmtPlay = $pdo->prepare("SELECT * FROM revenda_players WHERE member_id = ? ORDER BY id DESC");
    $stmtPlay->execute([$id_usuario]);
    $players = $stmtPlay->fetchAll(PDO::FETCH_ASSOC);
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Web Player White Label - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --bg-dark: #121519; --bg-sidebar: #1e2227; --bg-card: #272c33; --text-main: #d1d5da; --text-muted: #8a94a1; --accent: <?php echo $cor_primaria; ?>; --border-color: #3a4149; --success: #28a745; --danger: #dc3545; --warning: #f39c12; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        
        .sidebar { width: 260px; background-color: var(--bg-sidebar); display: flex; flex-direction: column; transition: 0.3s; border-right: 1px solid var(--border-color); z-index: 1001; flex-shrink: 0; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .sidebar-logo { max-width: 180px; max-height: 55px; object-fit: contain; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(255, 255, 255, 0.05); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; padding-bottom: 20px;}
        .menu-list::-webkit-scrollbar { width: 6px; }
        .menu-list::-webkit-scrollbar-thumb { background: #3a4149; border-radius: 3px; }

        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; border-left: 3px solid transparent; font-size: 14px; cursor: pointer; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background-color: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i:first-child { color: var(--accent); }
        .menu-category { padding: 20px 20px 5px; font-size: 11px; font-weight: bold; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px;}
        .logout-btn { padding: 15px; background-color: var(--danger); color: white; text-align: center; text-decoration: none; font-weight: bold; }

        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 13px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: transform 0.3s ease; font-size: 11px; }
        
        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; position: relative; }
        .topbar { display: flex; justify-content: flex-start; align-items: center; padding: 15px 25px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); gap: 15px;}
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 22px; cursor: pointer; padding: 5px; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }
        
        .content-area { padding: 30px; flex: 1; max-width: 1200px; margin: 0 auto; width: 100%; box-sizing: border-box; }
        .card { background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-color); padding: 25px; margin-bottom: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .card h3 { margin-top: 0; color: white; border-bottom: 1px solid var(--border-color); padding-bottom: 15px; display: flex; align-items: center; gap: 10px;}
        
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 8px; font-size: 13px; font-weight: bold; color: var(--text-muted); }
        
        input[type="text"], input[type="number"], input[type="color"], select { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 8px; box-sizing: border-box; font-size: 14px;}
        
        input[type="file"] { width: 100%; padding: 9px; background: #121519; border: 1px dashed var(--border-color); color: white; border-radius: 8px; box-sizing: border-box; font-size: 13px; cursor: pointer; }
        input[type="file"]::file-selector-button { background: var(--border-color); color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer; font-weight: bold; margin-right: 15px; transition: 0.2s;}
        input[type="file"]::file-selector-button:hover { background: #4a525b; }
        
        input[type="text"]:focus, input[type="number"]:focus, select:focus { border-color: var(--accent); outline: none; }
        input[type="color"] { padding: 5px; height: 45px; cursor: pointer; }
        
        .btn-save { background: var(--accent); color: white; border: none; padding: 15px; border-radius: 8px; cursor: pointer; font-weight: bold; width: 100%; margin-top: 10px; font-size: 15px; transition: 0.2s;}
        .btn-save:hover { filter: brightness(1.1); box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .btn-save:disabled { background: #444 !important; cursor: not-allowed !important; color: #888 !important; box-shadow: none !important; }
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; display: flex; align-items: center; gap: 10px;}
        .alert.success { background: rgba(40, 167, 69, 0.15); border: 1px solid var(--success); color: var(--success); }
        .alert.danger { background: rgba(220, 53, 69, 0.15); border: 1px solid var(--danger); color: var(--danger); }
        .alert.warning { background: rgba(243, 156, 18, 0.15); border: 1px solid var(--warning); color: var(--warning); }
        
        .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }

        .table-responsive { overflow-x: auto; width: 100%; }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; font-size: 13px; min-width: 800px;}
        th, td { text-align: left; padding: 15px; border-bottom: 1px solid var(--border-color); }
        th { color: var(--text-muted); text-transform: uppercase; font-size: 11px; font-weight: bold; background: #16191d;}
        td { color: var(--text-main); vertical-align: middle; }
        
        .btn-action { background: #3a4149; color: white; border: none; padding: 8px 12px; border-radius: 6px; cursor: pointer; font-weight: bold; transition: 0.2s; display: inline-flex; align-items: center; gap: 5px; text-decoration: none; font-size: 12px;}
        .btn-action:hover { filter: brightness(1.2); }
        .btn-copy { background: #28a745; }
        .btn-delete { background: #dc3545; }

        .player-logo-preview { max-width: 100px; max-height: 40px; object-fit: contain; background: rgba(0,0,0,0.5); padding: 5px; border-radius: 4px; border: 1px dashed var(--border-color);}
        .color-dot { display: inline-block; width: 15px; height: 15px; border-radius: 50%; border: 1px solid white; vertical-align: middle; margin-right: 5px;}

        @media (max-width: 768px) {
            .menu-toggle { display: block; }
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .sidebar.active { left: 0; }
            .sidebar-overlay.active { display: block; }
            .content-area { padding: 15px; }
            .grid-2 { grid-template-columns: 1fr; gap: 0;}
        }
    </style>
</head>
<body>
    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>
    
    <nav class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <?php if(!empty($logo_url) && file_exists($logo_url)): ?>
                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="sidebar-logo">
            <?php else: ?>
                <?php echo htmlspecialchars($nome_painel); ?>
            <?php endif; ?>
        </div>
        <div class="user-info">
            <div style="color:white; font-size: 14px;">Olá, <strong><?php echo htmlspecialchars($nome_usuario); ?></strong></div>
            <span class="badge"><?php echo $is_admin ? 'Administrador' : 'Revendedor'; ?></span>
            <div class="credits-badge"><i class="fas fa-coins"></i> Saldo: <?php echo number_format($user_credits, 1); ?></div>
        </div>
        
        <div class="menu-list">
            <a href="dashboard.php" class="menu-item active"><i class="fas fa-chart-line"></i> Dashboard</a>
            <a href="perfil.php" class="menu-item active"><i class="fas fa-user-circle"></i> Meu Perfil</a>
            
            <a href="lancamentos.php" class="menu-item active"><i class="fas fa-fire"></i> Últimos Adicionados</a>
            
            <a href="ajuda.php" class="menu-item active"><i class="fas fa-question-circle"></i> Material de Ajuda</a>
            <a href="meus_links.php" class="menu-item active"><i class="fas fa-link" style="color: var(--accent);"></i> Central de Links</a>
            
            <div class="menu-category">Gestão</div>
            <a href="clientes.php" class="menu-item active"><i class="fas fa-users"></i> Clientes IPTV</a>
            <a href="testes.php" class="menu-item active"><i class="fas fa-vial"></i> Gerenciar Testes</a>
            <a href="online.php" class="menu-item active"><i class="fas fa-plug"></i> Clientes Online</a>
            <a href="revendedores.php" class="menu-item active"><i class="fas fa-user-tie"></i> Revendedores</a>
            <a href="migrar_clientes.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Migrar Clientes</a>
            <a href="logs_creditos.php" class="menu-item active"><i class="fas fa-list-alt"></i> Extrato de Créditos</a>
            <a href="marketing.php" class="menu-item active"><i class="fas fa-bullhorn"></i> Central de Marketing</a>
            
            
            <div class="menu-category">Clientes P2P</div>
            <a href="p2p_clientes.php" class="menu-item active"><i class="fas fa-tv"></i> Clientes P2P</a>
            
            <?php if (!empty($api_conf['api_binstream_url'])): ?>
                <a href="binstream_p2p.php" class="menu-item active"><i class="fas fa-tv"></i> Binstream P2P</a>
            <?php endif; ?>

 <?php if($role === 'admin'): ?>
<div class="menu-category">Gerar Licença</div>
<a href="admin_licencas.php" class="menu-item active"> <i class="fas fa-key" style="color: #28a745;"></i> <span>Gerador SaaS</span> </a>
<?php endif; ?>

<div class="menu-category">Api WhatsApp</div>
                <a href="integracoes_api_whatsapp.php" class="menu-item active"><i class="fas fa-plug"></i> Integrações API WhatsApp</a>


            <div class="menu-category">Integração & Cobrança</div>
            <a href="pagamentos.php" class="menu-item active"><i class="fas fa-dollar-sign"></i> Pagamento Automático</a>
            <a href="cobranca.php" class="menu-item active"><i class="fas fa-comment-dollar"></i> Central de Cobrança</a>
            <a href="admin_planos.php" class="menu-item active"><i class="fas fa-tags"></i> Meus Planos de Venda</a>
            <a href="comprar_creditos.php" class="menu-item active"><i class="fas fa-shopping-cart"></i> Comprar Créditos</a>
          
            <div class="menu-item active" onclick="toggleSubmenu('appsSub')">
                <i class="fas fa-rocket"></i><span>Aplicações</span><i class="fas fa-chevron-down arrow-icon" id="arrow-appsSub"></i>

            </div>
            <div class="submenu" id="appsSub">
                <a href="loja_apps.php" class="menu-item active"><i class="fas fa-store"></i> Loja de Aplicativos</a>
                <?php if($role === 'admin'): ?>
                    <a href="admin_loja.php" class="menu-item active"><i class="fas fa-cogs"></i> Gerenciar Loja</a>
                <?php endif; ?>
                <a href="chatbot.php" class="menu-item active"><i class="fab fa-whatsapp"></i> Chatbot Automático</a>
            </div>
           <a href="admin_player_revenda.php" class="menu-item active"><i class="fas fa-play-circle"></i> WebPlayer</a>
            
   <div class="menu-category">Segurança</div>
            <a href="historico_logins.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sessões Ativas</a>

            <?php if($role === 'admin'): ?>
                <div class="menu-category">Administração</div>
                <a href="admin_monitor.php" class="menu-item active"><i class="fas fa-heartbeat"></i> Monitor do Servidor</a>
                <a href="admin_template.php" class="menu-item active"><i class="fas fa-edit"></i> Editor de Template</a>
                <a href="admin_token.php" class="menu-item active"><i class="fas fa-user-secret"></i> Token Links Xui</a>
                <a href="admin_lb.php" class="menu-item active"><i class="fas fa-server"></i> Load Balancers</a>
                <a href="guia_cloudflare.php" class="menu-item active"><i class="fas fa-cloud"></i> Guia Cloudflare</a>
                 <a href="admin_loja_creditos.php" class="menu-item active"><i class="fas fa-store"></i> Configurar Loja (PIX)</a>
                 <a href="integracoes_api.php" class="menu-item active"><i class="fas fa-plug"></i> Integrações API</a>
                 <a href="admin_robo.php" class="menu-item active"><i class="fas fa-robot"></i> Robô de Cobrança</a>
                 <a href="admin_anti_bloqueio.php" class="menu-item active"><i class="fas fa-bolt"></i> Botão de Pânico</a>
                 <a href="admin_anti_fraude.php" class="menu-item active"><i class="fas fa-user-secret"></i> Radar Anti-Fraude</a>  
                 <a href="admin_watchdog.php" class="menu-item active"><i class="fas fa-dog"></i> Watchdog LB</a>  
                 
                 <a href="admin_epg_sync.php" class="menu-item active">
        <i class="fas fa-clock"></i> Sincronizar EPG
    </a>
    

 <div class="menu-item active" onclick="toggleSubmenu('painelSub')">
                    <i class="fas fa-desktop"></i><span>Painel</span><i class="fas fa-chevron-down arrow-icon" id="arrow-painelSub"></i>
                </div>
                <div class="submenu" id="painelSub">
                    <a href="personalizacao.php" class="menu-item active"><i class="fas fa-paint-brush"></i> Personalização</a>
                </div>
             
                <div class="menu-item active" onclick="toggleSubmenu('adminSub')">
                    <i class="fas fa-toolbox"></i><span>Ferramentas</span><i class="fas fa-chevron-down arrow-icon" id="arrow-adminSub"></i>
                </div>
                <div class="submenu" id="adminSub">
                    <a href="importar.php" class="menu-item active"><i class="fas fa-file-import"></i> Importador</a>
                    <a href="importar3.php" class="menu-item active"><i class="fas fa-file-import"></i> Importador Turbo</a>
                    <a href="dns_manager.php" class="menu-item active"><i class="fas fa-link"></i> Alterar DNS</a>
                    <a href="admin_logos.php" class="menu-item active"><i class="fas fa-image"></i> Alterar Logos</a>
                    <a href="mover_conteudos.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Mover Conteúdos</a>
                    <a href="limpeza.php" class="menu-item active"><i class="fas fa-trash-alt"></i> Limpeza de Dados</a>
                    <a href="limpar_duplicados.php" class="menu-item active"><i class="fas fa-copy"></i> Limpeza de Duplicados</a>
                    <a href="backup.php" class="menu-item active"><i class="fas fa-database"></i> Backup do Sistema</a>
                    <a href="seguranca.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sistema de Segurança</a>
                    <a href="configuracoes.php" class="menu-item active"><i class="fas fa-tools"></i> Configurações</a>
                </div>

                 <?php if($role === 'admin'): ?>
    <div class="menu-category">Financeiro</div>
     <!-- NOVO MENU FINANCEIRO COM SUBMENU -->
            <div class="menu-item active" onclick="toggleSubmenu('finSub')">
                <i class="fas fa-hand-holding-usd"></i><span>Financeiro</span><i class="fas fa-chevron-down arrow-icon rotate" id="arrow-finSub"></i>
            </div>
            <div class="submenu" id="finSub" style="display: block;">
                <a href="financeiro.php" class="menu-item active">Faturamento</a>
            </div>
    
    <?php endif; ?>

                <div class="menu-category">Conteúdos</div>
                <a href="categorias.php" class="menu-item active"><i class="fas fa-folder-open"></i><span>Categorias</span></a>
                <div class="menu-item active" onclick="toggleSubmenu('contentSub')">
                    <i class="fas fa-layer-group"></i><span>Mídias</span><i class="fas fa-chevron-down arrow-icon" id="arrow-contentSub"></i>
                </div>
                <div class="submenu" id="contentSub">
                    <a href="bouquets.php" class="menu-item active">Editar Bouquets</a>
                    <a href="canais.php" class="menu-item active">Canais Ao Vivo</a>
                    <a href="filmes.php" class="menu-item active">Filmes (VOD)</a>
                    <a href="series.php" class="menu-item active">Séries</a>
                </div>
                 <a href="admin_autofix_vod.php" class="menu-item active"><i class="fas fa-magic"></i> Auto-Fix TMDB</a>
            <?php endif; ?>
        </div>
        <a href="logout.php" class="logout-btn"><i class="fas fa-power-off"></i> Sair</a>
    </nav>

    <div class="main-content">
        <header class="topbar">
            <div style="display:flex; align-items:center;">
                <button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; font-size: 18px; color:white;"><i class="fas fa-play-circle" style="color:var(--accent);"></i> Gerador de Web Player</h2>
            </div>
        </header>

        <div class="content-area">
            <?php echo $mensagem_alerta; ?>

            <?php if ($is_admin): ?>
            <div class="card" style="border-top: 4px solid var(--warning);">
                <h3><i class="fas fa-sliders-h" style="color: var(--warning);"></i> Limites de Revendedores</h3>
                <p style="font-size: 12px; color: var(--text-muted); margin-top:-5px; margin-bottom: 15px;">Aumente o limite de Web Players que uma revenda específica pode criar (O padrão é 1 para todos).</p>
                <form method="POST">
                    <input type="hidden" name="action_update_limit" value="1">
                    <div class="grid-2">
                        <div class="form-group">
                            <label>Selecione a Revenda</label>
                            <select name="limit_member_id" id="sel_limite_revenda" required onchange="atualizarCampoLimite()">
                                <option value="" disabled selected>Escolha um revendedor...</option>
                                <?php foreach($revendedores as $r): 
                                    $limitAtual = $mapa_limites[$r['id']] ?? 1;
                                ?>
                                    <option value="<?php echo $r['id']; ?>" data-limit="<?php echo $limitAtual; ?>"><?php echo htmlspecialchars($r['username']); ?> (Atual: <?php echo $limitAtual; ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Quantidade Permitida</label>
                            <input type="number" name="new_limit" id="val_new_limit" min="1" value="1" required>
                        </div>
                    </div>
                    <button type="submit" class="btn-save" style="background: #28a745; width: auto;"><i class="fas fa-check"></i> ATUALIZAR LIMITE</button>
                </form>
            </div>
            <?php endif; ?>

            <div class="card" style="border-top: 4px solid var(--accent);">
                <h3 id="formTitle"><i class="fas fa-magic" style="color:var(--accent);"></i> <?php echo $is_admin ? 'Gerar Player para Revenda' : 'Configurar Meu Player'; ?></h3>
                
                <?php if (!$is_admin): ?>
                    <p style="font-size: 13px; color: var(--text-muted);">Você possui <strong><?php echo $total_criados; ?></strong> de <strong><?php echo $limite_atual; ?></strong> player(s) criados.</p>
                <?php endif; ?>
                
                <form method="POST" id="formPlayer" enctype="multipart/form-data">
                    <input type="hidden" name="action_save_player" value="1">
                    <input type="hidden" name="player_id" id="f_player_id" value="">
                    
                    <div class="grid-2">
                        <?php if($is_admin): ?>
                            <div class="form-group">
                                <label>Dono do Player (Revendedor)</label>
                                <select name="member_id" id="f_member_id" required>
                                    <option value="<?php echo $id_usuario; ?>">Eu mesmo (Painel Oficial)</option>
                                    <?php foreach($revendedores as $r): ?>
                                        <option value="<?php echo $r['id']; ?>"><?php echo htmlspecialchars($r['username']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        <?php else: ?>
                            <input type="hidden" name="member_id" id="f_member_id" value="<?php echo $id_usuario; ?>">
                        <?php endif; ?>

                        <div class="form-group">
                            <label>Nome da sua Marca (Ex: João TV)</label>
                            <input type="text" name="nome_marca" id="f_nome_marca" placeholder="Nome que vai aparecer no site" required>
                        </div>
                    </div>

                    <div class="grid-2">
                        <div class="form-group">
                            <label>Colar Link da Logo</label>
                            <input type="text" name="logo_url_texto" id="f_logo_url_texto" placeholder="Ex: https://imgur.com/logo.png">
                        </div>
                        <div class="form-group">
                            <label style="color:var(--success);"><i class="fas fa-upload"></i> OU Fazer Upload do Computador</label>
                            <input type="file" name="logo_file" id="f_logo_file" accept="image/png, image/jpeg, image/webp, image/gif">
                        </div>
                    </div>
                    <small style="color:var(--text-muted); display:block; margin-top:-10px; margin-bottom:20px;">Se você selecionar um arquivo do computador, o link colado será ignorado.</small>

                    <div class="grid-2">
                        <div class="form-group">
                            <label>Cor de Fundo</label>
                            <div style="display:flex; gap:10px;">
                                <input type="color" name="cor_fundo" id="f_cor_fundo" value="#121519" style="width: 60px;">
                                <input type="text" value="#121519" id="f_cor_fundo_txt" readonly style="color: var(--text-muted);">
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Cor do Botão</label>
                            <div style="display:flex; gap:10px;">
                                <input type="color" name="cor_botao" id="f_cor_botao" value="#007bff" style="width: 60px;">
                                <input type="text" value="#007bff" id="f_cor_botao_txt" readonly style="color: var(--text-muted);">
                            </div>
                        </div>
                    </div>
                    
                    <div style="display:flex; gap:10px;">
                        <button type="submit" id="btnSaveForm" class="btn-save"><i class="fas fa-save"></i> SALVAR E GERAR LINK SECRETO</button>
                        <button type="button" onclick="resetForm()" class="btn-action" style="margin-top:10px; padding: 15px; font-size:15px; display:none;" id="btnCancel">Cancelar Edição</button>
                    </div>
                </form>
            </div>

            <div class="card">
                <h3><i class="fas fa-link" style="color: #f39c12;"></i> Links Prontos para Uso</h3>
                <div class="table-responsive">
                    <table>
                        <thead>
                            <tr>
                                <th>Marca</th>
                                <th>Cores</th>
                                <th>Seu Link Oficial</th>
                                <th>Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(empty($players)): ?>
                                <tr><td colspan="4" style="text-align:center; color: var(--text-muted); padding: 30px 0;">Você ainda não criou nenhum Web Player.</td></tr>
                            <?php else: foreach($players as $p): 
                                
                                $link_player = $protocolo . $dominio . "/webplayer/index.php?id=" . $p['slug'];
                            ?>
                                <tr>
                                    <td>
                                        <div style="display:flex; align-items:center; gap:10px;">
                                            <?php if(!empty($p['logo_url'])): ?>
                                                <img src="<?php echo htmlspecialchars($p['logo_url']); ?>" class="player-logo-preview">
                                            <?php endif; ?>
                                            <div>
                                                <strong><?php echo htmlspecialchars($p['nome_marca']); ?></strong>
                                                <?php if($is_admin): 
                                                    $dono_nome = $mapa_nomes[$p['member_id']] ?? 'ID: ' . $p['member_id'];
                                                    if ($p['member_id'] == $id_usuario) $dono_nome = 'Eu mesmo (Admin)';
                                                ?>
                                                    <div style="font-size:11px; color:#8b5cf6; margin-top:3px;"><i class="fas fa-user-tie"></i> Revenda: <?php echo htmlspecialchars($dono_nome); ?></div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="margin-bottom:4px;"><span class="color-dot" style="background:<?php echo htmlspecialchars($p['cor_fundo']); ?>;"></span> Fundo</div>
                                        <div><span class="color-dot" style="background:<?php echo htmlspecialchars($p['cor_botao']); ?>;"></span> Botão</div>
                                    </td>
                                    <td>
                                        <input type="text" value="<?php echo $link_player; ?>" id="link_<?php echo $p['id']; ?>" readonly style="background:transparent; border:1px dashed var(--border-color); padding:8px; color:var(--success); font-weight:bold; font-size:12px; width:100%; max-width:300px; border-radius:4px;">
                                    </td>
                                    <td>
                                        <button class="btn-action btn-copy" onclick="copiarLink('link_<?php echo $p['id']; ?>')" title="Copiar Link para mandar pro Cliente"><i class="fas fa-copy"></i> Copiar</button>
                                        
                                        <button class="btn-action" onclick='editarPlayer(<?php echo json_encode($p); ?>)' title="Editar Cores/Logo"><i class="fas fa-edit"></i></button>
                                        
                                        <a href="?delete=<?php echo $p['id']; ?>" class="btn-action btn-delete" onclick="return confirm('Tem certeza? O link atual vai parar de funcionar para os clientes.')" title="Apagar"><i class="fas fa-trash"></i></a>
                                    </td>
                                </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <script>
        // Verificação do limite no Javascript para travar o botão visualmente
        const atingiuLimite = <?php echo $atingiu_limite ? 'true' : 'false'; ?>;

        function toggleMenu() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('overlay').classList.toggle('active'); 
        }

        function toggleSubmenu(id) {
            var submenu = document.getElementById(id);
            var arrow = document.getElementById('arrow-' + id);
            
            if (submenu.style.display === "block") {
                submenu.style.display = "none";
                if(arrow) arrow.style.transform = "rotate(0deg)";
            } else {
                submenu.style.display = "block";
                if(arrow) arrow.style.transform = "rotate(180deg)";
            }
        }

        function copiarLink(id) {
            var copyText = document.getElementById(id);
            copyText.select();
            copyText.setSelectionRange(0, 99999);
            navigator.clipboard.writeText(copyText.value).then(() => {
                alert("Link Anônimo do Player copiado! Envie com segurança para seus clientes.");
            }).catch(err => {
                document.execCommand("copy");
                alert("Link copiado!");
            });
        }

        document.getElementById('f_cor_fundo').addEventListener('input', function() { document.getElementById('f_cor_fundo_txt').value = this.value; });
        document.getElementById('f_cor_botao').addEventListener('input', function() { document.getElementById('f_cor_botao_txt').value = this.value; });

        function editarPlayer(dados) {
            document.getElementById('formTitle').innerHTML = '<i class="fas fa-edit" style="color:var(--warning);"></i> Editar Meu Player';
            document.getElementById('f_player_id').value = dados.id;
            
            if(document.getElementById('f_member_id').tagName === 'SELECT') {
                document.getElementById('f_member_id').value = dados.member_id;
            } else {
                document.getElementById('f_member_id').value = dados.member_id;
            }
            
            document.getElementById('f_nome_marca').value = dados.nome_marca;
            document.getElementById('f_logo_url_texto').value = dados.logo_url;
            document.getElementById('f_logo_file').value = ''; 
            document.getElementById('f_cor_fundo').value = dados.cor_fundo;
            document.getElementById('f_cor_fundo_txt').value = dados.cor_fundo;
            document.getElementById('f_cor_botao').value = dados.cor_botao;
            document.getElementById('f_cor_botao_txt').value = dados.cor_botao;
            
            // Se ele for editar, liberamos o botão de salvar mesmo que ele esteja no limite
            document.getElementById('btnSaveForm').disabled = false;
            document.getElementById('btnSaveForm').innerHTML = '<i class="fas fa-save"></i> SALVAR EDIÇÃO';
            
            document.getElementById('btnCancel').style.display = 'block';
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }

        function resetForm() {
            document.getElementById('formTitle').innerHTML = '<i class="fas fa-magic" style="color:var(--accent);"></i> Configurar Meu Player';
            document.getElementById('formPlayer').reset();
            document.getElementById('f_player_id').value = '';
            document.getElementById('f_cor_fundo_txt').value = '#121519';
            document.getElementById('f_cor_botao_txt').value = '#007bff';
            document.getElementById('btnCancel').style.display = 'none';
            
            // Se for criar um novo e ele estiver no limite, travamos de novo
            if(atingiuLimite) {
                document.getElementById('btnSaveForm').disabled = true;
                document.getElementById('btnSaveForm').innerHTML = '<i class="fas fa-lock"></i> LIMITE DE PLAYERS ATINGIDO';
            } else {
                document.getElementById('btnSaveForm').disabled = false;
                document.getElementById('btnSaveForm').innerHTML = '<i class="fas fa-save"></i> SALVAR E GERAR LINK SECRETO';
            }
        }
        
        // Puxa a quantidade certa quando o admin for alterar no select
        function atualizarCampoLimite() {
            var sel = document.getElementById('sel_limite_revenda');
            var opt = sel.options[sel.selectedIndex];
            document.getElementById('val_new_limit').value = opt.getAttribute('data-limit');
        }
        
        // Trava o botão ao carregar a página se o limite já estourou
        window.onload = function() {
            if(atingiuLimite && document.getElementById('f_player_id').value === '') {
                document.getElementById('btnSaveForm').disabled = true;
                document.getElementById('btnSaveForm').innerHTML = '<i class="fas fa-lock"></i> LIMITE DE PLAYERS ATINGIDO';
            }
        };
        
        setTimeout(function() { 
            try { 
                var alerts = document.querySelectorAll('.alert'); 
                for(var i=0; i<alerts.length; i++) { alerts[i].style.opacity='0'; } 
                setTimeout(function(){ 
                    for(var j=0; j<alerts.length; j++) { alerts[j].style.display='none'; } 
                }, 500); 
            } catch(e) {} 
        }, 4000);
    </script>
</body>
</html>