<?php
// --- CORREÇÃO DE MEMÓRIA E TEMPO PARA LISTAS GRANDES ---
ini_set('memory_limit', '-1'); 
set_time_limit(0); 
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
@ob_implicit_flush(1);

session_start();
require_once 'config.php';

$pdo = getConexaoAtiva(); 
$pdo_int = getConexaoInterna(); // Adicionado para checar o XUI
$pdo->exec("SET NAMES utf8mb4");
$pdo_int->exec("SET NAMES utf8mb4");

// ====================================================================
// INTELIGÊNCIA ARTIFICIAL: DETECTA SE É XUI ONE OU XTREAM UI
// ====================================================================
$modo_ativo = 'interno';
try { $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno'; } catch (Exception $e) {}

$tabela_categorias = 'stream_categories';
$tabela_series = 'series';
$tabela_episodios = 'series_episodes';
$col_sort = 'sort';

if ($modo_ativo === 'xui') {
    $col_sort = 'episode_num';
    try { $pdo->query("SELECT 1 FROM streams_categories LIMIT 1"); $tabela_categorias = 'streams_categories'; } catch (Exception $e) { try { $pdo->query("SELECT 1 FROM categories LIMIT 1"); $tabela_categorias = 'categories'; } catch (Exception $e2) { } }
    try { $pdo->query("SELECT 1 FROM streams_series LIMIT 1"); $tabela_series = 'streams_series'; } catch (Exception $e) {}
    try { $pdo->query("SELECT 1 FROM streams_episodes LIMIT 1"); $tabela_episodios = 'streams_episodes'; } catch (Exception $e) {}
}
// ====================================================================

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';

try {
    $tabela_existe = $pdo_int->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo_int->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($config_painel) {
            $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
            $logo_url = !empty($config_painel['logo_url']) ? $config_painel['logo_url'] : $logo_url;
            $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
        }
    }
} catch (Exception $e) {}
// --- FIM: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---

if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }
$nome_usuario = $_SESSION['username'];
$user_id_logado = $_SESSION['user_id'];
$role = $_SESSION['user_role'];

// 1. GARANTE AS TABELAS E COLUNAS NO BANCO
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS $tabela_series (
        id INT(11) AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        category_id INT(11) NOT NULL,
        cover VARCHAR(255) NULL,
        plot TEXT NULL,
        last_modified INT(11) NULL
    )");
    $pdo->exec("ALTER TABLE streams ADD COLUMN IF NOT EXISTS notes TEXT NULL"); 
    $pdo->exec("ALTER TABLE streams ADD COLUMN IF NOT EXISTS plot TEXT NULL"); 
    $pdo->exec("ALTER TABLE streams ADD COLUMN IF NOT EXISTS direct_source INT(11) DEFAULT 0"); 
} catch (Exception $e) { }

// DETECTA O ERRO DE DIGITAÇÃO ORIGINAL DO XTREAM UI NA COLUNA (movie_propeties)
try {
    $check_col_props = $pdo->query("SHOW COLUMNS FROM streams LIKE 'movie_propeties'");
    if (!$check_col_props || !$check_col_props->fetch()) {
        $pdo->exec("ALTER TABLE streams ADD COLUMN IF NOT EXISTS movie_properties TEXT NULL"); 
    }
} catch (Exception $e) {}

// 2. CONFIGURAÇÃO TMDB
define('TMDB_API_KEY', 'f99aa9ae1fe7619969cc7db0938c1ae5');

function buscarDadosTMDB($nome, $tipo_busca = 'movie') {
    $ano = '';
    if (preg_match('/\((\d{4})\)|\b(\d{4})\b/', $nome, $matches)) {
        $ano = $matches[1] ?? $matches[2];
    }

    $n = preg_replace('/\[.*?\]/', '', $nome); 
    $n = preg_replace('/\(\d{4}\)/', '', $n); 
    $n = preg_replace('/\b(FHD|HD|SD|4K|1080p|720p|3D|DUB|LEG|DUBLADO|LEGENDADO|VOD|BR|PT|PT-BR|MKV|MP4|AVI)\b/i', '', $n);
    $n = str_replace(['.', '_'], ' ', $n);
    
    // SISTEMA AVANÇADO DE LIMPEZA
    $n = preg_replace('/(?:\s*|-|_)*(?:S|T|TEMP|TEMPORADA|SEASON)[a-z]*\s*\d+.*$/i', '', $n);
    $nome_limpo = trim(preg_replace('/\s+/', ' ', $n));
    $nome_limpo = trim($nome_limpo, " -_|");

    if (empty($nome_limpo)) return null;
    
    $endpoint = ($tipo_busca === 'series') ? 'tv' : 'movie';
    $url = "https://api.themoviedb.org/3/search/{$endpoint}?api_key=" . TMDB_API_KEY . "&query=" . urlencode($nome_limpo) . "&language=pt-BR";
    
    if (!empty($ano) && $tipo_busca === 'movie') {
        $url .= "&primary_release_year=" . $ano;
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    
    $res = curl_exec($ch);
    curl_close($ch);
    
    if (!$res) return null;

    $dados = json_decode($res, true);
    if (isset($dados['results'][0])) {
        $item = $dados['results'][0];
        return [
            'plot' => $item['overview'] ?? '', 
            'capa' => !empty($item['poster_path']) ? "https://image.tmdb.org/t/p/w500" . $item['poster_path'] : ''
        ];
    }
    return null;
}

$bouquets_disponiveis = $pdo->query("SELECT id, bouquet_name FROM bouquets ORDER BY bouquet_name ASC")->fetchAll(PDO::FETCH_ASSOC);

$mensagem = "";
$categorias = [];
$contadores_categorias = [];

// --- ETAPA 1: LER LISTA E SALVAR EM ARQUIVO TEMP ---
if (isset($_POST['ler_lista'])) {
    $conteudo_m3u = "";
    $sucesso_bypass = false;

    if (!empty($_POST['m3u_text'])) {
        $conteudo_m3u = $_POST['m3u_text'];
    } elseif (!empty($_POST['m3u_url'])) { 
        $url = trim($_POST['m3u_url']);
        
        if (preg_match('/(http[s]?:\/\/.*?)\/get\.php\?.*?username=([^&]+).*?password=([^&]+)/i', $url, $matches)) {
            $base_url = rtrim($matches[1], '/');
            $user = $matches[2];
            $pass = $matches[3];
            
            $api_url = $base_url . "/player_api.php?username=" . $user . "&password=" . $pass;
            
            $ch = curl_init($api_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            $auth_res = curl_exec($ch);
            curl_close($ch);
            
            $auth_data = json_decode($auth_res, true);
            
            if (isset($auth_data['user_info']['auth']) && $auth_data['user_info']['auth'] == 1) {
                $sucesso_bypass = true;
                
                function fetchApiDataBypass($endpoint) {
                    $ch = curl_init($endpoint);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
                    $res = curl_exec($ch);
                    curl_close($ch);
                    return json_decode($res, true);
                }
                
                $tmp_file = sys_get_temp_dir() . '/m3u_import_' . $user_id_logado . '.txt';
                $fp = fopen($tmp_file, 'wb');
                fwrite($fp, "#EXTM3U\n");
                
                // 1. Extrair Canais
                $live_cats = fetchApiDataBypass($api_url . "&action=get_live_categories");
                $live_streams = fetchApiDataBypass($api_url . "&action=get_live_streams");
                $map_live_cat = [];
                if (is_array($live_cats)) { foreach ($live_cats as $c) { $map_live_cat[$c['category_id']] = str_replace(',', '', $c['category_name']); } }
                if (is_array($live_streams)) {
                    foreach ($live_streams as $s) {
                        $cname = $map_live_cat[$s['category_id']] ?? 'Canais Ao Vivo';
                        $name = str_replace(',', '', $s['name']);
                        $logo = $s['stream_icon'] ?? '';
                        $id = $s['stream_id'];
                        fwrite($fp, "#EXTINF:-1 tvg-logo=\"$logo\" group-title=\"$cname\",$name\n$base_url/live/$user/$pass/$id.ts\n");
                    }
                }
                unset($live_cats, $live_streams, $map_live_cat);
                
                // 2. Extrair Filmes
                $vod_cats = fetchApiDataBypass($api_url . "&action=get_vod_categories");
                $vod_streams = fetchApiDataBypass($api_url . "&action=get_vod_streams");
                $map_vod_cat = [];
                if (is_array($vod_cats)) { foreach ($vod_cats as $c) { $map_vod_cat[$c['category_id']] = str_replace(',', '', $c['category_name']); } }
                if (is_array($vod_streams)) {
                    foreach ($vod_streams as $s) {
                        $cname = $map_vod_cat[$s['category_id']] ?? 'Filmes VOD';
                        $name = str_replace(',', '', $s['name']);
                        $logo = $s['stream_icon'] ?? '';
                        $id = $s['stream_id'];
                        $ext = $s['container_extension'] ?? 'mp4';
                        fwrite($fp, "#EXTINF:-1 tvg-logo=\"$logo\" group-title=\"$cname\",$name\n$base_url/movie/$user/$pass/$id.$ext\n");
                    }
                }
                unset($vod_cats, $vod_streams, $map_vod_cat);
                
                // 3. Extrair Índice de Séries
                $series_cats = fetchApiDataBypass($api_url . "&action=get_series_categories");
                $series = fetchApiDataBypass($api_url . "&action=get_series");
                $map_series_cat = [];
                if (is_array($series_cats)) { foreach ($series_cats as $c) { $map_series_cat[$c['category_id']] = str_replace(',', '', $c['category_name']); } }
                if (is_array($series)) {
                    foreach ($series as $s) {
                        $cname = $map_series_cat[$s['category_id']] ?? 'Séries';
                        $name = str_replace(',', '', $s['name']);
                        $logo = $s['cover'] ?? '';
                        $id = $s['series_id'];
                        
                        $payload_link = json_encode([
                            'api_type' => 'bypass_xtream_series',
                            'base_url' => $base_url,
                            'user' => $user,
                            'pass' => $pass,
                            'id' => $id
                        ]);
                        
                        fwrite($fp, "#EXTINF:-1 tvg-logo=\"$logo\" group-title=\"$cname\",$name\n$payload_link\n");
                    }
                }
                unset($series_cats, $series, $map_series_cat);
                
                $conteudo_m3u = file_get_contents($tmp_file);
            }
        }
        
        if (!$sucesso_bypass) {
            $conteudo_m3u = @file_get_contents($url); 
        }
    } elseif (!empty($_FILES['m3u_file']['tmp_name'])) { 
        $conteudo_m3u = file_get_contents($_FILES['m3u_file']['tmp_name']); 
    }

    if ($conteudo_m3u) {
        preg_match_all('/group-title="(.*?)"/i', $conteudo_m3u, $matches);
        $categorias = array_unique($matches[1]);
        sort($categorias);
        
        foreach($matches[1] as $cat_match) {
            if (!isset($contadores_categorias[$cat_match])) {
                $contadores_categorias[$cat_match] = 0;
            }
            $contadores_categorias[$cat_match]++;
        }
        $_SESSION['m3u_contadores'] = $contadores_categorias;
        
        $tmp_file = sys_get_temp_dir() . '/m3u_import_' . $user_id_logado . '.txt';
        file_put_contents($tmp_file, $conteudo_m3u);
        $_SESSION['temp_m3u_file'] = $tmp_file;
    } else { 
        $mensagem = "<div class='alert error' style='color:#e74c3c; padding:10px;'>Erro ao ler a lista. Verifique o link ou arquivo.</div>"; 
    }
}

if (isset($_SESSION['m3u_contadores'])) {
    $contadores_categorias = $_SESSION['m3u_contadores'];
}

// --- ETAPA 2: IMPORTAR OS DADOS ---
if (isset($_POST['importar_agora'])) {
    $selecionadas = $_POST['categorias_sel'] ?? [];
    $nomes_customizados = $_POST['categorias_nomes'] ?? [];
    $renovar_categorias = isset($_POST['renovar_categorias']) ? true : false;
    $bouquets_sel = $_POST['bouquets_sel'] ?? [];
    
    $conteudo = "";
    if (isset($_SESSION['temp_m3u_file']) && file_exists($_SESSION['temp_m3u_file'])) {
        $conteudo = file_get_contents($_SESSION['temp_m3u_file']);
    }

    $tmdb_cache = [];
    
    if ($conteudo && !empty($selecionadas)) {
        
        if ($renovar_categorias) {
            foreach ($selecionadas as $cat_original) {
                $nome_alvo = !empty($nomes_customizados[$cat_original]) ? trim($nomes_customizados[$cat_original]) : $cat_original;
                foreach (['live', 'movie', 'series'] as $t_type) {
                    $stmt_find = $pdo->prepare("SELECT id FROM $tabela_categorias WHERE category_name = ? COLLATE utf8mb4_unicode_ci AND category_type = ? LIMIT 1");
                    $stmt_find->execute([$nome_alvo, $t_type]);
                    $old_id = $stmt_find->fetchColumn();
                    if ($old_id) {
                        if ($t_type === 'series') {
                            $pdo->prepare("DELETE FROM $tabela_episodios WHERE series_id IN (SELECT id FROM $tabela_series WHERE category_id = ?)")->execute([$old_id]);
                            $pdo->prepare("DELETE FROM $tabela_series WHERE category_id = ?")->execute([$old_id]);
                        }
                        $pdo->prepare("DELETE FROM streams WHERE category_id = ? OR category_id = ? OR category_id LIKE ?")->execute([$old_id, json_encode([(int)$old_id]), json_encode([strval($old_id)])]);
                    }
                }
            }
        }

        $itens_para_processar = [];
        $linhas = explode("\n", str_replace("\r", "", $conteudo));
        
        $extinf_atual = ""; $nome_atual = ""; $cat_atual = "";

        foreach ($linhas as $linha) {
            $linha = trim($linha);
            if (empty($linha)) continue; 

            if (strpos($linha, '#EXTINF') === 0) {
                $extinf_atual = $linha;
                $partes = explode(',', $linha);
                $nome_atual = trim(end($partes));
                if (preg_match('/group-title="(.*?)"/i', $linha, $match_cat)) {
                    $cat_atual = trim($match_cat[1]);
                } else {
                    $cat_atual = "";
                }
            } 
            elseif (strpos($linha, '#EXTGRP:') === 0) {
                if (empty($cat_atual)) {
                    $cat_atual = trim(substr($linha, 8));
                }
            } 
            elseif (strpos($linha, '#') !== 0) { 
                if (!empty($extinf_atual) && !empty($linha)) {
                    if (in_array($cat_atual, $selecionadas)) {
                        $itens_para_processar[] = [
                            'cat' => $cat_atual,
                            'nome' => $nome_atual,
                            'link' => $linha,
                            'extinf' => $extinf_atual
                        ];
                    }
                }
                $extinf_atual = ""; $nome_atual = ""; $cat_atual = "";
            }
        }

        $total_itens = count($itens_para_processar);

        if ($total_itens > 0) {
            echo '<!DOCTYPE html><html lang="pt-BR"><head><link rel="stylesheet" href="tema.css"><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Importando... - ' . htmlspecialchars($nome_painel) . '</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">';
            echo '<style>
                body { background: #0f1114; color: #d1d5da; font-family: "Segoe UI", sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; box-sizing: border-box; }
                .container { background: #1e2227; padding: 20px; border-radius: 10px; border: 1px solid #2c3138; width: 95%; max-width: 800px; max-height: 95vh; display: flex; flex-direction: column; box-shadow: 0 10px 30px rgba(0,0,0,0.5); box-sizing: border-box; }
                .container h2 { margin-top: 0; font-size: 18px; }
                .progress-wrapper { background: #121519; border-radius: 6px; overflow: hidden; margin: 15px 0; border: 1px solid #2c3138; flex-shrink: 0; }
                .progress-bar { height: 25px; background: ' . $cor_primaria . '; width: 0%; transition: width 0.1s linear; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 12px; }
                .log-screen { background: #000; color: #0f0; font-family: monospace; padding: 10px; flex: 1; overflow-y: auto; border-radius: 6px; border: 1px solid #2c3138; font-size: 12px; line-height: 1.4; word-wrap: break-word; white-space: pre-wrap; }
                .log-screen span.info { color: #0ea5e9; }
                .log-screen span.tmdb { color: #f59e0b; }
                .log-screen span.success { color: #2ecc71; }
                .log-screen span.warning { color: #e67e22; }
                .btn-blue { background: ' . $cor_primaria . '; color: white; padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; text-decoration: none; font-weight: bold; display: inline-block; margin-top: 15px; text-align: center; }
                .report-area { background: #121519; color: #34d399; padding: 15px; border-radius: 6px; border: 1px solid #2c3138; font-family: monospace; max-height: 200px; overflow-y: auto; margin-top: 15px; text-align: left; white-space: pre-wrap; font-size: 13px; }
                .report-actions { display: flex; gap: 10px; justify-content: center; margin-top: 10px; flex-wrap: wrap; }
                .btn-action { padding: 10px 20px; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; color: white; display: inline-flex; align-items: center; gap: 8px; font-size: 13px; text-decoration: none; }
                .btn-copy { background: #4b5563; }
                .btn-whatsapp { background: #25d366; }
            </style></head><body>';
            
            echo '<div class="container">';
            echo '<h2><i class="fas fa-cloud-download-alt"></i> Velocidade da Luz Ativada</h2>';
            echo '<p style="margin: 0 0 10px 0; font-size: 13px;">Processando ' . $total_itens . ' itens. Modo Supersônico Sem Travas de Rede.</p>';
            echo '<div class="progress-wrapper"><div class="progress-bar" id="pb">0%</div></div>';
            echo '<div class="log-screen" id="log"></div>';
            
            echo '<div id="report-container" style="display:none;">';
            echo '<div class="report-area" id="report-text"></div>';
            echo '<div class="report-actions">';
            echo '<button class="btn-action btn-copy" onclick="copyReport()"><i class="fas fa-copy"></i> Copiar Relatório</button>';
            echo '<a id="wp-link" class="btn-action btn-green btn-whatsapp" href="#" target="_blank"><i class="fab fa-whatsapp"></i> Enviar WhatsApp</a>';
            echo '</div>';
            echo '</div>';
            
            echo '<div id="btn-voltar" style="display:none; text-align:center;"><a href="importar.php" class="btn-blue">Voltar para o Início</a></div>';
            echo '</div>';

            echo "<script>
                var lastUpdate = 0;
                function updateProgress(pct, msg, force) {
                    var now = Date.now();
                    if (force || now - lastUpdate > 10) { 
                        var pb = document.getElementById('pb');
                        if(pb) { pb.style.width = pct + '%'; pb.innerText = pct + '%'; }
                        var log = document.getElementById('log');
                        if(log) { log.innerHTML += msg + '<br>'; log.scrollTop = log.scrollHeight; }
                        lastUpdate = now;
                    }
                }
                function copyReport() {
                    var text = document.getElementById('report-text').innerText;
                    navigator.clipboard.writeText(text).then(function() {
                        alert('Relatório copiado com sucesso!');
                    }, function() {
                        alert('Erro ao copiar relatório.');
                    });
                }
                function finalizeReport(rawText) {
                    document.getElementById('report-text').innerText = rawText;
                    document.getElementById('report-container').style.display = 'block';
                    document.getElementById('wp-link').href = 'https://api.whatsapp.com/send?text=' + encodeURIComponent(rawText);
                }
                function showBtn() { document.getElementById('btn-voltar').style.display = 'block'; }
            </script>";

            while (ob_get_level() > 0) { ob_end_flush(); }
            flush();

            $importados = 0;
            $novos_stream_ids = []; 
            $relatorio_dados = [];
            
            $pdo->beginTransaction();
            
            $cache_sql_categorias = [];
            $cache_sql_series = [];
            
            foreach ($itens_para_processar as $item) {
                $cat_nome_original = $item['cat'];
                $cat_nome = !empty($nomes_customizados[$cat_nome_original]) ? trim($nomes_customizados[$cat_nome_original]) : $cat_nome_original;
                $nome = $item['nome'];
                $link = $item['link'];
                $extinf = $item['extinf'];
                
                $cat_nome_lower = mb_strtolower($cat_nome, 'UTF-8');
                
                $api_info = json_decode($link, true);
                $is_bypass_series = (is_array($api_info) && isset($api_info['api_type']) && $api_info['api_type'] === 'bypass_xtream_series');
                
                if (strpos($cat_nome_lower, 'canais') !== false || strpos($cat_nome_lower, 'ao vivo') !== false) {
                    $type = 1;
                } 
                elseif ($is_bypass_series || strpos($cat_nome_lower, 'série') !== false || strpos($cat_nome_lower, 'serie') !== false || strpos($cat_nome_lower, 'novela') !== false || strpos($cat_nome_lower, 'anime') !== false) {
                    $type = 5;
                } 
                elseif (strpos($cat_nome_lower, 'filme') !== false || strpos($cat_nome_lower, 'vod') !== false) {
                    $type = 2;
                } 
                else {
                    if (preg_match('/(S\d+E\d+|EP\s*\d+|CAP\s*\d+)/i', $nome)) {
                        $type = 5; 
                    } else {
                        $type = 1; 
                    }
                }

                $is_series = ($type == 5);
                $cat_type_str = ($type == 5) ? 'series' : (($type == 2) ? 'movie' : 'live');

                $logo_m3u = '';
                if (preg_match('/tvg-logo="(.*?)"/i', $extinf, $logo_match)) {
                    $logo_m3u = trim($logo_match[1]);
                }

                $logMsg = "<span class='info'>[Processando]</span> " . htmlspecialchars($nome);

                if (!$is_series && !$is_bypass_series) {
                    $stmt_check_dup = $pdo->prepare("SELECT COUNT(*) FROM streams WHERE stream_source = ? COLLATE utf8mb4_unicode_ci OR stream_source = ? COLLATE utf8mb4_unicode_ci");
                    $link_json_pure = json_encode([$link], JSON_UNESCAPED_SLASHES);
                    $stmt_check_dup->execute([$link, $link_json_pure]);
                    if ($stmt_check_dup->fetchColumn() > 0) {
                        $importados++;
                        $percent = floor(($importados / $total_itens) * 100);
                        $logMsgDup = $logMsg . " <span class='warning'>[Ignorado: Já existe]</span>";
                        echo "<script>updateProgress($percent, " . json_encode($logMsgDup) . ", false);</script>";
                        continue;
                    }
                }

                $cache_cat_key = $cat_nome . '_' . $cat_type_str;
                if (!isset($cache_sql_categorias[$cache_cat_key])) {
                    $stmt_cat = $pdo->prepare("SELECT id FROM $tabela_categorias WHERE category_name = ? COLLATE utf8mb4_unicode_ci AND category_type = ? LIMIT 1");
                    $stmt_cat->execute([$cat_nome, $cat_type_str]);
                    $cat_id = $stmt_cat->fetchColumn();
                    if (!$cat_id) {
                        try {
                            $pdo->prepare("INSERT INTO $tabela_categorias (category_name, category_type, parent_id, cat_order, is_adult) VALUES (?, ?, 0, 0, 0)")->execute([$cat_nome, $cat_type_str]);
                            $cat_id = $pdo->lastInsertId();
                        } catch (Exception $e) {
                            try {
                                $pdo->prepare("INSERT INTO $tabela_categorias (category_name, category_type) VALUES (?, ?)")->execute([$cat_nome, $cat_type_str]);
                                $cat_id = $pdo->lastInsertId();
                            } catch (Exception $e2) {
                                $pdo->prepare("INSERT INTO $tabela_categorias (category_name) VALUES (?)")->execute([$cat_nome]);
                                $cat_id = $pdo->lastInsertId();
                            }
                        }
                    }
                    $cache_sql_categorias[$cache_cat_key] = $cat_id;
                }
                $cat_id = $cache_sql_categorias[$cache_cat_key];

                $cat_id_stream = $cat_id;
                $cat_id_serie = $cat_id;
                if ($modo_ativo === 'xui' && $cat_id != 0) {
                    try {
                        $ex_stream = $pdo->query("SELECT category_id FROM streams WHERE category_id LIKE '[%' LIMIT 1")->fetchColumn();
                        $cat_id_stream = ($ex_stream && strpos($ex_stream, '"') !== false) ? json_encode([strval($cat_id)]) : json_encode([(int)$cat_id]);
                    } catch (Exception $e) { $cat_id_stream = json_encode([(int)$cat_id]); }
                    
                    try {
                        $ex_serie = $pdo->query("SELECT category_id FROM $tabela_series WHERE category_id LIKE '[%' LIMIT 1")->fetchColumn();
                        $cat_id_serie = ($ex_serie && strpos($ex_serie, '"') !== false) ? json_encode([strval($cat_id)]) : json_encode([(int)$cat_id]);
                    } catch (Exception $e) { $cat_id_serie = json_encode([(int)$cat_id]); }
                }

                if ($is_series) {
                    $serie_title = $nome; $season_num = 1; $ep_num = 1;
                    
                    if (preg_match('/^(.*?)(?:\s+|-|_)*(?:S|T)(\d+).*?(?:E|EP|CAP)(\d+)/i', $nome, $m_regex)) {
                        $serie_title = trim($m_regex[1]); $season_num = (int)$m_regex[2]; $ep_num = (int)$m_regex[3];
                    } 
                    elseif (preg_match('/^(.*?)(?:\s+|-|_)+(?:EP|CAP|CAPITULO|EPISODIO)\s*(\d+)/i', $nome, $m_regex)) {
                        $serie_title = trim($m_regex[1]); $season_num = 1; $ep_num = (int)$m_regex[2];
                    }
                    elseif (preg_match('/^(.*?)(?:\s+|-|_)+(\d{2,4})$/i', $nome, $m_regex)) {
                        $serie_title = trim($m_regex[1]); $season_num = 1; $ep_num = (int)$m_regex[2];
                    }

                    $serie_title = trim($serie_title, " -_|");
                    $serie_title_limpo = preg_replace('/(\[.*?\]|\(.*?\))/', '', $serie_title);
                    $serie_title_limpo = trim($serie_title_limpo);
                    if(empty($serie_title_limpo)) $serie_title_limpo = $serie_title;

                    if (!isset($tmdb_cache[$serie_title_limpo])) { 
                        $tmdb_cache[$serie_title_limpo] = buscarDadosTMDB($serie_title_limpo, 'series'); 
                        if ($tmdb_cache[$serie_title_limpo]) { $logMsg .= " <span class='success'>[TMDB OK]</span>"; }
                    }
                    
                    $capa = $tmdb_cache[$serie_title_limpo]['capa'] ?? $logo_m3u;
                    $plot = $tmdb_cache[$serie_title_limpo]['plot'] ?? "";

                    $cache_serie_key = $serie_title_limpo . '_' . json_encode($cat_id_serie);
                    if (!isset($cache_sql_series[$cache_serie_key])) {
                        $stmt_serie = $pdo->prepare("SELECT id FROM $tabela_series WHERE title = ? COLLATE utf8mb4_unicode_ci AND category_id = ? LIMIT 1");
                        $stmt_serie->execute([$serie_title_limpo, $cat_id_serie]);
                        $serie_id = $stmt_serie->fetchColumn();
                        if (!$serie_id) {
                            $pdo->prepare("INSERT INTO $tabela_series (title, category_id, cover, last_modified, plot) VALUES (?, ?, ?, ?, ?)")->execute([$serie_title_limpo, $cat_id_serie, $capa, time(), $plot]);
                            $serie_id = $pdo->lastInsertId();
                        }
                        $cache_sql_series[$cache_serie_key] = $serie_id;
                    }
                    $serie_id = $cache_sql_series[$cache_serie_key];

                    // OTIMIZAÇÃO EM LOTE PARA SÉRIES: Extrai e grava todos os episódios sem travar a rede
                    if ($is_bypass_series) {
                        $base_url = rtrim($api_info['base_url'], '/');
                        $user = $api_info['user'];
                        $pass = $api_info['pass'];
                        $s_id_api = $api_info['id'];
                        
                        $api_url_ep = $base_url . "/player_api.php?username=" . $user . "&password=" . $pass . "&action=get_series_info&series_id=" . $s_id_api;
                        
                        $ch_ep = curl_init($api_url_ep);
                        curl_setopt($ch_ep, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch_ep, CURLOPT_SSL_VERIFYPEER, false);
                        curl_setopt($ch_ep, CURLOPT_SSL_VERIFYHOST, false);
                        curl_setopt($ch_ep, CURLOPT_TIMEOUT, 6); 
                        $ep_res = curl_exec($ch_ep);
                        curl_close($ch_ep);
                        
                        $info_json = json_decode($ep_res, true);
                        if (isset($info_json['episodes']) && is_array($info_json['episodes'])) {
                            $count_eps_salvos = 0;
                            foreach ($info_json['episodes'] as $s_num => $eps_lista) {
                                foreach ($eps_lista as $ep_data) {
                                    $e_num = $ep_data['episode_num'] ?? 1;
                                    $e_id = $ep_data['id'] ?? '';
                                    $e_ext = $ep_data['container_extension'] ?? 'mp4';
                                    $e_title = $ep_data['title'] ?? '';
                                    
                                    $link_final_ep = "$base_url/series/$user/$pass/$e_id.$e_ext";
                                    $nome_final_ep = $nome . " S" . sprintf("%02d", $s_num) . "E" . sprintf("%02d", $e_num);
                                    if (!empty($e_title)) { $nome_final_ep .= " - " . $e_title; }
                                    
                                    // SISTEMA ANTI-DUPLICIDADE DE EPISÓDIO
                                    $stmt_check_ep = $pdo->prepare("SELECT COUNT(*) FROM $tabela_episodios WHERE series_id = ? AND season_num = ? AND $col_sort = ?");
                                    $stmt_check_ep->execute([$serie_id, $s_num, $e_num]);
                                    if ($stmt_check_ep->fetchColumn() > 0) {
                                        continue; 
                                    }
                                    
                                    $link_banco = json_encode([$link_final_ep], JSON_UNESCAPED_SLASHES);
                                    $props_json_ep = json_encode(['plot' => $plot, 'movie_image' => $capa, 'cover_big' => $capa, 'description' => $plot, 'name' => $nome_final_ep], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                                    
                                    $pdo->prepare("INSERT INTO streams (stream_display_name, stream_source, category_id, stream_icon, type, added) VALUES (?, ?, ?, ?, ?, ?)")
                                        ->execute([$nome_final_ep, $link_banco, $cat_id_stream, $capa, 5, time()]);
                                    $episode_stream_id = $pdo->lastInsertId();
                                    
                                    // NOVO SISTEMA: Updates isolados (O pulo do gato que descobrimos)
                                    try { $pdo->prepare("UPDATE streams SET direct_source = 1 WHERE id = ?")->execute([$episode_stream_id]); } catch(Exception $e){}
                                    try { $pdo->prepare("UPDATE streams SET plot = ? WHERE id = ?")->execute([$plot, $episode_stream_id]); } catch(Exception $e){}
                                    try { $pdo->prepare("UPDATE streams SET notes = ? WHERE id = ?")->execute([$plot, $episode_stream_id]); } catch(Exception $e){}
                                    try { $pdo->prepare("UPDATE streams SET movie_propeties = ? WHERE id = ?")->execute([$props_json_ep, $episode_stream_id]); } catch(Exception $e){} 
                                    try { $pdo->prepare("UPDATE streams SET movie_properties = ? WHERE id = ?")->execute([$props_json_ep, $episode_stream_id]); } catch(Exception $e){}
                                    try { $pdo->prepare("UPDATE streams SET target_container = 'mp4' WHERE id = ?")->execute([$episode_stream_id]); } catch(Exception $e){}
                                    try { $pdo->prepare("UPDATE streams SET stream_extension = 'mp4' WHERE id = ?")->execute([$episode_stream_id]); } catch(Exception $e){}

                                    try { $pdo->prepare("INSERT INTO $tabela_episodios (season_num, series_id, stream_id, $col_sort) VALUES (?, ?, ?, ?)")->execute([$s_num, $serie_id, $episode_stream_id, $e_num]); } catch (Exception $exEp) {}
                                    
                                    $novos_stream_ids[] = (int)$episode_stream_id;
                                    $count_eps_salvos++;
                                }
                            }
                            $logMsg .= " <span class='success'>[+{$count_eps_salvos} Eps]</span>";
                            
                            if (!isset($relatorio_dados['SÉRIES'][$cat_nome])) { $relatorio_dados['SÉRIES'][$cat_nome] = []; }
                            $relatorio_dados['SÉRIES'][$cat_nome][] = $serie_title_limpo;
                        }
                        $importados++;
                    } else {
                        // SISTEMA ANTI-DUPLICIDADE DE EPISÓDIO PADRÃO
                        $stmt_check_ep = $pdo->prepare("SELECT COUNT(*) FROM $tabela_episodios WHERE series_id = ? AND season_num = ? AND $col_sort = ?");
                        $stmt_check_ep->execute([$serie_id, $season_num, $ep_num]);
                        if ($stmt_check_ep->fetchColumn() > 0) {
                            $importados++;
                            $percent = floor(($importados / $total_itens) * 100);
                            $logMsgDup = $logMsg . " <span class='warning'>[Episódio Já Existe]</span>";
                            echo "<script>updateProgress($percent, " . json_encode($logMsgDup) . ", false);</script>";
                            continue;
                        }

                        $link_banco = (substr($link, 0, 1) !== '[') ? json_encode([$link], JSON_UNESCAPED_SLASHES) : $link;
                        $props_json_ep = json_encode(['plot' => $plot, 'movie_image' => $capa, 'cover_big' => $capa, 'description' => $plot, 'name' => $nome], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

                        $pdo->prepare("INSERT INTO streams (stream_display_name, stream_source, category_id, stream_icon, type, added) VALUES (?, ?, ?, ?, 5, ?)")
                            ->execute([$nome, $link_banco, $cat_id_stream, $capa, time()]);
                        $episode_stream_id = $pdo->lastInsertId();
                        
                        // NOVO SISTEMA: Updates isolados
                        try { $pdo->prepare("UPDATE streams SET direct_source = 1 WHERE id = ?")->execute([$episode_stream_id]); } catch(Exception $e){}
                        try { $pdo->prepare("UPDATE streams SET plot = ? WHERE id = ?")->execute([$plot, $episode_stream_id]); } catch(Exception $e){}
                        try { $pdo->prepare("UPDATE streams SET notes = ? WHERE id = ?")->execute([$plot, $episode_stream_id]); } catch(Exception $e){}
                        try { $pdo->prepare("UPDATE streams SET movie_propeties = ? WHERE id = ?")->execute([$props_json_ep, $episode_stream_id]); } catch(Exception $e){} 
                        try { $pdo->prepare("UPDATE streams SET movie_properties = ? WHERE id = ?")->execute([$props_json_ep, $episode_stream_id]); } catch(Exception $e){}
                        try { $pdo->prepare("UPDATE streams SET target_container = 'mp4' WHERE id = ?")->execute([$episode_stream_id]); } catch(Exception $e){}
                        try { $pdo->prepare("UPDATE streams SET stream_extension = 'mp4' WHERE id = ?")->execute([$episode_stream_id]); } catch(Exception $e){}

                        try { $pdo->prepare("INSERT INTO $tabela_episodios (season_num, series_id, stream_id, $col_sort) VALUES (?, ?, ?, ?)")->execute([$season_num, $serie_id, $episode_stream_id, $ep_num]); } catch (Exception $e) { }
                        
                        $novos_stream_ids[] = (int)$episode_stream_id;
                        $importados++;
                        
                        if (!isset($relatorio_dados['SÉRIES'][$cat_nome])) { $relatorio_dados['SÉRIES'][$cat_nome] = []; }
                        if (!in_array($serie_title_limpo, $relatorio_dados['SÉRIES'][$cat_nome])) {
                            $relatorio_dados['SÉRIES'][$cat_nome][] = $serie_title_limpo;
                        }
                    }
                } else {
                    $capa = $logo_m3u; 
                    $plot = ""; 
                    
                    if ($type == 2) { 
                        $nome_md5 = md5($nome);
                        if (!isset($tmdb_cache[$nome_md5])) {
                            $tmdb_cache[$nome_md5] = buscarDadosTMDB($nome, 'movie');
                        }
                        $info = $tmdb_cache[$nome_md5];
                        if ($info) {
                            if (!empty($info['capa'])) { $capa = $info['capa']; }
                            if (!empty($info['plot'])) { $plot = $info['plot']; }
                            $logMsg .= " <span class='success'>[TMDB OK]</span>"; 
                        } else {
                            $logMsg .= " <span style='color:#e74c3c;'>[TMDB FALHOU]</span>";
                        }
                    }

                    $link_banco = (substr($link, 0, 1) !== '[') ? json_encode([$link], JSON_UNESCAPED_SLASHES) : $link;
                    
                    // JSON Puro (Sem serialize que estava causando o bug)
                    $props_json = json_encode(['plot' => $plot, 'movie_image' => $capa, 'cover_big' => $capa, 'description' => $plot, 'name' => $nome], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

                    $pdo->prepare("INSERT INTO streams (stream_display_name, stream_source, category_id, stream_icon, type, added) VALUES (?, ?, ?, ?, ?, ?)")
                        ->execute([$nome, $link_banco, $cat_id_stream, $capa, $type, time()]);
                    
                    $new_stream_id = $pdo->lastInsertId();
                    
                    // NOVO SISTEMA: Updates isolados em sequência à prova de erros 
                    try { $pdo->prepare("UPDATE streams SET direct_source = 1 WHERE id = ?")->execute([$new_stream_id]); } catch(Exception $e){}
                    try { $pdo->prepare("UPDATE streams SET plot = ? WHERE id = ?")->execute([$plot, $new_stream_id]); } catch(Exception $e){}
                    try { $pdo->prepare("UPDATE streams SET notes = ? WHERE id = ?")->execute([$plot, $new_stream_id]); } catch(Exception $e){}
                    try { $pdo->prepare("UPDATE streams SET movie_propeties = ? WHERE id = ?")->execute([$props_json, $new_stream_id]); } catch(Exception $e){}
                    try { $pdo->prepare("UPDATE streams SET movie_properties = ? WHERE id = ?")->execute([$props_json, $new_stream_id]); } catch(Exception $e){}
                    try { $pdo->prepare("UPDATE streams SET target_container = 'mp4' WHERE id = ?")->execute([$new_stream_id]); } catch(Exception $e){}
                    try { $pdo->prepare("UPDATE streams SET stream_extension = 'mp4' WHERE id = ?")->execute([$new_stream_id]); } catch(Exception $e){}
                    
                    $novos_stream_ids[] = (int) $new_stream_id;
                    $importados++;
                    
                    $secao_relatorio = ($type == 2) ? 'FILMES' : 'CANAIS';
                    if (!isset($relatorio_dados[$secao_relatorio][$cat_nome])) { $relatorio_dados[$secao_relatorio][$cat_nome] = []; }
                    $relatorio_dados[$secao_relatorio][$cat_nome][] = $nome;
                }

                $percent = floor(($importados / $total_itens) * 100);
                $jsMsg = json_encode($logMsg);
                echo "<script>updateProgress($percent, $jsMsg, false);</script>";
                
                if ($importados % 25000 === 0) {
                    $pdo->commit();
                    $pdo->beginTransaction();
                    flush();
                }
            }
            
            if (!empty($novos_stream_ids) && !empty($bouquets_sel)) {
                foreach ($bouquets_sel as $bq_id) {
                    $row_bq = $pdo->query("SELECT bouquet_channels FROM bouquets WHERE id = ".intval($bq_id))->fetch();
                    if ($row_bq) {
                        $atuais = json_decode($row_bq['bouquet_channels'], true) ?: [];
                        $json = json_encode(array_values(array_unique(array_merge($atuais, $novos_stream_ids))), JSON_NUMERIC_CHECK);
                        $pdo->prepare("UPDATE bouquets SET bouquet_channels = ? WHERE id = ?")->execute([$json, $bq_id]);
                    }
                }
            }
            
            $pdo->commit();
            
            // ==============================================================================
            // CONSTRUTOR DE TEXTO DO RELATÓRIO DO WHATSAPP
            // ==============================================================================
            $texto_relatorio = "Atualização conteúdos do dia: " . date('d/m/Y') . "\n\n";
            foreach (['CANAIS', 'FILMES', 'SÉRIES'] as $secao) {
                if (!empty($relatorio_dados[$secao])) {
                    $texto_relatorio .= "[" . $secao . "]\n\n";
                    foreach ($relatorio_dados[$secao] as $categoria_tit => $titulos) {
                        $texto_relatorio .= "📁 " . $categoria_tit . "\n\n";
                        foreach (array_unique($titulos) as $t_nome) {
                            $texto_relatorio .= "📽️ " . $t_nome . "\n";
                        }
                        $texto_relatorio .= "\n";
                    }
                }
            }
            $texto_relatorio = trim($texto_relatorio);
            $jsRelatorio = json_encode($texto_relatorio);
            
            if (isset($_SESSION['temp_m3u_file']) && file_exists($_SESSION['temp_m3u_file'])) {
                @unlink($_SESSION['temp_m3u_file']);
                unset($_SESSION['temp_m3u_file']);
            }
            if (isset($_SESSION['m3u_contadores'])) {
                unset($_SESSION['m3u_contadores']);
            }
            
            echo "<script>
                    updateProgress(100, '<br><span class=\"success\" style=\"font-size:14px;\"><b>✓ IMPORTAÇÃO CONCLUÍDA! $importados conteúdos gravados.</b></span>', true);
                    finalizeReport($jsRelatorio);
                    showBtn();
                  </script>";
            echo '</body></html>';
            exit;
        } else {
            $mensagem = "<div class='alert error' style='color:#e74c3c; padding:10px; font-size:14px;'><b>Erro de Leitura:</b> Nenhum link válido foi encontrado nas categorias selecionadas.</div>";
        }
    } else {
        $mensagem = "<div class='alert error' style='color:#e74c3c; padding:10px;'>Sessão expirada ou nenhuma categoria marcada. Tente enviar o arquivo M3U novamente.</div>";
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Importador - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --bg: #0f1114; 
            --sidebar: #1a1d21; 
            --card: #1e2227; 
            --accent: <?php echo $cor_primaria; ?>; 
            --border: #2c3138; 
            --text: #d1d5da; 
            --success: #2ecc71; 
        }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background: var(--bg); color: var(--text); display: flex; height: 100vh; overflow: hidden; }

        .sidebar { width: 260px; background: var(--sidebar); border-right: 1px solid var(--border); display: flex; flex-direction: column; flex-shrink: 0; transition: 0.3s; z-index: 1001; }
        .sidebar-header { padding: 25px; text-align: center; font-size: 20px; font-weight: bold; color: white; border-bottom: 1px solid var(--border); }
        .sidebar-header span { color: var(--accent); }
        
        .sidebar-logo { width: 100%; max-width: 180px; height: auto; max-height: 60px; object-fit: contain; display: block; margin: 0 auto; }
        .user-info { padding: 20px; border-bottom: 1px solid var(--border); text-align: center; }
        
        .user-info > div:nth-child(2), .user-info .badge { background: rgba(0, 123, 255, 0.2) !important; color: var(--accent) !important; padding: 4px 10px !important; border-radius: 4px !important; font-size: 11px !important; text-transform: uppercase !important; font-weight: bold !important; margin-top: 5px !important; margin-bottom: 5px !important; display: inline-block !important; }
        .user-info > div:nth-child(3), .user-info .credits-badge, .user-info i.fa-coins { color: var(--success) !important; font-weight: bold !important; font-size: 13px !important; display: inline-block !important; }
        .user-info > div:nth-child(3) { margin-top: 8px !important; display: block !important; }

        .menu-list { flex: 1; overflow-y: auto; list-style: none; padding: 0; margin: 0; }
        .menu-category { padding: 20px 20px 8px; font-size: 11px; text-transform: uppercase; color: #8a94a1; font-weight: bold; letter-spacing: 1px; }
        .menu-item { padding: 14px 20px; color: #aeb6c0; text-decoration: none; display: flex; align-items: center; cursor: pointer; transition: 0.2s; font-size: 14px; border-left: 3px solid transparent;}
        
        .sidebar i, .sidebar span[class*="icon"], .sidebar .fas, .sidebar .fab { color: var(--accent) !important; }
        .sidebar .active, .sidebar .menu-item.active, .sidebar li.active > a { border-left-color: var(--accent) !important; color: white !important; background: #24282d !important; }
        .sidebar a:hover, .sidebar .menu-item:hover { border-left-color: var(--accent) !important; color: white !important; background: #2c3138 !important; }
        
        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 13px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 11px; }
        .rotate { transform: rotate(180deg); }
        .logout-btn { padding: 15px; background-color: #dc3545; color: white; text-align: center; text-decoration: none; font-weight: bold; margin-top: auto; }

        .main { flex: 1; overflow-y: auto; display: flex; flex-direction: column; position: relative; }
        .topbar { background: var(--sidebar); padding: 15px 20px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; }
        
        .status-badge { display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; border-radius: 20px; font-size: 12px; font-weight: bold; text-transform: uppercase; letter-spacing: 0.5px; border: 1px solid transparent; box-shadow: 0 2px 8px rgba(0,0,0,0.2); }
        .status-badge.interno { background: rgba(46, 204, 113, 0.15); color: #2ecc71; border-color: rgba(46, 204, 113, 0.3); }
        .status-badge.xui { background: rgba(230, 126, 34, 0.15); color: #e67e22; border-color: rgba(230, 126, 34, 0.3); }
        .status-badge.externo { background: rgba(52, 152, 219, 0.15); color: #3498db; border-color: rgba(52, 152, 219, 0.3); }
        .status-badge i { font-size: 11px; margin-right: 2px; }

        .content-area { padding: 20px; flex: 1; width: 100%; box-sizing: border-box; }
        .card { background: var(--card); border-radius: 10px; padding: 20px; border: 1px solid var(--border); width: 100%; box-sizing: border-box; }

        .btn { padding: 12px; border-radius: 6px; border: none; cursor: pointer; font-weight: bold; color: white; width: 100%; margin-top: 10px; transition: 0.2s; }
        .btn-blue { background: var(--accent); }
        .btn-green { background: var(--success); }
        .btn-small { background: #2c3138; color: #d1d5da; border: 1px solid #4a515a; padding: 5px 10px; border-radius: 4px; cursor: pointer; font-size: 11px; font-weight: bold; transition: 0.2s; }
        .btn-small:hover { background: #3d444d; color: white; }
        
        input[type="text"], input[type="file"], textarea { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border); color: white; border-radius: 6px; margin-bottom: 10px; box-sizing: border-box; }
        textarea { font-family: monospace; font-size: 13px; resize: vertical; }
        .cat-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 10px; max-height: 350px; overflow-y: auto; background: #121519; padding: 10px; border-radius: 6px; border: 1px solid var(--border); margin-bottom: 15px; }
        .cat-item { display: flex; align-items: center; justify-content: space-between; background: #1e2227; padding: 8px; border-radius: 4px; border: 1px solid #2c3138; font-size: 13px; }
        .cat-item-left { display: flex; align-items: center; flex: 1; min-width: 0; }
        .cat-item input[type="checkbox"] { margin-right: 8px; cursor: pointer; flex-shrink: 0; }
        .cat-item .cat-label-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1; min-width: 0; padding-right: 5px; }
        .cat-item .cat-badge-count { font-size: 10px; background: #2c3138; color: #34d399; padding: 2px 6px; border-radius: 10px; font-weight: bold; margin-left: auto; flex-shrink: 0; margin-right: 5px; }
        .cat-item input[type="text"] { margin: 0; padding: 5px; font-size: 12px; width: 45%; display: inline-block; flex-shrink: 0; }
        .flex-between { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
        .flex-between h4 { margin: 0; }

        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); z-index: 1000; }

        @media (max-width: 768px) {
            .sidebar { position: fixed; left: -260px; height: 100%; }
            .sidebar.active { left: 0; }
            .sidebar-overlay.active { display: block; }
            .content-area { padding: 15px; }
            .cat-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>
    <?php include 'sidebar.php'; ?>

    <div class="main">
        <header class="topbar">
            <button onclick="toggleMenu()" style="background:none; border:none; color:white; font-size:20px; cursor:pointer;"><i class="fas fa-bars"></i></button>
            <h3 style="margin:0; font-size:16px;">Importador Inteligente</h3>
            
            <?php if ($modo_ativo === 'xui'): ?>
                <div class="status-badge xui"><i class="fas fa-database"></i> XUI ONE</div>
            <?php elseif ($modo_ativo === 'externo'): ?>
                <div class="status-badge externo"><i class="fas fa-network-wired"></i> EXTERNO</div>
            <?php else: ?>
                <div class="status-badge interno"><i class="fas fa-server"></i> INTERNO</div>
            <?php endif; ?>
        </header>

        <div class="content-area">
            <?php echo $mensagem; ?>
            <div class="card">
                <?php if (empty($categorias)): ?>
                    <form method="POST" enctype="multipart/form-data">
                        <label>Link M3U</label>
                        <input type="text" name="m3u_url" placeholder="http://...">
                        <p style="font-size:12px; color:#8a94a1; margin-top:-5px; margin-bottom:15px;"><i class="fas fa-info-circle" style="color:var(--accent)!important;"></i> Cole o link direto fornecido pelo seu servidor. IMPORTANTE: Use link terminando em <strong>type=m3u_plus</strong> para puxar VOD.</p>
                        
                        <label>Ou Arquivo</label>
                        <input type="file" name="m3u_file">
                        <p style="font-size:12px; color:#8a94a1; margin-top:-5px; margin-bottom:15px;"><i class="fas fa-info-circle" style="color:var(--accent)!important;"></i> Selecione um arquivo .m3u salvo no seu dispositivo. Ótimo para listas offline ou backups locais.</p>

                        <label>Ou Cole o Texto M3U</label>
                        <textarea name="m3u_text" rows="6" placeholder="#EXTM3U..."></textarea>
                        <p style="font-size:12px; color:#8a94a1; margin-top:-5px; margin-bottom:15px;"><i class="fas fa-info-circle" style="color:var(--accent)!important;"></i> Cole diretamente o código da lista. Perfeito para edições rápidas ou para testar poucos canais.</p>
                        
                        <button type="submit" name="ler_lista" class="btn btn-blue">CARREGAR LISTA</button>
                    </form>
                <?php else: ?>
                    <form method="POST">
                        
                        <div class="flex-between">
                            <h4>1. Escolha os Bouquets</h4>
                            <button type="button" class="btn-small" onclick="toggleAll('bouquets_sel[]')">Marcar / Desmarcar Todos</button>
                        </div>
                        <div class="cat-grid" style="grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); max-height: 180px;">
                            <?php foreach ($bouquets_disponiveis = $pdo->query("SELECT id, bouquet_name FROM bouquets ORDER BY bouquet_name ASC")->fetchAll(PDO::FETCH_ASSOC) as $bq): ?>
                                <label style="display:flex; align-items:center; font-size:13px; cursor:pointer;"><input type="checkbox" name="bouquets_sel[]" value="<?php echo $bq['id']; ?>" style="margin-right:8px;"> <?php echo $bq['bouquet_name']; ?></label>
                            <?php endforeach; ?>
                        </div>

                        <div class="flex-between" style="margin-top: 20px;">
                            <h4>2. Escolha as Categorias e Renomeie se Desejar</h4>
                            <button type="button" class="btn-small" onclick="toggleAll('categorias_sel[]')">Marcar / Desmarcar Todas</button>
                        </div>
                        
                        <div style="background: #121519; padding: 10px; margin-bottom: 15px; border-radius: 6px; border: 1px solid var(--border);">
                            <label style="cursor: pointer; font-size: 13px; color: #f1c40f; display: flex; align-items: center;">
                                <input type="checkbox" name="renovar_categorias" value="1" style="margin-right: 8px;"> 
                                <strong><i class="fas fa-sync-alt"></i> Limpar categorias selecionadas antes de importar (Renovação Completa)</strong>
                            </label>
                        </div>

                        <div class="cat-grid">
                            <?php foreach ($categorias as $cat): 
                                $qtd_conteudos = $contadores_categorias[$cat] ?? 0;
                            ?>
                                <div class="cat-item">
                                    <div class="cat-item-left">
                                        <input type="checkbox" name="categorias_sel[]" value="<?php echo htmlspecialchars($cat); ?>">
                                        <span class="cat-label-text" title="<?php echo htmlspecialchars($cat); ?>"><?php echo htmlspecialchars(mb_strimwidth($cat, 0, 20, "...")); ?></span>
                                        <span class="cat-badge-count"><?php echo $qtd_conteudos; ?></span>
                                    </div>
                                    <input type="text" name="categorias_nomes[<?php echo htmlspecialchars($cat); ?>]" value="<?php echo htmlspecialchars($cat); ?>" placeholder="Alterar nome...">
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <button type="submit" name="importar_agora" class="btn btn-green" onclick="this.innerHTML='<i class=\'fas fa-spinner fa-spin\'></i> INICIANDO...'; this.style.opacity='0.7';">IMPORTAR AGORA</button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <script>
        function toggleMenu() {
            document.getElementById('sidebar').classList.toggle('active');
            document.getElementById('overlay').classList.toggle('active');
        }

        function toggleAll(name) {
            let checkboxes = document.querySelectorAll(`input[name="${name}"]`);
            let allChecked = Array.from(checkboxes).every(c => c.checked);
            checkboxes.forEach(c => c.checked = !allChecked);
        }

        function toggleSubmenu(id) {
            const sub = document.getElementById(id);
            const arrow = document.getElementById('arrow-' + id);
            
            if (sub.style.display === "block") {
                sub.style.display = "none";
                if(arrow) arrow.classList.remove('rotate');
            } else {
                sub.style.display = "block";
                if(arrow) arrow.classList.add('rotate');
            }
        }
    </script>
    <script src="tema.js"></script>
</body>
</html>
