<?php
// --- CORREÇÃO DE MEMÓRIA E TEMPO DE EXECUÇÃO ---
ini_set('memory_limit', '-1'); 
set_time_limit(0);

session_start();
require_once 'config.php'; 

$pdo = getConexaoAtiva();
$pdo->exec("SET NAMES utf8mb4");

// =================================================================================
// --- LÓGICA AJAX PARA CARREGAMENTO RÁPIDO DO BOUQUET (SEM TRAVAR A TELA) ---
// =================================================================================
if (isset($_GET['ajax_get_bouquet'])) {
    header('Content-Type: application/json; charset=utf-8');
    $id = intval($_GET['ajax_get_bouquet']);
    $stmt = $pdo->prepare("SELECT bouquet_channels FROM bouquets WHERE id = ?");
    $stmt->execute([$id]);
    $channels = $stmt->fetchColumn();
    echo $channels ?: '[]';
    exit;
}

// --- 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_p = $pdo->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($config_p) {
            $nome_painel = !empty($config_p['nome_painel']) ? $config_p['nome_painel'] : $nome_painel;
            $logo_url = !empty($config_p['logo_url']) ? $config_p['logo_url'] : $logo_url;
            $cor_primaria = !empty($config_p['cor_primaria']) ? $config_p['cor_primaria'] : $cor_primaria;
        }
    }
} catch (Exception $e) {}

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

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

try {
    $user_credits = $pdo->query("SELECT credits FROM reg_users WHERE id = " . intval($user_id_logado))->fetchColumn() ?: 0;
} catch (Exception $e) { $user_credits = 0; }

// =================================================================================
// --- OTIMIZAÇÃO: MAPEAR MÍDIAS PARA O JAVASCRIPT (MUITO MAIS RÁPIDO) ---
// =================================================================================
$categories = $pdo->query("SELECT id, category_name FROM stream_categories ORDER BY category_name ASC")->fetchAll(PDO::FETCH_ASSOC);

// Puxa tudo de uma vez de forma bruta, vamos agrupar no PHP para aliviar o banco
$all_media = $pdo->query("SELECT id, stream_display_name as name, category_id FROM streams ORDER BY stream_display_name ASC")->fetchAll(PDO::FETCH_ASSOC);

$media_by_cat = [];
foreach($all_media as $item) { 
    // Usamos 'i' e 'n' para economizar megabytes de texto no código final
    $media_by_cat[$item['category_id']][] = ['i' => (int)$item['id'], 'n' => $item['name']]; 
}
// =================================================================================


// Lógica de Salvar/Editar BURLANDO O MAX_INPUT_VARS
if (isset($_POST['save_bouquet'])) {
    $name = $_POST['bouquet_name'];
    $order = intval($_POST['bouquet_order']);
    $id = $_POST['bouquet_id'];
    
    // Agora recebemos a lista num campo só, em formato de texto JSON, e salvamos direto!
    $channels_json = $_POST['bouquet_data_json'] ?? '[]';
    
    // Validação básica para evitar erros
    if (!is_array(json_decode($channels_json, true))) {
        $channels_json = '[]';
    }
    
    if (!empty($id)) {
        $sql = "UPDATE bouquets SET bouquet_name=?, bouquet_channels=?, bouquet_order=? WHERE id=?";
        $pdo->prepare($sql)->execute([$name, $channels_json, $order, $id]);
    } else {
        $sql = "INSERT INTO bouquets (bouquet_name, bouquet_channels, bouquet_order) VALUES (?, ?, ?)";
        $pdo->prepare($sql)->execute([$name, $channels_json, $order]);
    }
    header("Location: bouquets.php"); exit;
}

if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM bouquets WHERE id = ?")->execute([$_GET['delete']]);
    header("Location: bouquets.php"); exit;
}

// OTIMIZAÇÃO: Na lista da tela inicial, NÃO puxamos a coluna bouquet_channels (para não travar a tabela)
$bouquets_lista = $pdo->query("SELECT id, bouquet_name, bouquet_order FROM bouquets ORDER BY bouquet_order ASC")->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>Bouquets - <?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; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; }
        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; cursor: pointer; transition: 0.2s; font-size: 15px; }
        .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); }
        
        .submenu { display: none; background: #16191d; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 14px; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 12px; }
        .rotate { transform: rotate(180deg); }
        .menu-category { padding: 20px 20px 8px; font-size: 11px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; }
        .logout-btn { padding: 15px; background-color: var(--danger); color: white; text-align: center; text-decoration: none; font-weight: bold; margin-top: auto; }

        .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); }
        .content-area { padding: 20px; flex: 1; }
        
        .card-table { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 10px; width: 100%; overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; min-width: 500px; }
        th { background: rgba(0,0,0,0.2); padding: 12px 15px; text-align: left; color: var(--text-muted); font-size: 11px; text-transform: uppercase; }
        td { padding: 15px; border-bottom: 1px solid var(--border-color); font-size: 14px; }
        
        .header-container { display: flex; justify-content: space-between; align-items: center; padding-bottom: 15px; }
        .btn-main { background: var(--accent); color: white; border: none; padding: 10px 18px; border-radius: 6px; cursor: pointer; font-weight: bold; transition: 0.2s; }
        .btn-main:hover { filter: brightness(1.2); }
        
        .btn-action { padding: 8px 12px; border-radius: 4px; text-decoration: none; font-size: 12px; margin-right: 5px; color: white; border: none; cursor: pointer; display: inline-flex; align-items: center; gap: 5px; }

        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); overflow-y: auto; }
        .modal-content { background: var(--bg-card); width: 95%; max-width: 900px; margin: 5% auto; padding: 25px; border-radius: 12px; border: 1px solid var(--border-color); }
        
        /* OTIMIZAÇÃO CSS: Área de Seleção de Mídias (Rápida) */
        .bouquet-editor { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
        .cat-list-container { border: 1px solid var(--border-color); border-radius: 8px; background: #1a1d21; overflow-y: auto; height: 400px; }
        .media-list-container { border: 1px solid var(--border-color); border-radius: 8px; background: #121519; overflow-y: auto; padding: 10px; height: 400px; }
        
        .cat-item { padding: 10px 15px; border-bottom: 1px solid var(--border-color); display: flex; align-items: center; justify-content: space-between; cursor: pointer; transition: 0.2s; }
        .cat-item:hover { background: #2c3138; }
        .cat-item.active { background: #2c3138; border-left: 3px solid var(--accent); }
        .cat-name-area { display: flex; align-items: center; gap: 10px; flex: 1; }
        
        .media-item { display: flex; align-items: center; padding: 8px; font-size: 13px; cursor: pointer; border-radius: 4px; color: white; }
        .media-item:hover { background: #1a1d21; }
        .media-item input { margin-right: 10px; cursor: pointer; width: 16px; height: 16px;}

        .loading-text { text-align: center; color: var(--text-muted); padding: 20px; font-size: 14px; }
        .badge-count { background: var(--accent); color: white; font-size: 11px; padding: 3px 8px; border-radius: 10px; font-weight: bold; }

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

        @media (max-width: 768px) {
            .bouquet-editor { grid-template-columns: 1fr; grid-template-rows: auto auto; }
            .cat-list-container { height: 250px; }
            .media-list-container { height: 350px; }
            .menu-toggle { display: block; }
            .sidebar { position: fixed; left: -260px; height: 100%; }
            .sidebar.active { left: 0; }
            .sidebar-overlay.active { display: block; }
        }
    </style>
</head>
<body>
    <div class="sidebar-overlay" id="overlay" onclick="document.getElementById('sidebar').classList.remove('active'); this.classList.remove('active');"></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" style="max-width: 180px; max-height: 60px; object-fit: contain;">
            <?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>
            <div style="margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px;">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="document.getElementById('sidebar').classList.toggle('active'); document.getElementById('overlay').classList.toggle('active');"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; font-size: 18px; color:white;">Bouquets</h2>
            </div>
        </header>

        <div class="content-area">
            <div class="header-container">
                <h3 style="margin:0;">Gerenciar Bouquets</h3>
                <button class="btn-main" onclick="openModal()">+ NOVO</button>
            </div>

            <div class="card-table">
                <table>
                    <thead>
                        <tr>
                            <th style="padding-left:15px;">Bouquet</th>
                            <th style="text-align:right; padding-right:15px;">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($bouquets_lista as $b): ?>
                        <tr>
                            <td style="padding-left:15px;"><strong><?php echo htmlspecialchars($b['bouquet_name']); ?></strong></td>
                            <td style="text-align:right; padding-right:15px;">
                                <button class="btn-action" style="background:var(--accent);" onclick="openModal(<?php echo $b['id']; ?>, '<?php echo addslashes($b['bouquet_name']); ?>', '<?php echo $b['bouquet_order']; ?>')">
                                    <i class="fas fa-edit"></i> Editar
                                </button>
                                <a href="?delete=<?php echo $b['id']; ?>" class="btn-action" style="background:var(--danger);" onclick="return confirm('Excluir bouquet?')">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <div id="bouquetModal" class="modal">
        <div class="modal-content">
            <h2 id="modalTitle" style="margin-top:0;">Configurar Bouquet</h2>
            <form method="POST" id="formBouquet">
                <input type="hidden" name="bouquet_id" id="b_id">
                <input type="text" name="bouquet_name" id="b_name" placeholder="Nome do Bouquet" required style="width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 6px; margin-bottom: 15px; box-sizing: border-box;">
                
                <div style="display:flex; gap:10px; margin-bottom: 15px;">
                    <button type="button" class="btn-main" style="flex:1; background:var(--success);" onclick="massSelect('all')">
                        <i class="fas fa-check-double"></i> Selecionar Tudo
                    </button>
                    <button type="button" class="btn-main" style="flex:1; background:var(--danger);" onclick="massSelect('none')">
                        <i class="fas fa-times"></i> Limpar Tudo
                    </button>
                </div>

                <div class="bouquet-editor">
                    <div class="cat-list-container" id="catList">
                        </div>
                    <div class="media-list-container" id="mediaList">
                        <div class="loading-text">Selecione uma categoria ao lado para ver os canais/filmes.</div>
                    </div>
                </div>

                <input type="hidden" name="bouquet_data_json" id="bouquet_data_json" value="[]">

                <input type="number" name="bouquet_order" id="b_order" placeholder="Ordem de Exibição" style="width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 6px; margin-bottom: 15px; margin-top: 15px; box-sizing: border-box;">
                
                <button type="button" class="btn-main" style="width:100%; padding:15px; background:#007bff; font-size:16px;" onclick="preSubmit()">SALVAR BOUQUET</button>
                
                <button type="submit" name="save_bouquet" id="realSubmit" style="display:none;"></button>
                <button type="button" onclick="closeModal()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:10px; cursor:pointer;">Cancelar</button>
            </form>
        </div>
    </div>

    <script>
        // Recebe os dados brutos e compactos do PHP
        const categoriesData = <?php echo json_encode($categories); ?>;
        const mediaByCat = <?php echo json_encode($media_by_cat); ?>;
        
        let selectedSet = new Set(); // Nossa memória super rápida no navegador
        let currentCatOpen = null;
        
        async function openModal(id = null, name = '', order = '') {
            document.getElementById('formBouquet').reset();
            selectedSet.clear();
            currentCatOpen = null;
            document.getElementById('mediaList').innerHTML = '<div class="loading-text">Selecione uma categoria ao lado.</div>';
            
            if (id) {
                document.getElementById('modalTitle').innerText = "Editar Bouquet";
                document.getElementById('b_id').value = id;
                document.getElementById('b_name').value = name;
                document.getElementById('b_order').value = order;
                
                // Mostra que está buscando na tela
                document.getElementById('mediaList').innerHTML = '<div class="loading-text"><i class="fas fa-spinner fa-spin"></i> Carregando suas seleções do banco de dados...</div>';
                
                // Busca de forma "invisível" os canais que o cara já tinha salvo
                try {
                    const response = await fetch('bouquets.php?ajax_get_bouquet=' + id);
                    const savedIds = await response.json();
                    savedIds.forEach(sid => selectedSet.add(parseInt(sid)));
                } catch(e) {
                    console.log("Erro ao puxar dados do bouquet", e);
                }
                
                document.getElementById('mediaList').innerHTML = '<div class="loading-text">Canais carregados com sucesso!<br>Selecione uma categoria ao lado para visualizar.</div>';
            } else {
                document.getElementById('modalTitle').innerText = "Novo Bouquet";
                document.getElementById('b_id').value = "";
            }

            renderCategories();
            document.getElementById('bouquetModal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('bouquetModal').style.display = 'none';
        }

        // Desenha a lista da Esquerda (Categorias)
        function renderCategories() {
            let html = '';
            categoriesData.forEach(cat => {
                const items = mediaByCat[cat.id] || [];
                if(items.length === 0) return; // Esconde categoria vazia
                
                let checkedCount = 0;
                items.forEach(item => { if(selectedSet.has(item.i)) checkedCount++; });
                
                const isAllChecked = (checkedCount === items.length);
                const badge = checkedCount > 0 ? `<span class="badge-count">${checkedCount} / ${items.length}</span>` : '';
                
                html += `
                    <div class="cat-item ${currentCatOpen === cat.id ? 'active' : ''}" id="cat-row-${cat.id}" onclick="loadMedia(${cat.id})">
                        <div class="cat-name-area">
                            <input type="checkbox" id="check-cat-${cat.id}" style="width: 16px; height:16px; cursor:pointer;" ${isAllChecked ? 'checked' : ''} onclick="toggleCategory(event, ${cat.id})">
                            <span style="font-size:13px; font-weight:bold;">${cat.category_name}</span>
                        </div>
                        <div id="badge-cat-${cat.id}">${badge}</div>
                    </div>
                `;
            });
            document.getElementById('catList').innerHTML = html;
        }

        // Desenha a lista da Direita (Canais / Filmes / Séries)
        function loadMedia(catId) {
            currentCatOpen = catId;
            document.querySelectorAll('.cat-item').forEach(el => el.classList.remove('active'));
            document.getElementById(`cat-row-${catId}`).classList.add('active');
            
            const items = mediaByCat[catId] || [];
            let html = '';
            
            // Botão "Selecionar Todos" apenas desta categoria no topo
            html += `
                <div style="padding:10px; background:#1e2227; margin-bottom:10px; border-radius:5px; border:1px solid #3a4149;">
                    <label style="display:flex; align-items:center; cursor:pointer; font-weight:bold; color:var(--info); font-size:14px;">
                        <input type="checkbox" id="master-check-${catId}" style="margin-right:10px; width:18px; height:18px;" onchange="toggleCategoryMaster(this, ${catId})">
                        Selecionar Todos desta Pasta
                    </label>
                </div>
            `;

            items.forEach(item => {
                const isChecked = selectedSet.has(item.i);
                html += `
                    <label class="media-item">
                        <input type="checkbox" class="media-check-${catId}" value="${item.i}" ${isChecked ? 'checked' : ''} onchange="toggleItem(${item.i}, ${catId}, this.checked)">
                        ${item.n}
                    </label>
                `;
            });
            
            document.getElementById('mediaList').innerHTML = html;
            syncMasterCheckbox(catId);
        }

        // Quando clica em um canal individualmente
        function toggleItem(id, catId, isChecked) {
            if (isChecked) selectedSet.add(id);
            else selectedSet.delete(id);
            
            updateCategoryUI(catId);
            syncMasterCheckbox(catId);
        }

        // Quando clica no checkbox da Categoria (Lista da Esquerda)
        function toggleCategory(event, catId) {
            event.stopPropagation(); // Não deixa abrir a aba ao clicar no quadradinho
            const isChecked = event.target.checked;
            const items = mediaByCat[catId] || [];
            
            items.forEach(item => {
                if (isChecked) selectedSet.add(item.i);
                else selectedSet.delete(item.i);
            });
            
            if (currentCatOpen === catId) {
                document.querySelectorAll(`.media-check-${catId}`).forEach(cb => cb.checked = isChecked);
                syncMasterCheckbox(catId);
            }
            updateCategoryUI(catId);
        }

        // Quando clica no checkbox Master (Lista da Direita)
        function toggleCategoryMaster(checkbox, catId) {
            const isChecked = checkbox.checked;
            const items = mediaByCat[catId] || [];
            
            items.forEach(item => {
                if (isChecked) selectedSet.add(item.i);
                else selectedSet.delete(item.i);
            });
            
            document.querySelectorAll(`.media-check-${catId}`).forEach(cb => cb.checked = isChecked);
            updateCategoryUI(catId);
        }

        // Atualiza a contagem e a caixinha da esquerda (Azul)
        function updateCategoryUI(catId) {
            const items = mediaByCat[catId] || [];
            let checkedCount = 0;
            items.forEach(item => { if(selectedSet.has(item.i)) checkedCount++; });
            
            const isAllChecked = (checkedCount === items.length && items.length > 0);
            
            const cb = document.getElementById(`check-cat-${catId}`);
            if(cb) cb.checked = isAllChecked;
            
            const badge = document.getElementById(`badge-cat-${catId}`);
            if(badge) badge.innerHTML = checkedCount > 0 ? `<span class="badge-count">${checkedCount} / ${items.length}</span>` : '';
        }

        function syncMasterCheckbox(catId) {
            const items = mediaByCat[catId] || [];
            let checkedCount = 0;
            items.forEach(item => { if(selectedSet.has(item.i)) checkedCount++; });
            const isAllChecked = (checkedCount === items.length && items.length > 0);
            
            const masterCb = document.getElementById(`master-check-${catId}`);
            if (masterCb) masterCb.checked = isAllChecked;
        }

        // Botões Globais de Marcar/Desmarcar TUDO
        function massSelect(action) {
            if (action === 'all') {
                Object.values(mediaByCat).forEach(items => {
                    items.forEach(item => selectedSet.add(item.i));
                });
            } else {
                selectedSet.clear();
            }
            
            renderCategories();
            if (currentCatOpen) loadMedia(currentCatOpen);
        }

        function preSubmit() {
            // Esconde toda a lista dentro do input json (Bypass do erro do PHP)
            document.getElementById('bouquet_data_json').value = JSON.stringify(Array.from(selectedSet));
            
            // Força o clique no botão escondido de submit
            document.getElementById('realSubmit').click();
        }
    </script>
</body>
</html>