<?php
// ARQUIVO: importer.php (Interface Visual)
// 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">
    
    <style>
        body { background-color: #121212; color: #e0e0e0; font-family: 'Segoe UI', sans-serif; }
        .card { background-color: #1e1e1e; border: 1px solid #333; }
        .form-control, .custom-file-label { background-color: #2c2c2c; border: 1px solid #444; 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; }
        .container-fluid { max-width: 1200px; }
        .cat-chk { width: 18px; height: 18px; cursor: pointer; accent-color: #28a745; }
    </style>
</head>
<body>

<div class="container-fluid mt-4 mb-5">
    
    <div class="d-flex justify-content-between align-items-center mb-4 pb-2 border-bottom border-secondary">
        <h3 class="font-weight-bold text-white"><i class="fa fa-bolt text-warning"></i> Importador Turbo V4</h3>
        <a href="dashboard.php" class="btn btn-secondary btn-sm"><i class="fa fa-arrow-left"></i> Voltar</a>
    </div>

    <div class="row">
        <div class="col-md-5">
            <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">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;">
                        <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-md-7">
            <div class="card shadow-sm" style="height: 100%;">
                <div class="card-header bg-dark d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fa fa-list-ul"></i> 2. Categorias Encontradas</h5>
                    <button class="btn btn-success btn-sm font-weight-bold px-3" 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"></i><br><br>
                            Primeiro, baixe ou envie a lista M3U.
                        </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">${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>
