<?php
// mover.php - Com Sidebar e Layout Responsivo
session_start();
require_once 'includes/db.php';

// 1. Verifica se está logado
if (!isset($_SESSION['logged_in_fxtream'])) { header('Location: index.php'); exit; }

$current_user_id = $_SESSION['user_id'];

// 2. VERIFICAÇÃO DE SEGURANÇA
$is_admin = ($current_user_id == 1); 

if (!$is_admin) {
    try {
        $stmt = $pdo->prepare("SELECT role FROM revendedores WHERE id = ?");
        $stmt->execute([$current_user_id]);
        $role = $stmt->fetchColumn();
        if ($role === 'admin') $is_admin = true;
    } catch(Exception $e){}
}

// Se depois de tudo não for admin, redireciona
if (!$is_admin) { header('Location: dashboard.php'); exit; }
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Mover Conteúdo</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; }
        .form-control, .custom-select { background-color: #2c2c2c; border: 1px solid #444; color: white; }
        .form-control:focus { background-color: #333; border-color: #007bff; color: white; }
        .list-group-item { background-color: #252525; border-color: #333; color: #fff; cursor: pointer; }
        .list-group-item:hover { background-color: #303030; }
        .list-container { max-height: 500px; overflow-y: auto; }

        /* ============================================================
           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-exchange-alt text-warning mr-2"></i> Movimentador 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="row">
                    
                    <div class="col-md-12 col-lg-3 mb-4">
                        <div class="card shadow mb-3">
                            <div class="card-header bg-dark font-weight-bold">1. Configuração</div>
                            <div class="card-body">
                                <div class="form-group">
                                    <label>Tipo de Conteúdo</label>
                                    <select id="selectType" class="form-control">
                                        <option value="">Selecione...</option>
                                        <option value="live">Canais (Live)</option>
                                        <option value="movie">Filmes</option>
                                        <option value="series">Séries</option>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label>Categoria de <b class="text-danger">ORIGEM</b></label>
                                    <select id="selectSourceCat" class="form-control" disabled>
                                        <option value="">Aguardando tipo...</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="card shadow">
                            <div class="card-header bg-dark font-weight-bold">3. Destino</div>
                            <div class="card-body">
                                <div class="form-group">
                                    <label>Categoria de <b class="text-success">DESTINO</b></label>
                                    <select id="selectTargetCat" class="form-control" disabled>
                                        <option value="">Selecione origem...</option>
                                    </select>
                                </div>
                                <button id="btnMove" class="btn btn-warning btn-block font-weight-bold" disabled>
                                    <i class="fa fa-exchange-alt"></i> MOVER AGORA
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-12 col-lg-9">
                        <div class="card shadow h-100">
                            <div class="card-header bg-dark d-flex justify-content-between align-items-center flex-wrap">
                                <span class="font-weight-bold mr-3 mb-2 mb-md-0">2. Selecione os Itens</span>
                                <div class="d-flex align-items-center">
                                    <input type="text" id="searchBox" class="form-control form-control-sm d-inline-block" placeholder="Buscar..." style="width: 150px; margin-right: 5px;">
                                    <button class="btn btn-sm btn-outline-info ml-1" onclick="selectAll()">Todos</button>
                                    <button class="btn btn-sm btn-outline-secondary ml-1" onclick="deselectAll()">Nenhum</button>
                                </div>
                            </div>
                            <div class="card-body p-0">
                                <div id="contentList" class="list-group list-group-flush list-container">
                                    <div class="text-center py-5 text-muted">Selecione uma categoria de origem primeiro.</div>
                                </div>
                            </div>
                            <div class="card-footer bg-dark text-muted small">
                                <span id="countSelected">0</span> itens selecionados
                            </div>
                        </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/toastr.js/latest/toastr.min.js"></script>

<script>
    // 1. MUDANÇA DE TIPO (Carrega Categorias)
    $('#selectType').change(function(){
        let type = $(this).val();
        $('#selectSourceCat, #selectTargetCat').html('<option value="">Carregando...</option>').prop('disabled', true);
        $('#contentList').html('<div class="text-center py-5 text-muted">Aguardando categoria...</div>');
        
        if(!type) return;

        $.get('api/mover_api.php', { action: 'get_categories', type: type }, function(data){
            let opts = '<option value="">Selecione...</option>';
            data.forEach(c => { opts += `<option value="${c.id}">${c.name}</option>`; });
            
            $('#selectSourceCat').html(opts).prop('disabled', false);
            $('#selectTargetCat').html(opts).prop('disabled', false); // Destino carrega junto
        }, 'json');
    });

    // 2. MUDANÇA DE ORIGEM (Carrega Conteúdo)
    $('#selectSourceCat').change(function(){
        let cat_id = $(this).val();
        let type = $('#selectType').val();
        
        if(!cat_id) return;
        $('#contentList').html('<div class="text-center py-5 text-muted"><i class="fa fa-spin fa-spinner"></i> Carregando itens...</div>');

        $.get('api/mover_api.php', { action: 'get_content', type: type, cat_id: cat_id }, function(data){
            let html = '';
            if(data.length === 0) {
                html = '<div class="text-center py-5 text-muted">Categoria vazia.</div>';
            } else {
                data.forEach(item => {
                    html += `
                    <label class="list-group-item d-flex align-items-center m-0">
                        <input type="checkbox" class="item-chk mr-3" value="${item.id}" style="transform: scale(1.5);">
                        <span>${item.name}</span>
                    </label>`;
                });
            }
            $('#contentList').html(html);
            updateCount();
        }, 'json');
    });

    // 3. MUDANÇA DE DESTINO (Habilita botão)
    $('#selectTargetCat').change(function(){
        let origin = $('#selectSourceCat').val();
        let target = $(this).val();
        
        if(target && target === origin) {
            toastr.warning('Destino igual à origem!');
            $('#btnMove').prop('disabled', true);
        } else {
            $('#btnMove').prop('disabled', !target);
        }
    });

    // 4. MOVER (Botão)
    $('#btnMove').click(function(){
        let type = $('#selectType').val();
        let target = $('#selectTargetCat').val();
        let ids = [];
        
        $('.item-chk:checked').each(function(){ ids.push($(this).val()); });

        if(ids.length === 0) { toastr.warning('Selecione pelo menos um item.'); return; }

        if(confirm(`Tem certeza que deseja mover ${ids.length} itens?`)) {
            let btn = $(this);
            btn.prop('disabled', true).html('<i class="fa fa-spin fa-spinner"></i> Movendo...');

            $.post('api/mover_api.php', {
                action: 'move',
                type: type,
                target_cat: target,
                ids: ids
            }, function(res){
                btn.prop('disabled', false).html('<i class="fa fa-exchange-alt"></i> MOVER AGORA');
                if(res.status) {
                    toastr.success(res.msg);
                    $('#selectSourceCat').trigger('change'); // Recarrega lista
                } else {
                    toastr.error(res.msg);
                }
            }, 'json');
        }
    });

    // UTILS
    function selectAll() { $('.item-chk').prop('checked', true); updateCount(); }
    function deselectAll() { $('.item-chk').prop('checked', false); updateCount(); }
    
    $(document).on('change', '.item-chk', updateCount);
    
    function updateCount() {
        $('#countSelected').text($('.item-chk:checked').length);
    }

    // BUSCA LOCAL
    $('#searchBox').on('keyup', function() {
        var value = $(this).val().toLowerCase();
        $("#contentList label").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });
</script>

</body>
</html>