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

$pdo = getConexaoAtiva(); // Banco Principal (Xtream ou XUI)
$pdo_int = getConexaoInterna(); // Banco Local (Configs)

$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) {}

// O XUI One usa a tabela no plural (streams_categories)
$tabela_categorias = ($modo_ativo === 'xui') ? '`streams_categories`' : '`stream_categories`';

// --- 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) {}
// --- 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_int->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 $tabela_categorias 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 $tabela_categorias WHERE category_type = '$type'")->fetchColumn();
            $new_order = intval($last_order) + 1;
            
            $stmt = $pdo->prepare("INSERT INTO $tabela_categorias (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 $tabela_categorias 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 $tabela_categorias 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 $tabela_categorias 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>
    <link rel="stylesheet" href="tema.css">
    <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; }
        
        /* CSS OBRIGATÓRIO PARA A LOGO E MENU (Evita o bug da logo gigante) */
        .sidebar { width: 260px; background-color: var(--bg-sidebar); border-right: 1px solid var(--border-color); display: flex; flex-direction: column; z-index: 1001; transition: 0.3s; 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; transition: 0.2s; border-left: 3px solid transparent; font-size: 15px; cursor: pointer; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background-color: #2c3138; color: white; border-left-color: var(--accent); }
        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 13px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 11px; }
        .rotate { transform: rotate(180deg); }
        .logout-btn { padding: 15px; background-color: #dc3545; color: white; text-align: center; text-decoration: none; font-weight: bold; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }

        /* Main Content */
        .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 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; }
        
      
        /* ==================================================================== */
        /* FORÇA A COR AZUL NO ADMINISTRADOR E VERDE NO SALDO */
        /* ==================================================================== */
        .user-info > div:nth-child(2), .user-info .badge { background: rgba(0, 123, 255, 0.2) !important; color: var(--accent) !important; padding: 4px 10px !important; border-radius: 4px !important; font-size: 11px !important; text-transform: uppercase !important; font-weight: bold !important; margin-top: 5px !important; margin-bottom: 5px !important; display: inline-block !important; }
        .user-info > div:nth-child(3), .user-info .credits-badge, .user-info i.fa-coins { color: var(--success) !important; font-weight: bold !important; font-size: 13px !important; display: inline-block !important; }
        .user-info > div:nth-child(3) { margin-top: 8px !important; display: block !important; }

        /* ==================================================================== */
        /* FORÇA OS ÍCONES DA SIDEBAR A FICAREM AZUIS */
        /* ==================================================================== */
        .sidebar i, .sidebar span[class*="icon"], .sidebar .fas, .sidebar .fab { color: var(--accent) !important; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--accent) !important; }
        .menu-item:hover, .menu-item.active { background-color: #2c3138 !important; color: white !important; border-left-color: var(--accent) !important; }
        .sidebar .active, .sidebar .menu-item.active, .sidebar li.active > a { border-left-color: var(--accent) !important; color: white !important; background: #24282d !important; }
        .sidebar a:hover, .sidebar .menu-item:hover { border-left-color: var(--accent) !important; color: white !important; background: #2c3138 !important; }
        
    
        @media (max-width: 768px) {
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .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="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;">Categorias</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-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>
        function toggleMenu() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('overlay').classList.toggle('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";
                if(arrow) arrow.classList.remove('rotate');
            } else {
                sub.style.display = "block";
                if(arrow) 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>
    <script src="tema.js"></script>
</body>
</html>