<?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->exec("SET NAMES utf8mb4");

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

try {
    $tabela_existe = $pdo->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo->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 NO BANCO INTERNO
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS 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"); 
} 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)) {
        
        // ==============================================================================
        // NOVO MOTOR DE LEITURA M3U À PROVA DE FALHAS (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; // Pula linhas vazias

            if (strpos($linha, '#EXTINF') === 0) {
                $extinf_atual = $linha;
                
                // Extrai o nome do canal/filme (tudo depois da última vírgula)
                $partes = explode(',', $linha);
                $nome_atual = trim(end($partes));
                
                // Extrai a categoria (group-title)
                if (preg_match('/group-title="(.*?)"/i', $linha, $match_cat)) {
                    $cat_atual = trim($match_cat[1]);
                } else {
                    $cat_atual = "";
                }
            } 
            elseif (strpos($linha, '#EXTGRP:') === 0) {
                // Algumas listas colocam a categoria na tag #EXTGRP embaixo do EXTINF
                if (empty($cat_atual)) {
                    $cat_atual = trim(substr($linha, 8));
                }
            } 
            elseif (strpos($linha, '#') !== 0) { 
                // Se a linha não começa com # e não é vazia, É O LINK DO VÍDEO!
                if (!empty($extinf_atual) && !empty($linha)) {
                    // Verifica se a categoria deste item foi marcada por você
                    if (in_array($cat_atual, $selecionadas)) {
                        $itens_para_processar[] = [
                            'cat' => $cat_atual,
                            'nome' => $nome_atual,
                            'link' => $linha,
                            'extinf' => $extinf_atual
                        ];
                    }
                }
                // Reseta as variáveis para procurar o próximo canal
                $extinf_atual = "";
                $nome_atual = "";
                $cat_atual = "";
            }
        }
        // ==============================================================================

        $total_itens = count($itens_para_processar);

        if ($total_itens > 0) {
            echo '<!DOCTYPE html><html lang="pt-BR"><head><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 stream_categories WHERE category_name = ? AND category_type = ?");
                $stmt_cat->execute([$cat_nome, $cat_type_str]);
                $cat_id = $stmt_cat->fetchColumn();
                if (!$cat_id) {
                    $pdo->prepare("INSERT INTO stream_categories (category_name, category_type) VALUES (?, ?)")->execute([$cat_nome, $cat_type_str]);
                    $cat_id = $pdo->lastInsertId();
                }

                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 series WHERE title = ? AND category_id = ?");
                    $stmt_serie->execute([$serie_title_limpo, $cat_id]);
                    $serie_id = $stmt_serie->fetchColumn();
                    if (!$serie_id) {
                        $pdo->prepare("INSERT INTO series (title, category_id, cover, plot, last_modified) VALUES (?, ?, ?, ?, ?)")->execute([$serie_title_limpo, $cat_id, $capa, $plot, time()]);
                        $serie_id = $pdo->lastInsertId();
                    }

                    $pdo->prepare("INSERT INTO streams (stream_display_name, stream_source, category_id, stream_icon, type, added) VALUES (?, ?, ?, ?, ?, ?)")->execute([$nome, $link, $cat_id, $capa, 5, time()]);
                    $episode_stream_id = $pdo->lastInsertId();
                    
                    try {
                        $pdo->prepare("INSERT INTO series_episodes (season_num, series_id, stream_id, 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>";
                        }
                    }
                    
                    try {
                        $pdo->prepare("INSERT INTO streams (stream_display_name, stream_source, category_id, stream_icon, type, added, notes) VALUES (?, ?, ?, ?, ?, ?, ?)")->execute([$nome, $link, $cat_id, $capa, $type, time(), $plot]);
                        $novos_stream_ids[] = (int) $pdo->lastInsertId();
                        $importados++;
                    } catch (Exception $e) {
                        $pdo->prepare("INSERT INTO streams (stream_display_name, stream_source, category_id, stream_icon, type, added) VALUES (?, ?, ?, ?, ?, ?)")->execute([$nome, $link, $cat_id, $capa, $type, time()]);
                        $novos_stream_ids[] = (int) $pdo->lastInsertId();
                        $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; }

        .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); }
        .user-info { padding: 20px; border-bottom: 1px solid var(--border); text-align: center; }
        .menu-list { flex: 1; overflow-y: auto; }
        .menu-item { padding: 12px 25px; color: #aeb6c0; text-decoration: none; display: flex; align-items: center; border-left: 3px solid transparent; cursor: pointer; }
        .menu-item:hover, .menu-item.active { background: #24282d; color: white; border-left-color: var(--accent); }
        .menu-item i { margin-right: 15px; width: 20px; text-align: center; }

        .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; }
        .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)); }
        }
        
        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 14px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 12px; }
        .rotate { transform: rotate(180deg); }
        .menu-category { padding: 20px 20px 8px; font-size: 11px; text-transform: uppercase; color: #8a94a1; font-weight: bold; letter-spacing: 1px; }
    </style>
</head>
<body>
    <div class="sidebar-overlay" id="overlay"></div>
    <nav class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <?php if(!empty($logo_url) && file_exists($logo_url)): ?>
                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" style="max-width: 180px; max-height: 60px; object-fit: contain;">
            <?php else: ?>
                <?php echo htmlspecialchars($nome_painel); ?>
            <?php endif; ?>
        </div>
        <div class="user-info">
            <div style="font-size:14px;">Olá, <b><?php echo $nome_usuario; ?></b></div>
            <div style="color:var(--success); font-size:12px; margin-top:5px;">Saldo: <?php echo $user_credits ?? '0'; ?></div>
        </div>
        
        <div class="menu-list">
            <a href="dashboard.php" class="menu-item active"><i class="fas fa-chart-line"></i> Dashboard</a>
            <a href="perfil.php" class="menu-item active"><i class="fas fa-user-circle"></i> Meu Perfil</a>
            
            <a href="lancamentos.php" class="menu-item active"><i class="fas fa-fire"></i> Últimos Adicionados</a>
            
            <a href="ajuda.php" class="menu-item active"><i class="fas fa-question-circle"></i> Material de Ajuda</a>
            
            <div class="menu-category">Gestão</div>
            <a href="clientes.php" class="menu-item active"><i class="fas fa-users"></i> Clientes IPTV</a>
            <a href="testes.php" class="menu-item active"><i class="fas fa-vial"></i> Gerenciar Testes</a>
            <a href="online.php" class="menu-item active"><i class="fas fa-plug"></i> Clientes Online</a>
            <a href="revendedores.php" class="menu-item active"><i class="fas fa-user-tie"></i> Revendedores</a>
            <a href="migrar_clientes.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Migrar Clientes</a>
            <a href="logs_creditos.php" class="menu-item active"><i class="fas fa-list-alt"></i> Extrato de Créditos</a>
            
            <div class="menu-category">Clientes P2P</div>
            <a href="p2p_clientes.php" class="menu-item active"><i class="fas fa-tv"></i> Clientes P2P</a>
            
            <?php if (!empty($api_conf['api_binstream_url'])): ?>
                <a href="binstream_p2p.php" class="menu-item active"><i class="fas fa-tv"></i> Binstream P2P</a>
            <?php endif; ?>

            <div class="menu-category">Integração & Cobrança</div>
            <a href="pagamentos.php" class="menu-item active"><i class="fas fa-dollar-sign"></i> Pagamento Automático</a>
            <a href="cobranca.php" class="menu-item active"><i class="fas fa-comment-dollar"></i> Central de Cobrança</a>
            <a href="admin_planos.php" class="menu-item active"><i class="fas fa-tags"></i> Meus Planos de Venda</a>
            <a href="comprar_creditos.php" class="menu-item active"><i class="fas fa-shopping-cart"></i> Comprar Créditos</a>
            
            <div class="menu-item active" onclick="toggleSubmenu('appsSub')">
                <i class="fas fa-rocket"></i><span>Aplicações</span><i class="fas fa-chevron-down arrow-icon" id="arrow-appsSub"></i>
            </div>
            <div class="submenu" id="appsSub">
                <a href="loja_apps.php" class="menu-item active"><i class="fas fa-store"></i> Loja de Aplicativos</a>
                <?php if($role === 'admin'): ?>
                    <a href="admin_loja.php" class="menu-item active"><i class="fas fa-cogs"></i> Gerenciar Loja</a>
                <?php endif; ?>
                <a href="chatbot.php" class="menu-item active"><i class="fab fa-whatsapp"></i> Chatbot Automático</a>
            </div>
           <a href="admin_player_revenda.php" class="menu-item active"><i class="fas fa-play-circle"></i> WebPlayer</a>
            
   <div class="menu-category">Segurança</div>
            <a href="historico_logins.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sessões Ativas</a>

            <?php if($role === 'admin'): ?>
                <div class="menu-category">Administração</div>
                <a href="admin_monitor.php" class="menu-item active"><i class="fas fa-heartbeat"></i> Monitor do Servidor</a>
                <a href="admin_template.php" class="menu-item active"><i class="fas fa-edit"></i> Editor de Template</a>
                <a href="admin_lb.php" class="menu-item active"><i class="fas fa-server"></i> Load Balancers</a>
                <a href="guia_cloudflare.php" class="menu-item active"><i class="fas fa-cloud"></i> Guia Cloudflare</a>
                 <a href="admin_loja_creditos.php" class="menu-item active"><i class="fas fa-store"></i> Configurar Loja (PIX)</a>
                 <a href="integracoes_api.php" class="menu-item active"><i class="fas fa-plug"></i> Integrações API</a>
                 <a href="admin_robo.php" class="menu-item active"><i class="fas fa-robot"></i> Robô de Cobrança</a>
                 <a href="admin_anti_bloqueio.php" class="menu-item active"><i class="fas fa-bolt"></i> Botão de Pânico</a>
                 <a href="admin_anti_fraude.php" class="menu-item active"><i class="fas fa-user-secret"></i> Radar Anti-Fraude</a>  
                 <a href="admin_watchdog.php" class="menu-item active"><i class="fas fa-dog"></i> Watchdog LB</a>  
                 
                 <a href="admin_epg_sync.php" class="menu-item active">
        <i class="fas fa-clock"></i> Sincronizar EPG
    </a>
 <div class="menu-item active" onclick="toggleSubmenu('painelSub')">
                    <i class="fas fa-desktop"></i><span>Painel</span><i class="fas fa-chevron-down arrow-icon" id="arrow-painelSub"></i>
                </div>
                <div class="submenu" id="painelSub">
                    <a href="personalizacao.php" class="menu-item active"><i class="fas fa-paint-brush"></i> Personalização</a>
                </div>

                <div class="menu-item active" onclick="toggleSubmenu('adminSub')">
                    <i class="fas fa-toolbox"></i><span>Ferramentas</span><i class="fas fa-chevron-down arrow-icon" id="arrow-adminSub"></i>
                </div>
                <div class="submenu" id="adminSub">
                    <a href="importar.php" class="menu-item active"><i class="fas fa-file-import"></i> Importador</a>
                    <a href="dns_manager.php" class="menu-item active"><i class="fas fa-link"></i> Alterar DNS</a>
                    <a href="mover_conteudos.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Mover Conteúdos</a>
                    <a href="limpeza.php" class="menu-item active"><i class="fas fa-trash-alt"></i> Limpeza de Dados</a>
                    <a href="limpar_duplicados.php" class="menu-item active"><i class="fas fa-copy"></i> Limpeza de Duplicados</a>
                    <a href="backup.php" class="menu-item active"><i class="fas fa-database"></i> Backup do Sistema</a>
                    <a href="seguranca.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sistema de Segurança</a>
                    <a href="configuracoes.php" class="menu-item active"><i class="fas fa-tools"></i> Configurações</a>
                </div>

                <div class="menu-category">Conteúdos</div>
                <a href="categorias.php" class="menu-item active"><i class="fas fa-folder-open"></i><span>Categorias</span></a>
                <div class="menu-item active" onclick="toggleSubmenu('contentSub')">
                    <i class="fas fa-layer-group"></i><span>Mídias</span><i class="fas fa-chevron-down arrow-icon" id="arrow-contentSub"></i>
                </div>
                <div class="submenu" id="contentSub">
                    <a href="bouquets.php" class="menu-item active">Editar Bouquets</a>
                    <a href="canais.php" class="menu-item active">Canais Ao Vivo</a>
                    <a href="filmes.php" class="menu-item active">Filmes (VOD)</a>
                    <a href="series.php" class="menu-item active">Séries</a>
                </div>
                 <a href="admin_autofix_vod.php" class="menu-item active"><i class="fas fa-magic"></i> Auto-Fix TMDB</a>
            <?php endif; ?>
        </div>
        <a href="logout.php" class="logout-btn"><i class="fas fa-power-off"></i> Sair</a>
    </nav>

    <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');
        }
        document.getElementById('overlay').onclick = toggleMenu;

        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>
</body>
</html>
