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

include('includes/db.php'); 
session_start();

// Verifica login
if (!isset($_SESSION['logged_in_fxtream'])) { header('Location: index.php'); exit; }

set_time_limit(0); 
ini_set('memory_limit', '1024M');

$mensagem = "";
$arquivo_fonte = 'epg_source.txt';
$debug_content = "";
$log = [];

// --- FUNÇÃO DE LIMPEZA ---
function normalizarNome($nome) {
    $nome = mb_strtolower($nome, 'UTF-8');
    $remover = ['fhd', 'hd', 'sd', '4k', 'h.265', 'h265', 'hevc', '[alter]', '(alter)', '[backup]', 'vip', 'br', '1080p', '|', '-', '.', '_', '[', ']', '(', ')'];
    $nome = str_replace($remover, '', $nome);
    return preg_replace('/[^a-z0-9]/', '', $nome);
}

if (isset($_POST['btn_importar'])) {
    $url_xml = $_POST['url_xml'];
    
    if (!empty($url_xml)) {
        file_put_contents($arquivo_fonte, $url_xml);
        
        // --- DOWNLOAD COM SUPORTE A COMPRESSÃO ---
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url_xml);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_ENCODING, ''); // Aceita GZIP/Deflate
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        
        $xml_content = curl_exec($ch);
        $info = curl_getinfo($ch);
        $erro_curl = curl_error($ch);
        curl_close($ch);

        $inicio_arquivo = substr(trim($xml_content), 0, 200);

        if ($xml_content && (strpos($inicio_arquivo, '<?xml') !== false || strpos($inicio_arquivo, '<tv') !== false)) {
            
            $meus_canais = [];
            $stmt = $pdo->query("SELECT id, name FROM channels");
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $chave_limpa = normalizarNome($row['name']);
                if(!empty($chave_limpa)) $meus_canais[$chave_limpa][] = $row['id'];
            }

            $xml = @simplexml_load_string($xml_content, 'SimpleXMLElement', LIBXML_PARSEHUGE | LIBXML_NOERROR);
            
            if ($xml) {
                $vinculados = 0;
                $ids_para_atualizar = []; 

                foreach ($xml->channel as $canal_xml) {
                    $epg_id = (string)$canal_xml->attributes()->id;
                    $nome_xml_original = (string)$canal_xml->{'display-name'};
                    $chave_xml = normalizarNome($nome_xml_original);
                    
                    if (isset($meus_canais[$chave_xml])) {
                        foreach ($meus_canais[$chave_xml] as $id_banco) {
                            $ids_para_atualizar[$epg_id][] = $id_banco;
                        }
                        if($vinculados < 20) {
                            $log[] = "<div class='log-item success'>✅ MATCH: <b>$nome_xml_original</b> == <b>{$chave_xml}</b></div>";
                        }
                        $vinculados++;
                    }
                }
                
                if (!empty($ids_para_atualizar)) {
                    $sql_update = "UPDATE channels SET epg_id = ? WHERE id = ?";
                    $stmt_up = $pdo->prepare($sql_update);
                    $total = 0;
                    foreach ($ids_para_atualizar as $epg_id => $ids) {
                        foreach ($ids as $id) { $stmt_up->execute([$epg_id, $id]); $total++; }
                    }
                    $mensagem = "SUCESSO! Vinculados <b>$total</b> canais.";
                } else {
                    $mensagem = "XML baixado, mas nenhum nome coincidiu. Verifique a lista abaixo.";
                }
            } else {
                $mensagem = "Erro: O arquivo baixado não é um XML válido (pode ter caracteres inválidos).";
                $debug_content = "Início do arquivo: " . htmlspecialchars($inicio_arquivo);
            }
        } else {
            $mensagem = "Erro no Download.";
            $debug_content = "HTTP Code: " . $info['http_code'] . "<br>Conteúdo recebido (primeiros chars): " . htmlspecialchars($inicio_arquivo);
        }
    }
}
$link_atual = file_exists($arquivo_fonte) ? file_get_contents($arquivo_fonte) : '';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Importador V6 GZIP</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.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: #1a1c23; color: #fff; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        
        .card { background: #232730; border: 1px solid #333; }
        .log-box { background: #000; height: 300px; overflow-y: auto; padding: 10px; font-family: monospace; border: 1px solid #333; }
        .log-item.success { color: #00ff00; }
        .form-control { background-color: #1a1c23; border: 1px solid #444; color: #fff; }
        .form-control:focus { background-color: #1a1c23; border-color: #ffc107; color: #fff; }

        /* 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; }
    </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 fw-bold text-white"><i class="fa fa-file-code text-warning me-2"></i> Importador EPG V6</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 px-4 pb-5">
                
                <div class="card shadow-lg border-secondary">
                    <div class="card-header bg-warning text-dark text-center py-4">
                        <h2 class="mb-0 fw-bold"><i class="fa fa-box-open me-2"></i> Importador V6 (Descompactador)</h2>
                    </div>
                    <div class="card-body p-4">
                        <?php if(!empty($mensagem)): ?>
                            <div class="alert alert-info border-0 shadow mb-4"><?php echo $mensagem; ?></div>
                            <?php if($debug_content): ?>
                                <div class="alert alert-danger mb-4" style="word-break: break-all;">
                                    <strong>Debug do Servidor:</strong><br>
                                    <?php echo $debug_content; ?>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>

                        <form method="POST">
                            <label class="mb-2 text-white fw-bold">URL do XML (suporta .gz):</label>
                            <input type="url" name="url_xml" class="form-control form-control-lg mb-4" value="<?php echo htmlspecialchars($link_atual); ?>" required placeholder="http://exemplo.com/epg.xml.gz">
                            <button type="submit" name="btn_importar" class="btn btn-warning w-100 fw-bold py-3 mb-3">
                                <i class="fa fa-sync me-2"></i> TENTAR IMPORTAR AGORA
                            </button>
                        </form>

                        <?php if(isset($log) && count($log) > 0): ?>
                            <label class="mb-2 text-white fw-bold">Log de Processamento:</label>
                            <div class="log-box mb-3"><?php foreach($log as $l) echo $l; ?></div>
                        <?php endif; ?>
                    </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://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>