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

// Inicia um buffer para evitar que erros silenciosos quebrem o JSON do AJAX
ob_start();

session_start();
require_once 'config.php'; 

$pdo = getConexaoAtiva(); // Banco Principal
$pdo_int = getConexaoInterna(); // Banco Local

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

// ====================================================================
// INTELIGÊNCIA ARTIFICIAL: DETECTA SE É XUI ONE OU XTREAM UI
// ====================================================================
$modo_ativo = 'interno';
try {
    $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno';
} catch (Exception $e) {}

// =================================================================================
// --- LÓGICA AJAX PARA CARREGAMENTO RÁPIDO DO BOUQUET (SEM TRAVAR A TELA) ---
// =================================================================================
if (isset($_GET['ajax_get_bouquet'])) {
    ob_clean(); // Limpa qualquer output anterior
    header('Content-Type: application/json; charset=utf-8');
    error_reporting(0); // Evita notices no JSON
    
    $id = intval($_GET['ajax_get_bouquet']);
    
    // MODO INTELIGENTE: Puxa e funde as arrays se for XUI ONE
    if ($modo_ativo === 'xui') {
        $stmt = $pdo->prepare("SELECT bouquet_channels, bouquet_movies, bouquet_series FROM bouquets WHERE id = ?");
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($row) {
            $c = json_decode($row['bouquet_channels'] ?? '[]', true) ?: [];
            $m = json_decode($row['bouquet_movies'] ?? '[]', true) ?: [];
            $s = json_decode($row['bouquet_series'] ?? '[]', true) ?: [];
            
            $c = array_map('intval', $c);
            $m = array_map('intval', $m);
            // Transforma o ID da série num número negativo para o JS não confundir com o ID do filme!
            $s_negative = array_map(function($s_id) { return -abs((int)$s_id); }, $s);
            
            $todas_midias = array_merge($c, $m, $s_negative);
            echo json_encode(array_values(array_unique($todas_midias)));
        } else {
            echo '[]';
        }
    } else {
        $stmt = $pdo->prepare("SELECT bouquet_channels FROM bouquets WHERE id = ?");
        $stmt->execute([$id]);
        $channels = json_decode($stmt->fetchColumn() ?? '[]', true) ?: [];
        echo json_encode(array_map('intval', $channels));
    }
    exit;
}

ob_end_flush(); // Libera o buffer para o HTML

// --- 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'];
    
    $json_bruto = $_POST['bouquet_data_json'] ?? '[]';
    $midias_selecionadas = json_decode($json_bruto, true) ?: [];

    if ($modo_ativo === 'xui') {
        $canais_finais = [];
        $filmes_finais = [];
        $series_finais = [];
        
        // Reconstrói o mapa de tipos para saber onde salvar cada mídia
        $mapa_tipos = [];
        $all_streams = $pdo->query("SELECT id, type FROM streams")->fetchAll(PDO::FETCH_ASSOC);
        foreach($all_streams as $s) {
            $mapa_tipos[$s['id']] = (int)$s['type'];
        }

        foreach($midias_selecionadas as $midia_id) {
            $midia_id_int = (int)$midia_id;
            
            // Se for negativo, sabemos que é uma série graças ao truque!
            if ($midia_id_int < 0) {
                $series_finais[] = abs($midia_id_int); // Salva como INTEIRO puro
            } else {
                $tipo = $mapa_tipos[$midia_id_int] ?? 1;
                // Type 1, 3 e 4 normalmente são Live, Type 2 é VOD
                if ($tipo == 1 || $tipo == 3 || $tipo == 4) $canais_finais[] = $midia_id_int;
                elseif ($tipo == 2) $filmes_finais[] = $midia_id_int;
                else $canais_finais[] = $midia_id_int; // Fallback
            }
        }
        
        // json_encode de arrays de inteiros gera [1,2,3] (Formato exigido pelo XUI ONE)
        $json_c = json_encode(array_values(array_unique($canais_finais)));
        $json_m = json_encode(array_values(array_unique($filmes_finais)));
        $json_s = json_encode(array_values(array_unique($series_finais)));
        $json_r = '[]'; // Rádios vazio para não dar conflito

        if (!empty($id)) {
            $sql = "UPDATE bouquets SET bouquet_name=?, bouquet_channels=?, bouquet_movies=?, bouquet_series=?, bouquet_radios=?, bouquet_order=? WHERE id=?";
            $pdo->prepare($sql)->execute([$name, $json_c, $json_m, $json_s, $json_r, $order, $id]);
        } else {
            $sql = "INSERT INTO bouquets (bouquet_name, bouquet_channels, bouquet_movies, bouquet_series, bouquet_radios, bouquet_order) VALUES (?, ?, ?, ?, ?, ?)";
            $pdo->prepare($sql)->execute([$name, $json_c, $json_m, $json_s, $json_r, $order]);
        }
    } else {
        // Xtream UI padrão: tudo numa coluna só
        $todas_str = array_map('strval', $midias_selecionadas);
        $json_tudo = json_encode(array_values(array_unique($todas_str)));
        
        if (!empty($id)) {
            $sql = "UPDATE bouquets SET bouquet_name=?, bouquet_channels=?, bouquet_order=? WHERE id=?";
            $pdo->prepare($sql)->execute([$name, $json_tudo, $order, $id]);
        } else {
            $sql = "INSERT INTO bouquets (bouquet_name, bouquet_channels, bouquet_order) VALUES (?, ?, ?)";
            $pdo->prepare($sql)->execute([$name, $json_tudo, $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;
}


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

try {
    $tabela_existe = $pdo_int->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_p = $pdo_int->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_int->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 (COM TRADUTOR DE ARRAYS) ---
// =================================================================================
$tabela_categorias = ($modo_ativo === 'xui') ? '`streams_categories`' : '`stream_categories`';
$categories = $pdo->query("SELECT id, category_name FROM $tabela_categorias ORDER BY category_name ASC")->fetchAll(PDO::FETCH_ASSOC);

// Puxa canais e filmes
$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 = [];

// Função auxiliar para quebrar a matriz de categoria do XUI ONE
function parseCategoryIds($cat_val) {
    if ($cat_val === null || $cat_val === '') return [];
    $cat_val = trim((string)$cat_val);
    if (strpos($cat_val, '[') === 0) {
        $arr = json_decode($cat_val, true);
        if (is_array($arr)) return array_map('intval', $arr);
    }
    return [(int)$cat_val];
}

foreach($all_media as $item) { 
    $cids = parseCategoryIds($item['category_id']);
    foreach($cids as $cid) {
        if ($cid > 0) {
            $media_by_cat[$cid][] = ['i' => (int)$item['id'], 'n' => $item['name']]; 
        }
    }
}

// Se for XUI ONE, busca as Séries também e joga os IDs como negativos (para o JS não confundir)
if ($modo_ativo === 'xui') {
    try {
        $all_series = $pdo->query("SELECT id, title as name, category_id FROM streams_series ORDER BY title ASC")->fetchAll(PDO::FETCH_ASSOC);
        foreach($all_series as $item) {
            $cids = parseCategoryIds($item['category_id']);
            $neg_id = -abs((int)$item['id']);
            foreach($cids as $cid) {
                if ($cid > 0) {
                    $media_by_cat[$cid][] = ['i' => $neg_id, 'n' => $item['name']]; 
                }
            }
        }
    } catch (Exception $e) {}
}
// =================================================================================

// OTIMIZAÇÃO: Na lista da tela inicial, NÃO puxamos a coluna bouquet_channels
$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>
    <link rel="stylesheet" href="tema.css">
    <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; }
        
        /* CSS OBRIGATÓRIO PARA A LOGO E MENU */
        .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 { width: 100%; max-width: 180px; height: auto; max-height: 60px; object-fit: contain; display: block; margin: 0 auto; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(0, 123, 255, 0.2); 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; }
        .menu-category { padding: 20px 20px 8px; font-size: 11px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .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); }
        .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; }
        
        .mode-badge { padding: 6px 15px; border-radius: 20px; font-size: 12px; font-weight: bold; white-space: nowrap; display: inline-block; }
        .badge-interno { background: rgba(40, 167, 69, 0.15); color: var(--success); border: 1px solid var(--success); }
        .badge-externo { background: rgba(243, 156, 18, 0.15); color: var(--warning); border: 1px solid var(--warning); }

        .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 */
        .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; margin-right: 15px; }
            .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; }
            .topbar { padding: 15px 20px; justify-content: flex-start; gap: 10px; }
            .topbar-right { margin-left: auto; }
            .topbar h2 { display: none; }
            .content-area { padding: 15px; padding-bottom: 120px; }
        }
    </style>
</head>
<body>
    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>
    
    <?php include 'sidebar.php'; ?>

    <div class="main-content">
        <header class="topbar">
            <div style="display:flex; justify-content:space-between; align-items:center; width: 100%;">
                <div style="display:flex; align-items:center;">
                    <button class="menu-toggle" id="btnMenu" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                    <h2 style="margin:0; color: white; margin-left: 10px;">Bouquets</h2>
                </div>
                
                <div class="topbar-right">
                    <?php 
                        $modo_atual = defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : strtoupper($modo_ativo);
                        $classe_modo = ($modo_atual === 'INTERNO') ? 'badge-interno' : 'badge-externo';
                        $icone_modo = ($modo_atual === 'INTERNO') ? 'fa-database' : 'fa-globe';
                    ?>
                    <span class="mode-badge <?php echo $classe_modo; ?>">
                        <i class="fas <?php echo $icone_modo; ?>"></i> MODO: <?php echo $modo_atual; ?>
                    </span>
                </div>
            </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>
        function toggleMenu() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('overlay').classList.toggle('active'); 
        }

        // 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>
    <script src="tema.js"></script>
</body>
</html>