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

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

// --- 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) {}
// --- FIM: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---

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

// Apenas Admin pode acessar
if ($role !== 'admin') { header("Location: dashboard.php"); exit; }

// Buscar créditos do usuário (Sidebar)
try {
    $user_credits = $pdo->query("SELECT credits FROM reg_users WHERE id = " . intval($user_id_logado))->fetchColumn() ?: 0;
} catch (Exception $e) { $user_credits = 0; }

// ==========================================
// LÓGICA DE CRUD E ORDENAÇÃO
// ==========================================

// 1. Adicionar / Editar Categoria
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'save_category') {
        $id = $_POST['cat_id'] ?? '';
        $name = $_POST['cat_name'];
        $type = $_POST['cat_type'];
        
        if (!empty($id)) {
            // Editar
            $stmt = $pdo->prepare("UPDATE stream_categories SET category_name = ?, category_type = ? WHERE id = ?");
            $stmt->execute([$name, $type, $id]);
        } else {
            // Adicionar (Pega a última ordem para jogar no final)
            $last_order = $pdo->query("SELECT MAX(cat_order) FROM stream_categories WHERE category_type = '$type'")->fetchColumn();
            $new_order = intval($last_order) + 1;
            
            $stmt = $pdo->prepare("INSERT INTO stream_categories (category_name, category_type, parent_id, cat_order) VALUES (?, ?, 0, ?)");
            $stmt->execute([$name, $type, $new_order]);
        }
        header("Location: categorias.php?msg=saved");
        exit;
    }
    
    // 2. Salvar Ordem (Recebe requisição AJAX do JavaScript)
    if ($_POST['action'] === 'save_order') {
        $orderData = json_decode($_POST['order_data'], true);
        if (is_array($orderData)) {
            foreach ($orderData as $item) {
                $stmt = $pdo->prepare("UPDATE stream_categories SET cat_order = ? WHERE id = ?");
                $stmt->execute([$item['order'], $item['id']]);
            }
        }
        echo "Ordem salva com sucesso!";
        exit;
    }
}

// 3. Excluir Categoria
if (isset($_GET['delete'])) {
    $id_del = intval($_GET['delete']);
    $pdo->prepare("DELETE FROM stream_categories WHERE id = ?")->execute([$id_del]);
    header("Location: categorias.php?msg=deleted");
    exit;
}

// 4. Buscar Categorias organizadas por Tipo e Ordem
$categories = ['live' => [], 'movie' => [], 'series' => []];
$stmt = $pdo->query("SELECT * FROM stream_categories ORDER BY category_type, cat_order ASC, id ASC");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $type = $row['category_type'];
    if (array_key_exists($type, $categories)) {
        $categories[$type][] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Categorias - <?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">
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
    <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 COMPLETA E PADRONIZADA */
        .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: 30px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .sidebar-header span { color: var(--accent); }
        
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(255, 255, 255, 0.05); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .user-info .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-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; border-left: 3px solid transparent; cursor: pointer; transition: 0.2s; position: relative; width: 100%; box-sizing: border-box; font-size: 15px;}
        .menu-item i:first-child { margin-right: 15px; width: 20px; text-align: center; color: var(--text-muted); font-size: 16px;}
        .menu-item:hover, .menu-item.active { background-color: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i { color: var(--accent); }
        
        /* Submenu */
        .submenu { display: none; background: #121519; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 14px; border-left: none; }
        .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; letter-spacing: 1px;}
        .logout-btn { padding: 15px; background-color: var(--danger); color: white; text-align: center; text-decoration: none; font-weight: bold; margin-top: auto;}

        /* Main Content */
        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; }
        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 15px 30px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); }
        
        .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); }

        .content-area { padding: 30px; width: 100%; box-sizing: border-box; max-width: 900px; margin: 0 auto; flex: 1;}
        
        .header-actions { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 10px; }
        .btn { padding: 12px 20px; border-radius: 6px; font-weight: bold; cursor: pointer; border: none; color: white; display: inline-flex; align-items: center; gap: 8px; font-size: 14px; text-decoration: none; transition: 0.2s;}
        .btn-primary { background: var(--accent); }
        .btn-primary:hover { filter: brightness(0.85); }
        .btn-success { background: var(--success); }
        .btn-success:hover { background: #218838; }
        .btn-danger { background: var(--danger); padding: 8px 12px; font-size: 12px; }
        .btn-edit { background: var(--warning); padding: 8px 12px; font-size: 12px; }

        .tabs { display: flex; background: var(--bg-sidebar); border-radius: 8px; overflow: hidden; margin-bottom: 25px; border: 1px solid var(--border-color); }
        .tab-btn { flex: 1; padding: 15px; text-align: center; background: none; border: none; color: var(--text-muted); font-weight: bold; cursor: pointer; transition: 0.3s; font-size: 15px; }
        .tab-btn.active { background: var(--accent); color: white; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }

        .category-list { list-style: none; padding: 0; margin: 0; }
        .category-item { background: var(--bg-card); border: 1px solid var(--border-color); margin-bottom: 10px; padding: 15px 20px; border-radius: 8px; display: flex; align-items: center; justify-content: space-between; transition: 0.2s; }
        .category-item.sortable-ghost { opacity: 0.4; background: #2c3138; border: 1px dashed var(--accent); }
        
        .cat-info { display: flex; align-items: center; gap: 15px; flex: 1; }
        
        .drag-handle { 
            color: var(--text-muted); 
            cursor: grab; 
            font-size: 22px; 
            padding: 10px 15px 10px 0; 
            touch-action: none; 
            -webkit-user-select: none; 
            user-select: none;
        }
        .drag-handle:active { cursor: grabbing; color: var(--accent); }

        .cat-name { font-weight: bold; font-size: 15px; color: white; word-break: break-word; }
        .cat-actions { display: flex; gap: 8px; }

        .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: 90%; max-width: 400px; margin: 10% auto; padding: 25px; border-radius: 12px; border: 1px solid var(--border-color); }
        .form-control { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 6px; margin-bottom: 15px; box-sizing: border-box; }
        
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 24px; cursor: pointer; }
        .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) {
            .sidebar { position: fixed; left: -260px; height: 100%; }
            .sidebar.active { left: 0; }
            .menu-toggle { display: block; margin-right: 15px; }
            .sidebar-overlay.active { display: block; }
            .tab-btn { font-size: 13px; padding: 12px 5px; }
            .topbar { padding: 15px 20px; justify-content: flex-start; gap: 10px; }
            .topbar-right { margin-left: auto; }
            .topbar h2 { display: none; }
            .content-area { padding: 15px; }
            .modal-content { width: 90%; }
        }
    </style>
</head>
<body>
    <div class="sidebar-overlay" id="sidebarOverlay"></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>
            <span class="badge">Administrador</span>
            <div class="credits-badge"><i class="fas fa-coins"></i> Saldo: <?php echo number_format($user_credits, 1); ?></div>
        </div>
        
        <div class="menu-list">
            <a href="dashboard.php" class="menu-item active"><i class="fas fa-chart-line"></i> Dashboard</a>
            <a href="perfil.php" class="menu-item active"><i class="fas fa-user-circle"></i> Meu Perfil</a>
            
            <a href="lancamentos.php" class="menu-item active"><i class="fas fa-fire"></i> Últimos Adicionados</a>
            
            <a href="ajuda.php" class="menu-item active"><i class="fas fa-question-circle"></i> Material de Ajuda</a>
            <a href="meus_links.php" class="menu-item active"><i class="fas fa-link" style="color: var(--accent);"></i> Central de Links</a>
            
            <div class="menu-category">Gestão</div>
            <a href="clientes.php" class="menu-item active"><i class="fas fa-users"></i> Clientes IPTV</a>
            <a href="testes.php" class="menu-item active"><i class="fas fa-vial"></i> Gerenciar Testes</a>
            <a href="online.php" class="menu-item active"><i class="fas fa-plug"></i> Clientes Online</a>
            <a href="revendedores.php" class="menu-item active"><i class="fas fa-user-tie"></i> Revendedores</a>
            <a href="migrar_clientes.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Migrar Clientes</a>
            <a href="logs_creditos.php" class="menu-item active"><i class="fas fa-list-alt"></i> Extrato de Créditos</a>
            <a href="marketing.php" class="menu-item active"><i class="fas fa-bullhorn"></i> Central de Marketing</a>
            
            
            <div class="menu-category">Clientes P2P</div>
            <a href="p2p_clientes.php" class="menu-item active"><i class="fas fa-tv"></i> Clientes P2P</a>
            
            <?php if (!empty($api_conf['api_binstream_url'])): ?>
                <a href="binstream_p2p.php" class="menu-item active"><i class="fas fa-tv"></i> Binstream P2P</a>
            <?php endif; ?>

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

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


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

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

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

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

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

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

    <div class="main-content">
        <header class="topbar">
            <div style="display:flex; align-items:center;">
                <button class="menu-toggle" id="btnMenu"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; color: white;">Categorias</h2>
            </div>
            
            <div class="topbar-right">
                <?php 
                    $modo_atual = defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : 'INTERNO';
                    $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>
        </header>

        <div class="content-area">
            <div class="header-actions">
                <button class="btn btn-primary" onclick="openModal()"><i class="fas fa-plus"></i> Nova Categoria</button>
                <button class="btn btn-success" onclick="salvarOrdemGeral()"><i class="fas fa-save"></i> Salvar Ordem</button>
            </div>

            <div class="tabs">
                <button class="tab-btn active" onclick="switchTab('live')"><i class="fas fa-tv"></i> Canais</button>
                <button class="tab-btn" onclick="switchTab('movie')"><i class="fas fa-film"></i> Filmes</button>
                <button class="tab-btn" onclick="switchTab('series')"><i class="fas fa-video"></i> Séries</button>
            </div>

            <?php 
            $tipos = ['live' => 'Canais', 'movie' => 'Filmes', 'series' => 'Séries'];
            foreach ($tipos as $tipo_key => $tipo_nome): 
            ?>
            <div id="tab-<?php echo $tipo_key; ?>" class="tab-content <?php echo $tipo_key == 'live' ? 'active' : ''; ?>">
                <ul class="category-list" id="list-<?php echo $tipo_key; ?>" data-type="<?php echo $tipo_key; ?>">
                    <?php 
                    if(isset($categories[$tipo_key])) {
                        foreach ($categories[$tipo_key] as $cat): 
                            $nome_cat = mb_convert_encoding($cat['category_name'], "UTF-8", "auto");
                            $json_cat = htmlspecialchars(json_encode(['id' => $cat['id'], 'name' => $nome_cat, 'type' => $cat['category_type']]), ENT_QUOTES, 'UTF-8');
                    ?>
                    <li class="category-item" data-id="<?php echo $cat['id']; ?>">
                        <div class="cat-info">
                            <i class="fas fa-grip-lines drag-handle" title="Arraste para reordenar"></i>
                            <span class="cat-name"><?php echo htmlspecialchars($nome_cat); ?></span>
                        </div>
                        <div class="cat-actions">
                            <button class="btn btn-edit" title="Editar" onclick='editModal(<?php echo $json_cat; ?>)'><i class="fas fa-edit"></i></button>
                            <a href="?delete=<?php echo $cat['id']; ?>" title="Excluir" class="btn btn-danger" onclick="return confirm('ATENÇÃO: Ao excluir uma categoria, todo o conteúdo vinculado a ela ficará sem classificação. Deseja continuar?')"><i class="fas fa-trash"></i></a>
                        </div>
                    </li>
                    <?php 
                        endforeach; 
                    } else {
                        echo "<p style='color: var(--text-muted); padding: 15px;'>Nenhuma categoria encontrada.</p>";
                    }
                    ?>
                </ul>
            </div>
            <?php endforeach; ?>
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <div id="catModal" class="modal">
        <div class="modal-content">
            <h3 id="modalTitle" style="margin-top:0; color: white;">Nova Categoria</h3>
            <form method="POST" action="categorias.php">
                <input type="hidden" name="action" value="save_category">
                <input type="hidden" name="cat_id" id="m_id">
                
                <label style="font-size: 13px; color: var(--text-muted); font-weight: bold; margin-bottom: 5px; display: block;">Nome da Categoria</label>
                <input type="text" name="cat_name" id="m_name" class="form-control" required>
                
                <label style="font-size: 13px; color: var(--text-muted); font-weight: bold; margin-bottom: 5px; display: block;">Tipo de Conteúdo</label>
                <select name="cat_type" id="m_type" class="form-control" required>
                    <option value="live">Canais Ao Vivo</option>
                    <option value="movie">Filmes (VOD)</option>
                    <option value="series">Séries</option>
                </select>
                
                <button type="submit" class="btn btn-primary" style="width:100%; margin-top:10px; justify-content:center; padding: 15px;">SALVAR CATEGORIA</button>
                <button type="button" class="btn" style="width:100%; background:none; color:var(--text-muted); margin-top:5px; justify-content:center;" onclick="closeModal()">Cancelar</button>
            </form>
        </div>
    </div>

    <form id="orderForm" method="POST" style="display:none;">
        <input type="hidden" name="action" value="save_order">
        <input type="hidden" name="order_data" id="orderDataInput">
    </form>

    <script>
        const btnMenu = document.getElementById('btnMenu');
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebarOverlay');
        btnMenu.onclick = () => { sidebar.classList.toggle('active'); overlay.classList.toggle('active'); };
        overlay.onclick = () => { sidebar.classList.remove('active'); overlay.classList.remove('active'); };

        function toggleSubmenu(id) {
            const sub = document.getElementById(id);
            const arrow = document.getElementById('arrow-' + id);
            
            if (sub.style.display === "block" || sub.style.display === "") {
                sub.style.display = "none";
                arrow.classList.remove('rotate');
            } else {
                sub.style.display = "block";
                arrow.classList.add('rotate');
            }
        }

        let currentTab = 'live';
        function switchTab(tabId) {
            currentTab = tabId;
            document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
            document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
            document.getElementById('tab-' + tabId).classList.add('active');
            event.currentTarget.classList.add('active');
        }

        const modal = document.getElementById('catModal');
        function openModal() {
            document.getElementById('modalTitle').innerText = "Nova Categoria";
            document.getElementById('m_id').value = "";
            document.getElementById('m_name').value = "";
            document.getElementById('m_type').value = currentTab;
            modal.style.display = 'block';
        }
        function editModal(data) {
            document.getElementById('modalTitle').innerText = "Editar Categoria";
            document.getElementById('m_id').value = data.id;
            document.getElementById('m_name').value = data.name;
            document.getElementById('m_type').value = data.type;
            modal.style.display = 'block';
        }
        function closeModal() { modal.style.display = 'none'; }

        const lists = ['list-live', 'list-movie', 'list-series'];
        lists.forEach(listId => {
            const el = document.getElementById(listId);
            if(el) {
                new Sortable(el, {
                    handle: '.drag-handle',
                    animation: 150,
                    ghostClass: 'sortable-ghost',
                    delay: 200, 
                    delayOnTouchOnly: true,
                    touchStartThreshold: 5 
                });
            }
        });

        function salvarOrdemGeral() {
            const activeList = document.getElementById('list-' + currentTab);
            const items = activeList.querySelectorAll('li.category-item');
            let orderArray = [];
            items.forEach((item, index) => {
                orderArray.push({ id: item.getAttribute('data-id'), order: index });
            });
            if(orderArray.length === 0) return;

            document.getElementById('orderDataInput').value = JSON.stringify(orderArray);
            const formData = new FormData(document.getElementById('orderForm'));

            fetch('categorias.php', { method: 'POST', body: formData })
            .then(r => r.text())
            .then(d => alert("A nova ordem das categorias foi salva com sucesso!"))
            .catch(e => alert("Erro ao salvar a ordem."));
        }
    </script>
</body>
</html>