<?php
// categories.php - Com Sidebar e Responsivo
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>Gerenciar Categorias</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: #1a1c23; color: #fff; overflow-x: hidden; font-family: 'Segoe UI', sans-serif; }
        .card { background-color: #232730; border: 1px solid #333; }
        
        /* Lista Arrastável */
        .sortable-list { list-style: none; padding: 0; }
        .sortable-item {
            background-color: #2c2c2c;
            border: 1px solid #444;
            margin-bottom: 8px;
            padding: 12px 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: grab;
            border-radius: 4px;
            color: #e0e0e0;
        }
        .sortable-item:hover { background-color: #383838; }
        .sortable-item.sortable-ghost { opacity: 0.5; background-color: #007bff; }
        
        .drag-handle { color: #888; margin-right: 15px; cursor: grab; font-size: 1.2rem; }
        
        /* Botão Flutuante Salvar */
        #btnSaveOrder {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1050;
            display: none;
            box-shadow: 0 4px 15px rgba(0,0,0,0.6);
            border-radius: 50px;
            padding: 15px 30px;
        }

        /* Abas Estilizadas */
        .nav-tabs { border-bottom: 1px solid #444; }
        .nav-tabs .nav-link { color: #aaa; border: none; font-weight: bold; }
        .nav-tabs .nav-link:hover { color: #fff; }
        .nav-tabs .nav-link.active { color: #fff; background-color: #232730; border: 1px solid #333; border-bottom-color: #232730; }

        /* RESPONSIVIDADE DO LAYOUT (IGUAL AO CLIENTS.PHP) */
        @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; }
        }
        @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; }
        }
        
        .page-header { padding: 15px 20px; border-bottom: 1px solid #333; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; background-color: #1a1c23; }
        .modal-content { background-color: #232730; border: 1px solid #444; }
        .form-control { background-color: #1a1c23; border: 1px solid #444; color: #fff; }
        .form-control:focus { background-color: #1a1c23; color: #fff; border-color: #007bff; }
    </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>
                    <h4 class="mb-0 font-weight-bold text-white"><i class="fa fa-layer-group text-info mr-2"></i> Categorias</h4>
                </div>
                <div>
                    <button class="btn btn-success font-weight-bold btn-sm shadow-sm" onclick="openModal()">
                        <i class="fa fa-plus-circle"></i> <span class="d-none d-sm-inline">Nova</span>
                    </button>
                    <a href="dashboard.php" class="btn btn-secondary btn-sm d-none d-lg-inline-block ml-2">Voltar</a>
                </div>
            </div>

            <div class="container-fluid px-4 pb-5">
                
                <ul class="nav nav-tabs mb-3" id="catTabs">
                    <li class="nav-item">
                        <a class="nav-link active" data-type="channel" href="#"><i class="fa fa-tv text-primary"></i> Canais</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-type="movie" href="#"><i class="fa fa-film text-success"></i> Filmes</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-type="series" href="#"><i class="fa fa-video text-warning"></i> Séries</a>
                    </li>
                </ul>

                <div class="card shadow">
                    <div class="card-body p-0">
                        <div id="loading" class="text-center py-5">
                            <i class="fa fa-circle-notch fa-spin fa-3x text-info"></i>
                            <p class="mt-2 text-muted">Carregando...</p>
                        </div>
                        
                        <ul id="catList" class="sortable-list p-2">
                            </ul>
                    </div>
                </div>

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

<button id="btnSaveOrder" class="btn btn-warning btn-lg font-weight-bold text-dark" onclick="saveOrder()">
    <i class="fa fa-save"></i> SALVAR ORDEM
</button>

<div class="modal fade" id="catModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content shadow-lg">
            <div class="modal-header border-secondary">
                <h5 class="modal-title font-weight-bold" id="modalTitle">Nova Categoria</h5>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="editId">
                <div class="form-group">
                    <label>Nome da Categoria</label>
                    <input type="text" class="form-control" id="catName" placeholder="Ex: Filmes Ação">
                </div>
                <div class="form-group">
                    <label>Tipo</label>
                    <select class="form-control" id="catType" disabled>
                        <option value="channel">Canais</option>
                        <option value="movie">Filmes</option>
                        <option value="series">Séries</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer border-secondary">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary px-4 font-weight-bold" onclick="saveCategory()">Salvar</button>
            </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://cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.js"></script>

<script>
    var currentType = 'channel';
    var sortableInstance;

    $(document).ready(function() {
        loadCategories();

        // Troca de Abas
        $('.nav-link').click(function(e) {
            e.preventDefault();
            $('.nav-link').removeClass('active');
            $(this).addClass('active');
            
            currentType = $(this).data('type');
            loadCategories();
            $('#btnSaveOrder').fadeOut();
        });
    });

    function loadCategories() {
        $('#loading').show();
        $('#catList').hide();
        
        $.post('api/categories_api.php', { action: 'list', type: currentType }, function(data) {
            $('#catList').empty();
            
            if(!data || data.length === 0) {
                $('#catList').html('<div class="text-center text-muted p-5"><h5>Nenhuma categoria encontrada.</h5><button class="btn btn-sm btn-outline-info mt-2" onclick="openModal()">Criar Primeira</button></div>');
            } else {
                data.forEach(function(cat) {
                    let html = `
                    <li class="sortable-item" data-id="${cat.id}">
                        <div class="d-flex align-items-center">
                            <i class="fa fa-bars drag-handle p-2" title="Arraste para organizar"></i>
                            <span class="font-weight-bold ml-2" style="font-size: 1.1rem;">${cat.name}</span>
                        </div>
                        <div>
                            <button class="btn btn-sm btn-info mr-1" title="Editar" onclick="editCat(${cat.id}, '${escapeHtml(cat.name)}')"><i class="fa fa-pen"></i></button>
                            <button class="btn btn-sm btn-danger" title="Excluir" onclick="deleteCat(${cat.id})"><i class="fa fa-trash"></i></button>
                        </div>
                    </li>`;
                    $('#catList').append(html);
                });
            }

            $('#loading').hide();
            $('#catList').fadeIn();

            initSortable();

        }, 'json').fail(function() {
            toastr.error('Erro ao conectar com API.');
        });
    }

    // Inicializa Drag & Drop
    function initSortable() {
        var el = document.getElementById('catList');
        if(sortableInstance) sortableInstance.destroy();

        sortableInstance = new Sortable(el, {
            handle: '.drag-handle', // Só arrasta pelo ícone
            animation: 150,
            ghostClass: 'sortable-ghost',
            onEnd: function (evt) {
                $('#btnSaveOrder').fadeIn(); // Mostra botão salvar
            },
        });
    }

    // Salvar Ordem no Banco
    function saveOrder() {
        var order = sortableInstance.toArray(); 
        
        $.post('api/categories_api.php', { action: 'reorder', order: order }, function(res){
            if(res.status) {
                toastr.success('Ordem salva!');
                $('#btnSaveOrder').fadeOut();
            } else {
                toastr.error('Erro ao salvar: ' + res.msg);
            }
        }, 'json');
    }

    // --- FUNÇÕES CRUD ---

    function openModal() {
        $('#editId').val('');
        $('#catName').val('');
        $('#catType').val(currentType);
        $('#modalTitle').text('Nova Categoria (' + translateType(currentType) + ')');
        $('#catModal').modal('show');
        setTimeout(() => $('#catName').focus(), 500);
    }

    function editCat(id, name) {
        $('#editId').val(id);
        $('#catName').val(name);
        $('#catType').val(currentType);
        $('#modalTitle').text('Editar Categoria');
        $('#catModal').modal('show');
    }

    function saveCategory() {
        let id = $('#editId').val();
        let name = $('#catName').val();
        
        if(!name.trim()) { toastr.warning('Digite um nome!'); return; }

        $.post('api/categories_api.php', { 
            action: 'save', 
            id: id, 
            name: name, 
            type: currentType 
        }, function(res){
            if(res.status) {
                toastr.success('Salvo!');
                $('#catModal').modal('hide');
                loadCategories();
            } else {
                toastr.error(res.msg);
            }
        }, 'json');
    }

    function deleteCat(id) {
        if(confirm('Tem certeza absoluta?')) {
            $.post('api/categories_api.php', { action: 'delete', id: id }, function(res){
                if(res.status) {
                    toastr.success('Removido.');
                    loadCategories();
                } else {
                    toastr.error(res.msg);
                }
            }, 'json');
        }
    }

    function translateType(t) {
        if(t=='channel') return 'Canais';
        if(t=='movie') return 'Filmes';
        if(t=='series') return 'Séries';
        return t;
    }
    
    function escapeHtml(text) {
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
</script>

</body>
</html>