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

$pdo = getConexaoInterna(); 

// --- PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV';
$cor_primaria = '#007bff';
try {
    $config_p = $pdo->query("SELECT nome_painel, cor_primaria FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($config_p) {
        $nome_painel = $config_p['nome_painel'] ?: $nome_painel;
        $cor_primaria = $config_p['cor_primaria'] ?: $cor_primaria;
    }
} catch (Exception $e) {}

if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }

$nome_usuario = $_SESSION['username'] ?? 'Usuário';
$role = $_SESSION['user_role'] ?? 'admin';
$my_id = $_SESSION['user_id'];

// =========================================================================
// BANCO DE DADOS: CRIAR TABELA LOCAL PARA CLIENTES BINSTREAM/P2P
// =========================================================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `binstream_clientes` (
        `id` int(11) AUTO_INCREMENT PRIMARY KEY,
        `usuario` varchar(100) NOT NULL,
        `senha` varchar(100) NOT NULL,
        `vencimento` datetime DEFAULT NULL,
        `status` enum('ativo','bloqueado') DEFAULT 'ativo',
        `plataforma` varchar(50) DEFAULT 'binstream',
        `bouquet_id` int(11) DEFAULT NULL,
        `api_res_id` varchar(100) DEFAULT NULL,
        `data_cadastro` timestamp DEFAULT CURRENT_TIMESTAMP
    )");
    
    // AUTO-CORREÇÃO: Adiciona a coluna para separar clientes por dono/revendedor
    $pdo->exec("ALTER TABLE `binstream_clientes` ADD COLUMN IF NOT EXISTS `member_id` INT(11) DEFAULT 0");
} catch (PDOException $e) {}

// =========================================================================
// LÓGICA DE VISIBILIDADE (MENU DINÂMICO)
// =========================================================================
$api_conf = $pdo->query("SELECT api_binstream_url, api_binstream_key FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
if (empty($api_conf['api_binstream_url']) && $role !== 'admin') {
    die("Serviço Binstream não configurado ou indisponível.");
}

$mensagem = "";

// AÇÃO: CRIAR CLIENTE LOCALMENTE (SIMULAÇÃO ANTES DA API REAL)
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action_criar_p2p'])) {
    $user = trim($_POST['p2p_user']);
    $pass = trim($_POST['p2p_pass']);
    $venc = $_POST['p2p_venc'];
    $bq_id = $_POST['p2p_bouquet'];
    
    try {
        // Agora salva o $my_id (Dono do cliente)
        $stmt = $pdo->prepare("INSERT INTO binstream_clientes (usuario, senha, vencimento, bouquet_id, plataforma, member_id) VALUES (?, ?, ?, ?, 'binstream', ?)");
        $stmt->execute([$user, $pass, $venc, $bq_id, $my_id]);
        $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Cliente Binstream P2P criado com sucesso! (Aguardando integração final da API)</div>";
    } catch (Exception $e) { $mensagem = "<div class='alert danger'><i class='fas fa-exclamation-triangle'></i> Erro: " . $e->getMessage() . "</div>"; }
}

// TRAVA DE SEGURANÇA: Revendedor só afeta os próprios clientes
$condicao_dono = ($role !== 'admin') ? " AND member_id = " . intval($my_id) : "";

// AÇÕES INDIVIDUAIS: APAGAR E BLOQUEAR
if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM binstream_clientes WHERE id = ? $condicao_dono")->execute([$_GET['delete']]);
    header("Location: binstream_p2p.php"); exit;
}
if (isset($_GET['block'])) {
    $pdo->prepare("UPDATE binstream_clientes SET status = IF(status='ativo', 'bloqueado', 'ativo') WHERE id = ? $condicao_dono")->execute([$_GET['block']]);
    header("Location: binstream_p2p.php"); exit;
}

// AÇÃO INDIVIDUAL: RENOVAR
if (isset($_POST['action_renew'])) {
    $id = intval($_POST['renew_id']);
    $meses = intval($_POST['renew_meses']);
    $pdo->prepare("UPDATE binstream_clientes SET vencimento = DATE_ADD(vencimento, INTERVAL ? MONTH) WHERE id = ? $condicao_dono")->execute([$meses, $id]);
    $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Renovação aplicada com sucesso!</div>";
}

// AÇÕES EM MASSA
if (isset($_POST['action_bulk'])) {
    $tipo = $_POST['bulk_type'];
    $ids_raw = explode(',', $_POST['bulk_ids']);
    $clean_ids = []; foreach($ids_raw as $i) { if(intval($i) > 0) $clean_ids[] = intval($i); }
    
    if (!empty($clean_ids)) {
        $id_list = implode(',', $clean_ids);
        if ($tipo === 'delete') {
            $pdo->exec("DELETE FROM binstream_clientes WHERE id IN ($id_list) $condicao_dono");
            $mensagem = "<div class='alert success'>Clientes apagados com sucesso!</div>";
        } elseif ($tipo === 'block') {
            $pdo->exec("UPDATE binstream_clientes SET status = IF(status='ativo', 'bloqueado', 'ativo') WHERE id IN ($id_list) $condicao_dono");
            $mensagem = "<div class='alert success'>Status alterado com sucesso!</div>";
        } elseif ($tipo === 'renew') {
            $meses = intval($_POST['bulk_months']);
            $pdo->exec("UPDATE binstream_clientes SET vencimento = DATE_ADD(vencimento, INTERVAL $meses MONTH) WHERE id IN ($id_list) $condicao_dono");
            $mensagem = "<div class='alert success'>Renovação em massa aplicada com sucesso!</div>";
        }
    }
}

// Busca pacotes
$pacotes = $pdo->query("SELECT * FROM api_bouquets WHERE servidor = 'binstream'")->fetchAll(PDO::FETCH_ASSOC);

// ISOLAMENTO DE LISTA: Revendedor só vê os dele
if ($role === 'admin') {
    $clientes = $pdo->query("SELECT * FROM binstream_clientes ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
} else {
    $clientes = $pdo->query("SELECT * FROM binstream_clientes WHERE member_id = " . intval($my_id) . " ORDER BY id DESC")->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>Binstream P2P - <?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: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        
        /* MENU LATERAL COMPLETO E RESPONSIVO */
        .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); }
        
        .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; }

        /* SUBMENUS DO PAINEL */
        .submenu { display: none; background: #1a1d21; }
        .submenu .menu-item { padding-left: 45px; font-size: 13px; }
        .arrow-icon { margin-left: auto; font-size: 10px; transition: transform 0.3s; }
        
        /* ÁREA PRINCIPAL */
        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; position: relative; }
        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 15px 25px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); }
        .topbar-left { display: flex; align-items: center; 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; }
        .user-pill { background: #2c3138; padding: 8px 15px; border-radius: 20px; font-size: 13px; font-weight: bold; color: white; display: flex; align-items: center; gap: 8px; border: 1px solid var(--border-color);}

        /* CONTEÚDO BINSTREAM (MANTEVE ORIGINAL, APENAS ESTILIZADO) */
        .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; box-shadow: 0 4px 15px rgba(0,0,0,0.1); margin-bottom: 25px; }
        
        .form-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 20px; }
        label { display: block; margin-bottom: 8px; font-size: 13px; font-weight: bold; color: var(--text-muted); }
        input, select { background: #121519; border: 1px solid var(--border-color); color: white; padding: 12px; border-radius: 6px; width: 100%; box-sizing: border-box; font-family: inherit;}
        input:focus, select:focus { outline: none; border-color: var(--accent); }
        
        .btn { padding: 12px 20px; border-radius: 6px; border: none; font-weight: bold; cursor: pointer; transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; font-size: 14px; text-decoration: none; color: white; }
        .btn-success { background: var(--success); }
        .btn-success:hover { background: #218838; }
        .btn-sm { padding: 6px 12px; font-size: 12px; margin-right: 3px; }
        .btn-danger { background: var(--danger); }
        .btn-secondary { background: #6c757d; }
        
        .table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        .table th { text-align: left; padding: 15px 12px; border-bottom: 2px solid var(--border-color); color: var(--text-muted); font-size: 13px; text-transform: uppercase; }
        .table td { padding: 15px 12px; border-bottom: 1px solid var(--border-color); font-size: 14px; }
        
        .badge { padding: 5px 10px; border-radius: 4px; font-size: 11px; font-weight: bold; text-transform: uppercase; }
        .badge-ativo { background: rgba(40, 167, 69, 0.15); border: 1px solid var(--success); color: var(--success); }
        .badge-bloqueado { background: rgba(220, 53, 69, 0.15); border: 1px solid var(--danger); color: var(--danger); }

        .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.1); border: 1px solid var(--success); color: var(--success); }
        .alert.danger { background: rgba(220, 53, 69, 0.1); border: 1px solid var(--danger); color: var(--danger); }

        /* INJEÇÃO DE CSS: MODAIS E BARRA DE AÇÕES EM MASSA */
        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); align-items: center; justify-content: center; }
        .modal-content { background: var(--bg-card); width: 90%; max-width: 400px; padding: 25px; border-radius: 12px; border: 1px solid var(--border-color); position: relative; }
        .btn-save-modal { width: 100%; padding: 12px; background: var(--accent); border: none; color: white; border-radius: 6px; font-weight: bold; cursor: pointer; margin-top: 5px; }
        .bulk-bar { display: none; background: rgba(30, 34, 39, 0.95); padding: 15px 20px; border-radius: 10px; border: 1px dashed var(--accent); margin-bottom: 20px; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px; }

        /* RESPONSIVO MOBILE */
        @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; }
            .table { display: block; overflow-x: auto; white-space: nowrap; }
        }
    </style>
</head>
<body>
    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>
    
    <nav class="sidebar" id="sidebar">
        <div class="sidebar-header"><?php echo htmlspecialchars($nome_painel); ?></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>

    <main class="main-content">
        <header class="topbar">
            <div class="topbar-left">
                <button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <div style="font-weight: bold; color: white; font-size: 18px;">GESTÃO BINSTREAM P2P</div>
            </div>
            <div class="user-pill"><i class="fas fa-user-circle"></i> <?php echo htmlspecialchars($nome_usuario); ?></div>
        </header>

        <div class="content-area">
            <h2 style="color:white; margin-top:0; margin-bottom: 25px;"><i class="fas fa-satellite-dish" style="color:var(--accent);"></i> Gerenciar Clientes Binstream</h2>
            
            <?php echo $mensagem; ?>

            <div class="card" style="border-top: 4px solid var(--accent);">
                <h3 style="margin-top:0; color:white; border-bottom: 1px solid var(--border-color); padding-bottom: 15px;"><i class="fas fa-user-plus"></i> Novo Usuário Binstream</h3>
                <form method="POST" style="margin-top: 20px;">
                    <div class="form-row">
                        <div><label>Usuário</label><input type="text" name="p2p_user" placeholder="Digite o usuário" required></div>
                        <div><label>Senha</label><input type="text" name="p2p_pass" placeholder="Digite a senha" required></div>
                        <div>
                            <label>Vencimento</label>
                            <input type="date" name="p2p_venc" value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>">
                        </div>
                        <div>
                            <label>Pacote (Bouquet)</label>
                            <select name="p2p_bouquet">
                                <?php foreach($pacotes as $p): ?>
                                    <option value="<?php echo $p['bouquet_id']; ?>"><?php echo htmlspecialchars($p['bouquet_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <button type="submit" name="action_criar_p2p" class="btn btn-success"><i class="fas fa-cloud-upload-alt"></i> CRIAR NO SERVIDOR BINSTREAM</button>
                </form>
            </div>

            <div id="bulkBar" class="bulk-bar">
                <span style="color: white; font-weight: bold; font-size:14px;"><span id="selCount" style="color:var(--accent); font-size: 16px;">0</span> Selecionados</span>
                <button type="button" class="btn btn-sm" style="background:var(--accent); color:white;" onclick="openBulkModal()"><i class="fas fa-cogs"></i> OPÇÕES EM MASSA</button>
            </div>

            <div class="card">
                <h3 style="margin-top:0; color:white; border-bottom: 1px solid var(--border-color); padding-bottom: 15px;"><i class="fas fa-list"></i> Clientes Ativos</h3>
                <table class="table">
                    <thead>
                        <tr>
                            <th style="width: 30px;"><input type="checkbox" id="selectAll" onclick="toggleAll(this)" style="cursor:pointer; width:16px; height:16px; accent-color: var(--accent);"></th>
                            <th>Usuário</th>
                            <th>Vencimento</th>
                            <th>Status</th>
                            <th>Pacote</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($clientes)): ?>
                            <tr><td colspan="6" style="text-align:center; color:var(--text-muted); padding: 30px;">Nenhum cliente cadastrado no momento.</td></tr>
                        <?php else: ?>
                            <?php foreach($clientes as $c): ?>
                            <tr>
                                <td><input type="checkbox" class="chk-item" value="<?php echo $c['id']; ?>" onchange="toggleBulk()" style="cursor:pointer; width:16px; height:16px; accent-color: var(--accent);"></td>
                                <td style="font-weight:bold; color:white;"><?php echo htmlspecialchars($c['usuario']); ?></td>
                                <td><?php echo date('d/m/Y', strtotime($c['vencimento'])); ?></td>
                                <td>
                                    <?php if($c['status'] == 'ativo'): ?>
                                        <span class="badge badge-ativo">Ativo</span>
                                    <?php else: ?>
                                        <span class="badge badge-bloqueado">Bloqueado</span>
                                    <?php endif; ?>
                                </td>
                                <td><small style="color:var(--text-muted);"><i class="fas fa-box"></i> ID: <?php echo $c['bouquet_id']; ?></small></td>
                                <td>
                                    <button class="btn btn-sm btn-info" style="background:#007bff; color:white; border:none;" onclick='viewInfo(<?php echo json_encode($c); ?>)' title="Ver Informações"><i class="fas fa-eye"></i></button>
                                    <button class="btn btn-sm btn-success" onclick="openRenew(<?php echo $c['id']; ?>, '<?php echo htmlspecialchars($c['usuario']); ?>')" title="Renovar"><i class="fas fa-sync"></i></button>
                                    
                                    <?php if($c['status'] == 'ativo'): ?>
                                        <a href="?block=<?php echo $c['id']; ?>" class="btn btn-sm btn-warning" style="background:var(--warning); color:black; text-decoration:none;" title="Bloquear"><i class="fas fa-ban"></i></a>
                                    <?php else: ?>
                                        <a href="?block=<?php echo $c['id']; ?>" class="btn btn-sm" style="background:var(--success); color:white; text-decoration:none;" title="Desbloquear"><i class="fas fa-check"></i></a>
                                    <?php endif; ?>
                                    
                                    <a href="?delete=<?php echo $c['id']; ?>" class="btn btn-sm btn-secondary" style="background:var(--danger); text-decoration:none;" onclick="return confirm('Tem certeza que deseja excluir?')" title="Excluir"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <?php include 'rodape.php'; ?>
        </div>
    </main>

    <div id="modalView" class="modal"><div class="modal-content">
        <h3 style="margin-top:0;"><i class="fas fa-eye" style="color:#007bff;"></i> Dados de Acesso Binstream</h3>
        <textarea id="view_text" rows="8" readonly style="width:100%; background:#121519; color:white; border:1px solid var(--border-color); padding:10px; border-radius:5px; resize:none; font-size:12px; margin-bottom:10px;"></textarea>
        <button onclick="copyView()" class="btn-save-modal" style="background:#007bff; margin-bottom:10px;"><i class="fas fa-copy"></i> COPIAR DADOS</button>
        <a id="view_zap" href="#" target="_blank" class="btn-save-modal" style="background:#25d366; display:block; text-align:center; text-decoration:none; box-sizing:border-box;"><i class="fab fa-whatsapp"></i> ENVIAR WHATSAPP</a>
        <button type="button" onclick="closeModal('modalView')" style="width:100%; background:none; border:none; color:gray; margin-top:10px; cursor:pointer;">Fechar</button>
    </div></div>

    <div id="modalRenew" class="modal"><div class="modal-content">
        <h3 style="margin-top:0;"><i class="fas fa-sync-alt" style="color:var(--success);"></i> Renovar Cliente</h3>
        <p style="font-size:13px; color:var(--text-muted); margin-top:-5px;">Usuário: <strong id="renew_code" style="color:white;"></strong></p>
        <form method="POST">
            <input type="hidden" name="action_renew" value="1">
            <input type="hidden" name="renew_id" id="renew_id">
            <div style="margin-bottom: 15px;"><label>Adicionar meses</label><input type="number" name="renew_meses" value="1" min="1" style="font-size:18px; text-align:center; font-weight:bold; width:100%;"></div>
            <button type="submit" class="btn-save-modal" style="background:var(--success);">CONFIRMAR RENOVAÇÃO</button>
            <button type="button" onclick="closeModal('modalRenew')" style="width:100%; background:none; border:none; color:gray; margin-top:10px; cursor:pointer;">Cancelar</button>
        </form>
    </div></div>

    <div id="modalBulk" class="modal"><div class="modal-content">
        <h3 style="margin-top:0;"><i class="fas fa-layer-group" style="color:var(--accent);"></i> Ações em Massa</h3>
        <form method="POST">
            <input type="hidden" name="action_bulk" value="1">
            <input type="hidden" name="bulk_ids" id="bulk_ids_input">
            
            <div style="margin-bottom: 15px;">
                <label>Selecione a Ação</label>
                <select name="bulk_type" id="bulk_type" onchange="changeBulk(this.value)" required style="width:100%;">
                    <option value="">-- Escolha --</option>
                    <option value="renew">Renovar Vencimento</option>
                    <option value="block">Bloquear / Desbloquear</option>
                    <option value="delete">Apagar Permanentemente</option>
                </select>
            </div>

            <div id="bulk_renew_div" style="display:none; margin-bottom:15px;">
                <label>Adicionar Meses</label>
                <input type="number" name="bulk_months" value="1" min="1" style="width:100%;">
            </div>

            <button type="submit" class="btn-save-modal" onclick="return confirm('Confirmar ação em massa para todos selecionados?')">APLICAR AÇÃO</button>
            <button type="button" onclick="closeModal('modalBulk')" style="width:100%; background:none; border:none; color:gray; margin-top:10px; cursor:pointer;">Cancelar</button>
        </form>
    </div></div>

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

        // Script para animar as setinhas e abrir as pastas do menu lateral
        function toggleSubmenu(id) {
            const sub = document.getElementById(id);
            const arrow = document.getElementById('arrow-' + id);
            
            if (sub.style.display === "block") {
                sub.style.display = "none";
                if(arrow) arrow.style.transform = "rotate(0deg)";
            } else {
                sub.style.display = "block";
                if(arrow) arrow.style.transform = "rotate(180deg)";
            }
        }

        // INJEÇÃO DE SCRIPTS PARA OS MODAIS E CHECKBOXES
        function openModal(id) { document.getElementById(id).style.display = 'flex'; }
        function closeModal(id) { document.getElementById(id).style.display = 'none'; }

        function viewInfo(u) {
            let parts = u.vencimento.split(' ');
            let dateStr = parts[0].split('-').reverse().join('/') + ' ' + parts[1];
            let text = `🚀 *DADOS DE ACESSO BINSTREAM*\n\n👤 *Usuário:* ${u.usuario}\n🔑 *Senha:* ${u.senha}\n📅 *Vencimento:* ${dateStr}`;
            document.getElementById('view_text').value = text;
            document.getElementById('view_zap').href = `https://wa.me/?text=${encodeURIComponent(text)}`;
            openModal('modalView');
        }

        function copyView() {
            const area = document.getElementById('view_text');
            area.select(); document.execCommand('copy');
            alert('Copiado com sucesso!');
        }

        function openRenew(id, nome) {
            document.getElementById('renew_id').value = id;
            document.getElementById('renew_code').innerText = nome;
            openModal('modalRenew');
        }

        // SELEÇÃO E AÇÕES EM MASSA
        function toggleAll(source) {
            const checkboxes = document.querySelectorAll('.chk-item');
            checkboxes.forEach(chk => chk.checked = source.checked);
            toggleBulk();
        }

        function toggleBulk() {
            const checkboxes = document.querySelectorAll('.chk-item:checked');
            const bar = document.getElementById('bulkBar');
            const countSpan = document.getElementById('selCount');
            if (bar && countSpan) {
                if (checkboxes.length > 0) {
                    countSpan.innerText = checkboxes.length;
                    bar.style.display = 'flex';
                } else {
                    bar.style.display = 'none';
                    const selectAll = document.getElementById('selectAll');
                    if (selectAll) selectAll.checked = false;
                }
            }
        }

        function openBulkModal() {
            const checkboxes = document.querySelectorAll('.chk-item:checked');
            let ids = [];
            checkboxes.forEach(chk => ids.push(chk.value));
            document.getElementById('bulk_ids_input').value = ids.join(',');
            
            document.getElementById('bulk_type').value = "";
            changeBulk("");
            openModal('modalBulk');
        }

        function changeBulk(val) {
            document.getElementById('bulk_renew_div').style.display = (val === 'renew') ? 'block' : 'none';
        }
    </script>
</body>
</html>