<?php
// ARQUIVO: importer.php (Com Sidebar e Responsivo)
// LOCAL: Pasta Raiz (public_html/importer.php)

header('Content-Type: text/html; charset=utf-8');
session_start();

if (file_exists('includes/db.php')) {
    require_once 'includes/db.php';
} else {
    die("Erro: Arquivo includes/db.php não encontrado.");
}

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>Importador Turbo V4</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; }
        .form-control, .custom-file-label { background-color: #1a1c23; border: 1px solid #444; color: #fff; }
        .form-control:focus { background-color: #1a1c23; border-color: #007bff; color: #fff; }
        .list-group-item { background-color: #2c2c2c; border-color: #444; color: #fff; }
        .log-area { max-height: 200px; overflow-y: auto; background: #000; padding: 10px; border: 1px solid #444; color: #0f0; margin-top: 10px; font-size: 11px; font-family: monospace; }
        .badge-cat { min-width: 60px; text-align: center; }
        .cat-chk { width: 18px; height: 18px; cursor: pointer; accent-color: #28a745; }

        /* 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; }
        
        /* Ajuste Tabs */
        .nav-tabs .nav-link { color: #aaa; border: 1px solid transparent; }
        .nav-tabs .nav-link.active { color: #fff; background-color: #232730; border-color: #333 #333 #232730; font-weight: bold; }
        .nav-tabs { border-bottom: 1px solid #333; }
    </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-bolt text-warning mr-2"></i> Importador Turbo V4</h4>
                </div>
                <div>
                    <a href="dashboard.php" class="btn btn-secondary btn-sm d-none d-lg-inline-block">Voltar</a>
                </div>
            </div>

            <div class="container-fluid px-4 pb-5">
                
                <div class="row">
                    <div class="col-lg-5 mb-4">
                        <div class="card shadow-sm mb-3">
                            <div class="card-header bg-dark"><h5 class="mb-0"><i class="fa fa-cloud-download-alt"></i> 1. Baixar Lista</h5></div>
                            <div class="card-body">
                                <ul class="nav nav-tabs mb-3" role="tablist">
                                    <li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#link">🔗 Link URL</a></li>
                                    <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#file">📂 Enviar Arquivo</a></li>
                                </ul>

                                <div class="tab-content mb-3">
                                    <div class="tab-pane fade show active" id="link">
                                        <input type="text" class="form-control" id="urlInput" placeholder="http://dominio.com/get.php...">
                                        <small class="text-muted">Suporta listas grandes (M3U Plus).</small>
                                    </div>
                                    <div class="tab-pane fade" id="file">
                                        <div class="custom-file">
                                            <input type="file" class="custom-file-input" id="fileInput" accept=".m3u,.txt">
                                            <label class="custom-file-label" style="background-color: #1a1c23; border-color: #444;">Escolher arquivo...</label>
                                        </div>
                                    </div>
                                </div>

                                <button class="btn btn-primary btn-block font-weight-bold" onclick="processSource()">
                                    <i class="fa fa-sync"></i> BAIXAR E ANALISAR
                                </button>
                            </div>
                        </div>

                        <div class="card shadow-sm" id="progressCard" style="display:none;">
                            <div class="card-header bg-dark"><h5 class="mb-0">Status da Importação</h5></div>
                            <div class="card-body">
                                <div class="progress mb-2" style="height: 25px; background-color: #444;">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated bg-info" id="progressBar" style="width: 0%">0%</div>
                                </div>
                                <h6 id="statusText" class="text-center font-weight-bold text-info">Aguardando...</h6>
                                <div class="log-area" id="logArea"></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-7">
                        <div class="card shadow-sm h-100">
                            <div class="card-header bg-dark d-flex justify-content-between align-items-center flex-wrap">
                                <h5 class="mb-0 mr-2"><i class="fa fa-list-ul"></i> 2. Categorias Encontradas</h5>
                                <button class="btn btn-success btn-sm font-weight-bold px-3 mt-2 mt-sm-0" id="btnImport" onclick="startImport()" disabled>
                                    <i class="fa fa-play"></i> INICIAR IMPORTAÇÃO
                                </button>
                            </div>
                            
                            <div class="card-body p-2 d-flex flex-column">
                                <div class="btn-group btn-group-sm mb-2">
                                    <button class="btn btn-secondary" onclick="toggleAll(true)">Marcar Tudo</button>
                                    <button class="btn btn-secondary" onclick="toggleAll(false)">Desmarcar</button>
                                </div>

                                <div id="categoryList" style="flex: 1; overflow-y: auto; min-height: 400px; max-height: 600px;">
                                    <div class="text-center text-muted mt-5">
                                        <i class="fa fa-arrow-left fa-3x d-none d-lg-inline-block"></i>
                                        <i class="fa fa-arrow-up fa-3x d-lg-none"></i><br><br>
                                        Primeiro, baixe ou envie a lista M3U.
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

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

<div class="modal fade" id="modalReport" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content" style="background:#1a1c23; border:1px solid #444;">
            <div class="modal-header bg-success border-0">
                <h5 class="modal-title font-weight-bold text-white"><i class="fab fa-whatsapp"></i> Relatório de Conteúdos</h5>
                <button type="button" class="close text-white" data-dismiss="modal">×</button>
            </div>
            <div class="modal-body">
                <p class="text-white small">Copie o texto abaixo para divulgar as novidades:</p>
                <textarea id="reportText" class="form-control bg-dark text-white border-secondary" rows="15" style="resize:none;" readonly></textarea>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-primary" onclick="copyReport()"><i class="fa fa-copy"></i> COPIAR</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">FECHAR</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>
    // Variável para acumular os dados do relatório
    var reportData = { movie: {}, series: {}, channel: {} };

    $('.custom-file-input').on('change', function() {
        $(this).next('.custom-file-label').addClass("selected").html($(this).val().split('\\').pop());
    });

    function toggleAll(status) { $('.cat-chk').prop('checked', status); }

    function processSource() {
        $('#categoryList').html('<div class="text-center mt-5"><i class="fa fa-circle-notch fa-spin fa-3x text-info"></i><br><br>Analisando lista...</div>');
        $('#btnImport').prop('disabled', true);
        
        let activeTab = $('.nav-tabs .active').attr('href');
        let ajaxConfig = {
            url: 'api/importer.php', type: 'POST', dataType: 'json',
            success: function(res) { handleScanResult(res); },
            error: function(xhr) { toastr.error('Erro de servidor.'); $('#categoryList').html('<div class="text-center text-danger">Erro na API.</div>'); }
        };

        if (activeTab == '#link') {
            let url = $('#urlInput').val();
            if(!url) { toastr.error('Digite a URL'); return; }
            ajaxConfig.data = {action: 'download_url', url: url};
            $.ajax(ajaxConfig);
        } else {
            let file = $('#fileInput')[0].files[0];
            if(!file) { toastr.error('Selecione o arquivo'); return; }
            let formData = new FormData();
            formData.append('action', 'upload_file');
            formData.append('file', file);
            ajaxConfig.data = formData;
            ajaxConfig.processData = false;
            ajaxConfig.contentType = false;
            $.ajax(ajaxConfig);
        }
    }

    function handleScanResult(res) {
        if(res.status) { toastr.success(res.msg); renderCategories(res.categories); }
        else { toastr.error(res.msg); $('#categoryList').html('<div class="text-center text-danger mt-5">'+res.msg+'</div>'); }
    }

    function renderCategories(cats) {
        if(!cats || cats.length === 0) { $('#categoryList').html('<div class="text-center text-warning mt-5">Nenhuma categoria encontrada.</div>'); return; }
        let html = '';
        cats.forEach(c => {
            let badge = c.type == 'movie' ? 'badge-success' : (c.type == 'series' ? 'badge-warning' : 'badge-primary');
            html += `<div class="list-group-item py-2 d-flex align-items-center justify-content-between">
                <div class="d-flex align-items-center" style="max-width: 80%;">
                    <input type="checkbox" class="cat-chk mr-2" id="cat_${c.id}" value="${c.name}" data-type="${c.type}" checked>
                    <label class="mb-0 text-truncate" for="cat_${c.id}" style="cursor: pointer; font-size: 14px; margin-left: 5px;" title="${c.name}">${c.name}</label>
                </div>
                <div class="d-flex align-items-center"><span class="badge ${badge} badge-cat mr-2">${c.type}</span><span class="badge badge-light border" style="color:#000;">${c.count}</span></div>
            </div>`;
        });
        $('#categoryList').html(html);
        $('#btnImport').prop('disabled', false);
    }

    function startImport() {
        let selectedCats = [];
        $('.cat-chk:checked').each(function(){ selectedCats.push({ name: $(this).val(), type: $(this).data('type') }); });
        if(selectedCats.length === 0) { toastr.warning('Selecione categorias.'); return; }

        $('#progressCard').slideDown();
        $('#btnImport').prop('disabled', true);
        $('.cat-chk').prop('disabled', true);
        
        // Reset do relatório
        reportData = { movie: {}, series: {}, channel: {} };
        
        runBatchImport(selectedCats, 0);
    }

    function runBatchImport(categories, offset) {
        if(offset === 0) { $('#logArea').html(''); $('#progressBar').css('width', '1%').text('Iniciando...'); log('Iniciando importação...'); }

        $.ajax({
            url: 'api/importer.php', method: 'POST',
            data: { action: 'import_batch', categories: JSON.stringify(categories), offset: offset },
            dataType: 'json',
            success: function(res) {
                if(res.status) {
                    // Acumula itens para o relatório
                    if(res.imported_list && res.imported_list.length > 0) {
                        res.imported_list.forEach(item => {
                            if(!reportData[item.type][item.category]) reportData[item.type][item.category] = [];
                            reportData[item.type][item.category].push(item);
                        });
                    }

                    if(res.finished) {
                        $('#progressBar').css('width', '100%').addClass('bg-success').text('100%');
                        $('#statusText').text('Importação Concluída!');
                        log('Finalizado! Total: ' + res.offset);
                        toastr.success('Importação finalizada!');
                        $('#btnImport').prop('disabled', false);
                        $('.cat-chk').prop('disabled', false);
                        
                        // GERA O RELATÓRIO E ABRE O MODAL
                        generateAndShowReport();
                    } else {
                        log(`[Lote OK] ${res.msg}`);
                        $('#statusText').text(`Processando... Total: ${res.offset}`);
                        $('#progressBar').css('width', '50%').addClass('progress-bar-animated'); 
                        runBatchImport(categories, res.offset);
                    }
                } else {
                    log('Erro Fatal: ' + res.msg);
                    toastr.error(res.msg);
                    $('#btnImport').prop('disabled', false);
                }
            },
            error: function() { setTimeout(() => runBatchImport(categories, offset), 5000); }
        });
    }

    function generateAndShowReport() {
        let today = new Date().toLocaleDateString('pt-BR');
        let text = `Atualização conteúdos do dia: ${today}\n`;

        // 1. Filmes
        if (Object.keys(reportData.movie).length > 0) {
            text += `\n[FILMES]\n`;
            for (let cat in reportData.movie) {
                text += `\n📂 ${cat}\n\n`;
                reportData.movie[cat].forEach(i => {
                    let yearStr = i.year ? ` – (${i.year})` : '';
                    text += `📼 ${i.name}${yearStr}\n`;
                });
            }
        }

        // 2. Séries
        if (Object.keys(reportData.series).length > 0) {
            text += `\n[SÉRIES]\n`;
            for (let cat in reportData.series) {
                text += `\n📂 ${cat}\n\n`;
                reportData.series[cat].forEach(i => {
                    text += `📺 ${i.name}\n`;
                });
            }
        }

        // 3. Canais (Opcional, se quiser listar)
        if (Object.keys(reportData.channel).length > 0) {
            text += `\n[CANAIS]\n`;
            for (let cat in reportData.channel) {
                text += `\n📂 ${cat}\n\n`;
                reportData.channel[cat].forEach(i => {
                    text += `📡 ${i.name}\n`;
                });
            }
        }

        $('#reportText').val(text);
        $('#modalReport').modal('show');
    }

    function copyReport() {
        let textarea = document.getElementById("reportText");
        textarea.select();
        document.execCommand("copy");
        toastr.success("Relatório copiado!");
    }

    function log(msg) {
        let t = new Date().toLocaleTimeString();
        $('#logArea').append(`<div>[${t}] ${msg}</div>`);
        $('#logArea').scrollTop($('#logArea')[0].scrollHeight);
    }
</script>
</body>
</html>