<?php
// Força UTF-8 e verifica sessão
header('Content-Type: text/html; charset=utf-8');
session_start();
require_once 'includes/db.php';
if (!isset($_SESSION['logged_in_fxtream'])) { header('Location: index.php'); exit; }
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Gerenciador de Limpeza</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/style.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/dark-theme.css">
    
    <style>
        body { background-color: #121212; color: #e0e0e0; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        .card { background-color: #1e1e1e; border: 1px solid #333; }
        
        /* Botão Perigoso */
        .btn-nuke { background-color: #dc3545; color: white; font-weight: bold; padding: 15px; width: 100%; border: 1px solid #ff0000; box-shadow: 0 0 10px rgba(255,0,0,0.3); transition: all 0.3s; }
        .btn-nuke:hover { background-color: #ff0000; box-shadow: 0 0 20px rgba(255,0,0,0.6); transform: scale(1.02); }

        .table { color: #ddd; }
        .table td, .table th { vertical-align: middle; border-top: 1px solid #333; }
        
        .badge-type { width: 80px; }
        .search-box { background: #2c2c2c; border: 1px solid #444; color: white; }
        .search-box:focus { background: #333; color: white; border-color: #007bff; }

        /* ============================================================
           LAYOUT RESPONSIVO (SIDEBAR + CONTEÚDO)
           ============================================================ */
        
        /* PC (Telas Grandes) */
        @media (min-width: 992px) {
            #sidebar { 
                display: block !important; 
                width: 240px; 
                position: fixed; top: 0; left: 0; height: 100vh; 
                z-index: 1000; overflow-y: auto; 
            }
            .right-column { 
                margin-left: 240px; 
                width: calc(100% - 240px); 
                padding: 0;
            }
            .btn-voltar-mobile { display: none; }
        }

        /* CELULAR (Telas Pequenas) */
        @media (max-width: 991px) {
            #sidebar { display: none !important; }
            .right-column { 
                margin-left: 0 !important; 
                width: 100% !important; 
                padding: 0;
            }
            .btn-voltar-mobile {
                display: inline-block;
                margin-right: 10px;
                color: #fff;
                font-size: 1.2rem;
            }
        }

        /* Cabeçalho Customizado */
        .page-header {
            padding: 20px; 
            border-bottom: 1px solid #333; 
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #1e1e1e;
        }
    </style>
</head>
<body>

<div class="container-fluid p-0">
    <div class="row no-gutters">
        
        <?php include 'includes/sidebar.php'; ?>

        <div class="right-column">

            <div class="page-header sticky-top">
                <div class="d-flex align-items-center">
                    <a href="dashboard.php" class="btn-voltar-mobile"><i class="fa fa-arrow-left"></i></a>
                    <h3 class="m-0 h4"><i class="fa fa-trash-alt text-danger mr-2"></i> Gerenciador de Conteúdo</h3>
                </div>
                <a href="dashboard.php" class="btn btn-secondary btn-sm d-none d-lg-inline-block"><i class="fa fa-arrow-left"></i> Voltar</a>
            </div>

            <div class="container-fluid px-4 pb-5">
                
                <div class="card mb-5 border-danger shadow-lg">
                    <div class="card-header bg-danger text-white font-weight-bold">
                        <i class="fa fa-radiation-alt mr-2"></i> ZONA DE PERIGO
                    </div>
                    <div class="card-body text-center p-4">
                        <h5 class="text-white mb-3">Limpeza Total do Sistema</h5>
                        <p class="mb-1">Esta ação apagará <strong>TODOS</strong> os Canais, Filmes, Séries, Episódios e Categorias do banco de dados.</p>
                        <p class="text-muted small mb-4">Clientes, Revendedores e Configurações NÃO serão afetados.</p>
                        
                        <button class="btn btn-nuke btn-lg" onclick="wipeAll()">
                            <i class="fa fa-bomb fa-lg mr-2"></i> APAGAR TUDO (RESET TOTAL)
                        </button>
                    </div>
                </div>

                <div class="card shadow">
                    <div class="card-header bg-dark d-flex justify-content-between align-items-center py-3 flex-wrap">
                        <h5 class="mb-0 text-white mr-3"><i class="fa fa-list mr-2"></i> Excluir por Categoria</h5>
                        <input type="text" id="searchCat" class="form-control form-control-sm search-box mt-2 mt-md-0" style="max-width: 250px;" placeholder="Buscar categoria...">
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive" style="max-height: 600px; overflow-y: auto;">
                            <table class="table table-hover mb-0">
                                <thead class="bg-secondary text-white">
                                    <tr>
                                        <th class="pl-4">Nome da Categoria</th>
                                        <th class="text-center">Tipo</th>
                                        <th class="text-center">Conteúdos</th>
                                        <th class="text-right pr-4">Ação</th>
                                    </tr>
                                </thead>
                                <tbody id="catTableBody">
                                    <tr><td colspan="4" class="text-center py-5"><i class="fa fa-circle-notch fa-spin fa-3x text-muted"></i><p class="mt-2 text-muted">Carregando...</p></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

            </div> </div> </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://vendedorp2p.com/views/_plugins/bootbox.min.js"></script>

<script>
    $(document).ready(function() {
        loadCategories();

        // Filtro de busca em tempo real
        $("#searchCat").on("keyup", function() {
            var value = $(this).val().toLowerCase();
            $("#catTableBody tr").filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
            });
        });
    });

    // 1. CARREGAR LISTA
    function loadCategories() {
        $.post('api/manager_api.php', { action: 'list_categories' }, function(data) {
            let html = '';
            
            if(!data || data.length === 0) {
                html = '<tr><td colspan="4" class="text-center text-muted py-5"><h5>Nenhuma categoria encontrada.</h5></td></tr>';
            } else {
                data.forEach(c => {
                    let badge = 'badge-secondary';
                    let typeLabel = 'Outro';
                    
                    if(c.type == 'channel') { badge = 'badge-primary'; typeLabel = 'Canais'; }
                    if(c.type == 'movie') { badge = 'badge-success'; typeLabel = 'Filmes'; }
                    if(c.type == 'series') { badge = 'badge-warning'; typeLabel = 'Séries'; }

                    html += `
                    <tr>
                        <td class="font-weight-bold pl-4">${c.name}</td>
                        <td class="text-center"><span class="badge ${badge} badge-type p-2">${typeLabel}</span></td>
                        <td class="text-center font-weight-bold text-white" style="font-size:1.1em">${c.count}</td>
                        <td class="text-right pr-4">
                            <button class="btn btn-sm btn-outline-danger font-weight-bold" onclick="deleteCategory(${c.id}, '${c.type}', '${escapeHtml(c.name)}', ${c.count})">
                                <i class="fa fa-trash mr-1"></i> EXCLUIR
                            </button>
                        </td>
                    </tr>`;
                });
            }
            $('#catTableBody').html(html);
        }, 'json').fail(function() {
            toastr.error("Erro ao carregar categorias.");
        });
    }

    // 2. APAGAR CATEGORIA (E TUDO DENTRO)
    function deleteCategory(id, type, name, count) {
        bootbox.confirm({
            title: "<span class='text-danger'>CONFIRMAÇÃO DE EXCLUSÃO</span>",
            message: `
                <div class='text-center'>
                    <i class='fa fa-exclamation-circle fa-4x text-warning mb-3'></i><br>
                    Você vai apagar a categoria <b>${name}</b> e todos os <b>${count}</b> conteúdos dentro dela.<br><br>
                    <span class='text-danger font-weight-bold'>Essa ação é irreversível!</span>
                </div>
            `,
            buttons: {
                confirm: { label: '<i class="fa fa-trash"></i> SIM, APAGAR', className: 'btn-danger' },
                cancel: { label: 'CANCELAR', className: 'btn-secondary' }
            },
            callback: function (result) {
                if(result) {
                    let loadingBox = bootbox.dialog({ message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Apagando...</div>', closeButton: false });
                    
                    $.post('api/manager_api.php', { 
                        action: 'delete_category', 
                        id: id, 
                        type: type 
                    }, function(res){
                        loadingBox.modal('hide');
                        if(res.status) {
                            toastr.success(res.msg);
                            loadCategories();
                        } else {
                            toastr.error(res.msg);
                        }
                    }, 'json');
                }
            }
        });
    }

    // 3. WIPE ALL (RESET TOTAL)
    function wipeAll() {
        bootbox.confirm({
            title: "<span class='text-danger font-weight-bold'><i class='fa fa-radiation-alt'></i> ZONA DE PERIGO</span>",
            message: `
                <div class='text-center'>
                    <i class='fa fa-bomb fa-4x text-danger mb-3'></i><br>
                    <h3>TEM CERTEZA ABSOLUTA?</h3>
                    <p class='lead'>Isso vai apagar <b>TODOS</b> os canais, filmes, séries, temporadas, episódios e categorias.</p>
                    <p class='text-muted'>O painel ficará limpo, mantendo apenas os clientes.</p>
                </div>
            `,
            buttons: {
                confirm: { label: 'SIM, ZERAR TUDO', className: 'btn-danger btn-lg font-weight-bold' },
                cancel: { label: 'CANCELAR', className: 'btn-secondary btn-lg' }
            },
            callback: function (result) {
                if(result) {
                    let loadingBox = bootbox.dialog({ message: '<div class="text-center"><i class="fa fa-spin fa-spinner fa-3x"></i><br><h3>Limpando Banco de Dados...</h3></div>', closeButton: false });
                    
                    $.post('api/manager_api.php', { action: 'wipe_all' }, function(res){
                        loadingBox.modal('hide');
                        if(res.status) {
                            toastr.success(res.msg);
                            loadCategories();
                        } else {
                            toastr.error(res.msg);
                        }
                    }, 'json');
                }
            }
        });
    }

    function escapeHtml(text) {
        return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
    }
</script>

</body>
</html>