<?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"); 
} catch (Exception $e) { }

// DETECTA O ERRO DE DIGITAÇÃO ORIGINAL DO XTREAM UI NA COLUNA (movie_propeties)
$col_props = 'movie_properties';
try {
    $check_col_props = $pdo->query("SHOW COLUMNS FROM streams LIKE 'movie_propeties'");
    if ($check_col_props && $check_col_props->fetch()) {
        $col_props = 'movie_propeties'; // Xtream UI Raiz com o erro de digitação
    } else {
        $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);
    $nome_limpo = trim(preg_replace('/\s+/', ' ', $n));

    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, 8);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $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 = [];

// --- ETAPA 1: LER LISTA E SALVAR EM ARQUIVO TEMP ---
if (isset($_POST['ler_lista'])) {
    $conteudo_m3u = "";
    if (!empty($_POST['m3u_url'])) { 
        $conteudo_m3u = @file_get_contents($_POST['m3u_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);
        
        $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>"; 
    }
}

// --- ETAPA 2: IMPORTAR OS DADOS ---
if (isset($_POST['importar_agora'])) {
    $selecionadas = $_POST['categorias_sel'] ?? [];
    $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)) {
        
        // ==============================================================================
        // MOTOR DE LEITURA M3U (LINHA A LINHA)
        // ==============================================================================
        $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; }
                .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; }
            </style></head><body>';
            
            echo '<div class="container">';
            echo '<h2><i class="fas fa-cloud-download-alt"></i> Importação em Andamento</h2>';
            echo '<p style="margin: 0 0 10px 0; font-size: 13px;">Processando ' . $total_itens . ' itens. Não feche ou atualize esta aba.</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="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>
                function updateProgress(pct, msg) {
                    var pb = document.getElementById('pb');
                    pb.style.width = pct + '%'; pb.innerText = pct + '%';
                    var log = document.getElementById('log');
                    log.innerHTML += msg + '<br>';
                    log.scrollTop = log.scrollHeight;
                }
                function showBtn() { document.getElementById('btn-voltar').style.display = 'block'; }
            </script>";

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

            $importados = 0;
            $novos_stream_ids = []; 
            
            foreach ($itens_para_processar as $item) {
                $cat_nome = $item['cat'];
                $nome = $item['nome'];
                $link = $item['link'];
                $extinf = $item['extinf'];
                
                $cat_nome_lower = mb_strtolower($cat_nome, 'UTF-8');
                
                if (strpos($cat_nome_lower, 'canais') !== false || strpos($cat_nome_lower, 'ao vivo') !== false) {
                    $type = 1;
                } 
                elseif (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);

                $stmt_cat = $pdo->prepare("SELECT id FROM $tabela_categorias WHERE category_name = ? AND category_type = ?");
                $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) VALUES (?, ?)")->execute([$cat_nome, $cat_type_str]);
                        $cat_id = $pdo->lastInsertId();
                    } catch (Exception $e) {
                        $pdo->prepare("INSERT INTO $tabela_categorias (category_name) VALUES (?)")->execute([$cat_nome]);
                        $cat_id = $pdo->lastInsertId();
                    }
                }

                $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])) { 
                        $logMsg .= " <span class='tmdb'>-> TMDB...</span>";
                        $tmdb_cache[$serie_title_limpo] = buscarDadosTMDB($serie_title_limpo, 'series'); 
                        if ($tmdb_cache[$serie_title_limpo]) { $logMsg .= " <span class='success'>[OK]</span>"; }
                    }
                    
                    $capa = $tmdb_cache[$serie_title_limpo]['capa'] ?? $logo_m3u;
                    $plot = $tmdb_cache[$serie_title_limpo]['plot'] ?? "";

                    $stmt_serie = $pdo->prepare("SELECT id FROM $tabela_series WHERE title = ? AND category_id = ?");
                    $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) VALUES (?, ?, ?, ?)")->execute([$serie_title_limpo, $cat_id_serie, $capa, time()]);
                        $serie_id = $pdo->lastInsertId();
                        try { $pdo->prepare("UPDATE $tabela_series SET plot = ? WHERE id = ?")->execute([$plot, $serie_id]); } catch(Exception $e){}
                    }

                    // CORREÇÃO UNIVERSAL DE METADADOS: Formata link como JSON e salva em todas as colunas possíveis
                    $link_banco = (substr($link, 0, 1) !== '[') ? json_encode([$link], JSON_UNESCAPED_SLASHES) : $link;
                    $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, 5, time()]);
                    $episode_stream_id = $pdo->lastInsertId();

                    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 $col_props = ? WHERE id = ?")->execute([$props_json, $episode_stream_id]); } catch(Exception $e){} // Xtream UI + XUI One
                    try { $pdo->prepare("UPDATE streams SET movie_properties = ? WHERE id = ?")->execute([$props_json, $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++;
                } else {
                    $capa = $logo_m3u; 
                    $plot = ""; 
                    
                    if ($type == 2) { 
                        $logMsg .= " <span class='tmdb'>-> TMDB...</span>";
                        $info = buscarDadosTMDB($nome, 'movie');
                        if (!empty($info['capa'])) { $capa = $info['capa']; }
                        if (!empty($info['plot'])) { $plot = $info['plot']; }
                        
                        if (!empty($capa) || !empty($plot)) {
                            $logMsg .= " <span class='success'>[OK]</span>";
                        }
                    }

                    // CORREÇÃO UNIVERSAL DE METADADOS: Formata link como JSON e salva em todas as colunas possíveis
                    $link_banco = (substr($link, 0, 1) !== '[') ? json_encode([$link], JSON_UNESCAPED_SLASHES) : $link;
                    $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();

                    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 $col_props = ? WHERE id = ?")->execute([$props_json, $new_stream_id]); } catch(Exception $e){} // Xtream UI + XUI One
                    try { $pdo->prepare("UPDATE streams SET movie_properties = ? WHERE id = ?")->execute([$props_json, $new_stream_id]); } catch(Exception $e){}

                    $novos_stream_ids[] = (int) $new_stream_id;
                    $importados++;
                }

                $percent = floor(($importados / $total_itens) * 100);
                $jsMsg = json_encode($logMsg);
                echo "<script>updateProgress($percent, $jsMsg);</script>";
                flush();
            }
            
            if (!empty($novos_stream_ids) && !empty($bouquets_sel)) {
                echo "<script>updateProgress(99, '<span class=\"info\">[Bouquets] Atualizando vínculos...</span>');</script>";
                flush();
                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]);
                    }
                }
            }
            
            if (isset($_SESSION['temp_m3u_file']) && file_exists($_SESSION['temp_m3u_file'])) {
                @unlink($_SESSION['temp_m3u_file']);
                unset($_SESSION['temp_m3u_file']);
            }
            
            echo "<script>
                    updateProgress(100, '<br><span class=\"success\" style=\"font-size:14px;\"><b>✓ IMPORTAÇÃO CONCLUÍDA! $importados itens salvos.</b></span>');
                    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. O arquivo M3U pode estar fora do padrão suportado.</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; }

        /* ESTILOS DA SIDEBAR REVISADOS PARA FORÇAR CORES DO PAINEL */
        .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; }
        
        /* FORÇA A COR AZUL NO ADMINISTRADOR E VERDE NO SALDO INDEPENDENTE DA CLASSE DO SIDEBAR.PHP */
        .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;}
        
        /* FORÇA OS ÍCONES DA SIDEBAR A FICAREM AZUIS INDEPENDENTE DA CLASSE NATIVA */
        .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; }
        
        .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"] { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border); color: white; border-radius: 6px; margin-bottom: 10px; box-sizing: border-box; }
        .cat-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; max-height: 250px; 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; font-size: 13px; cursor: pointer; }
        .cat-item input { margin-right: 8px; cursor: pointer; }
        .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: repeat(auto-fill, minmax(120px, 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>
            <div></div>
        </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://...">
                        <label>Ou Arquivo</label>
                        <input type="file" name="m3u_file">
                        <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">
                            <?php foreach ($bouquets_disponiveis as $bq): ?>
                                <label class="cat-item"><input type="checkbox" name="bouquets_sel[]" value="<?php echo $bq['id']; ?>"> <?php echo $bq['bouquet_name']; ?></label>
                            <?php endforeach; ?>
                        </div>

                        <div class="flex-between" style="margin-top: 20px;">
                            <h4>2. Escolha as Categorias</h4>
                            <button type="button" class="btn-small" onclick="toggleAll('categorias_sel[]')">Marcar / Desmarcar Todas</button>
                        </div>
                        <div class="cat-grid">
                            <?php foreach ($categorias as $cat): ?>
                                <label class="cat-item"><input type="checkbox" name="categorias_sel[]" value="<?php echo htmlspecialchars($cat); ?>"> <?php echo htmlspecialchars($cat); ?></label>
                            <?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>
