<?php
session_start();

// Ligando o radar de erros para não ficarmos cegos com "Tela Branca"
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'config.php';

$pdo = getConexaoInterna();

// --- PROTEÇÃO GERAL (Admin e Revenda) ---
if (!isset($_SESSION['user_id'])) {
    die("Acesso negado. Por favor, faça login no painel.");
}

$id_usuario = $_SESSION['user_id'];
$nome_usuario = $_SESSION['username'] ?? 'Usuário';
$role = $_SESSION['user_role'] ?? 'revenda';
$is_admin = ($role === 'admin'); 

if (!$is_admin) {
    die("Acesso restrito ao administrador.");
}

// =========================================================================
// 1. BANCO DE DADOS: CONFIGURAÇÃO TMDB (AGORA BLINDADO CONTRA TELA BRANCA)
// =========================================================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `tmdb_config` (
        `id` int(11) PRIMARY KEY,
        `api_key` varchar(255) DEFAULT ''
    )");
    
    // Verifica se a linha ID 1 já existe de forma segura
    $check_tmdb = $pdo->query("SELECT COUNT(*) FROM tmdb_config WHERE id = 1")->fetchColumn();
    if ($check_tmdb == 0) {
        $pdo->exec("INSERT INTO tmdb_config (id, api_key) VALUES (1, '')");
    }
} catch (Exception $e) {
    // Ignora se não tiver permissão de criar tabela, mas não quebra o site
}

// Ação: Salvar TMDB Key
$mensagem_alerta = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action_save_tmdb'])) {
    $tmdb_key = trim($_POST['tmdb_api_key']);
    try {
        $pdo->prepare("UPDATE tmdb_config SET api_key = ? WHERE id = 1")->execute([$tmdb_key]);
        $mensagem_alerta = "<div class='alert success'><i class='fas fa-check-circle'></i> API Key do TMDB salva com sucesso! O Robô está pronto.</div>";
    } catch (Exception $e) {
        $mensagem_alerta = "<div class='alert danger'>Erro ao salvar no banco interno: " . $e->getMessage() . "</div>";
    }
}

// Busca a chave atual DE FORMA SEGURA
$tmdb_key_atual = '';
try {
    $tmdb_config = $pdo->query("SELECT api_key FROM tmdb_config WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
    if ($tmdb_config) {
        $tmdb_key_atual = $tmdb_config['api_key'];
    }
} catch (Exception $e) {}

// =========================================================================
// 2. ENDPOINTS AJAX PARA O ROBÔ (Trabalho invisível blindado)
// =========================================================================

// A) Puxar lista de filmes do Xtream UI que estão SEM CAPA
if (isset($_GET['action']) && $_GET['action'] == 'get_broken_movies') {
    ob_start(); // Segura qualquer erro PHP que possa quebrar o JSON
    error_reporting(0);
    ini_set('display_errors', 0);
    header('Content-Type: application/json; charset=utf-8');
    try {
        $pdo_ext = getConexaoAtiva();
        $stmt = $pdo_ext->query("SELECT id, stream_display_name FROM streams WHERE type = 2 AND (stream_icon = '' OR stream_icon IS NULL) ORDER BY id DESC LIMIT 25");
        $filmes = $stmt->fetchAll(PDO::FETCH_ASSOC);
        ob_end_clean(); // Limpa sujeira da tela antes de enviar o JSON
        echo json_encode(['status' => 'success', 'data' => $filmes, 'type' => 'movie'], JSON_INVALID_UTF8_SUBSTITUTE);
    } catch (Exception $e) {
        ob_end_clean();
        echo json_encode(['status' => 'error', 'msg' => $e->getMessage()]);
    }
    exit;
}

// B) Puxar lista de séries do Xtream UI que estão SEM CAPA
if (isset($_GET['action']) && $_GET['action'] == 'get_broken_series') {
    ob_start(); 
    error_reporting(0);
    ini_set('display_errors', 0);
    header('Content-Type: application/json; charset=utf-8');
    try {
        $pdo_ext = getConexaoAtiva();
        // Nas séries, verificamos a cover e a cover_big
        $stmt = $pdo_ext->query("SELECT id, title FROM series WHERE (cover = '' OR cover IS NULL OR cover_big = '' OR cover_big IS NULL) ORDER BY id DESC LIMIT 25");
        $series = $stmt->fetchAll(PDO::FETCH_ASSOC);
        ob_end_clean(); 
        echo json_encode(['status' => 'success', 'data' => $series, 'type' => 'tv'], JSON_INVALID_UTF8_SUBSTITUTE);
    } catch (Exception $e) {
        ob_end_clean();
        echo json_encode(['status' => 'error', 'msg' => $e->getMessage()]);
    }
    exit;
}

// C) Salvar o filme/série corrigido no Xtream UI
if (isset($_GET['action']) && $_GET['action'] == 'update_media') {
    ob_start(); 
    error_reporting(0);
    ini_set('display_errors', 0);
    
    $id = intval($_POST['id'] ?? 0);
    $type = $_POST['type'] ?? 'movie';
    $icon = $_POST['icon'] ?? '';
    $plot = $_POST['plot'] ?? '';
    $rating = $_POST['rating'] ?? '';
    $backdrop = $_POST['backdrop'] ?? '';

    if ($id > 0) {
        try {
            $pdo_ext = getConexaoAtiva();
            
            if ($type === 'movie') {
                // LOGICA DE FILMES
                $stmt = $pdo_ext->prepare("SELECT movie_propeties FROM streams WHERE id = ?");
                $stmt->execute([$id]);
                $row = $stmt->fetch(PDO::FETCH_ASSOC);
                
                $props = [];
                if ($row && !empty($row['movie_propeties'])) {
                    $props = json_decode($row['movie_propeties'], true);
                    if (!is_array($props)) $props = [];
                }
                
                if (!empty($icon)) $props['movie_image'] = $icon;
                if (!empty($plot)) $props['plot'] = $plot;
                if (!empty($rating)) $props['rating'] = $rating;
                if (!empty($backdrop)) $props['backdrop_path'] = [$backdrop];
                
                $props_json = json_encode($props, JSON_UNESCAPED_UNICODE);
                
                $set_sql = [];
                $params = [];
                
                if (!empty($icon)) { $set_sql[] = "stream_icon = ?"; $params[] = $icon; }
                $set_sql[] = "movie_propeties = ?"; $params[] = $props_json;
                $params[] = $id; 
                
                if (count($set_sql) > 0) {
                    $sql = "UPDATE streams SET " . implode(", ", $set_sql) . " WHERE id = ?";
                    $pdo_ext->prepare($sql)->execute($params);
                }
            } else {
                // LOGICA DE SÉRIES
                $set_sql = [];
                $params = [];
                
                if (!empty($icon)) { 
                    $set_sql[] = "cover = ?"; $params[] = $icon; 
                    $set_sql[] = "cover_big = ?"; $params[] = $icon; 
                }
                if (!empty($plot)) { $set_sql[] = "plot = ?"; $params[] = $plot; }
                if (!empty($rating)) { $set_sql[] = "rating = ?"; $params[] = $rating; }
                if (!empty($backdrop)) { $set_sql[] = "backdrop_path = ?"; $params[] = json_encode([$backdrop]); }
                
                $params[] = $id;
                
                if (count($set_sql) > 0) {
                    $sql = "UPDATE series SET " . implode(", ", $set_sql) . " WHERE id = ?";
                    $pdo_ext->prepare($sql)->execute($params);
                }
            }
            
            ob_end_clean();
            echo "OK";
        } catch (Exception $e) {
            ob_end_clean();
            echo "ERRO: " . $e->getMessage();
        }
    }
    exit;
}

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';
try {
    $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) { }

$total_filmes_quebrados = 0;
$total_series_quebradas = 0;
$user_credits = 0;

try {
    $pdo_ext = getConexaoAtiva();
    $user_credits = $pdo_ext->query("SELECT credits FROM reg_users WHERE id = " . intval($id_usuario))->fetchColumn() ?: 0;
    
    // Conta quantos filmes precisam de ajuda
    $total_filmes_quebrados = $pdo_ext->query("SELECT COUNT(*) FROM streams WHERE type = 2 AND (stream_icon = '' OR stream_icon IS NULL)")->fetchColumn() ?: 0;
    // Conta quantas series precisam de ajuda
    $total_series_quebradas = $pdo_ext->query("SELECT COUNT(*) FROM series WHERE (cover = '' OR cover IS NULL OR cover_big = '' OR cover_big IS NULL)")->fetchColumn() ?: 0;
    
} catch (Exception $e) { 
    // Falha silenciosa
}
?>

<!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>Auto-Fix VOD/Series - <?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-dark: #121519; --bg-sidebar: #1e2227; --bg-card: #272c33; --text-main: #d1d5da; --text-muted: #8a94a1; --accent: <?php echo $cor_primaria; ?>; --border-color: #3a4149; --success: #28a745; --danger: #dc3545; --warning: #f39c12; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        
        .sidebar { width: 260px; background-color: var(--bg-sidebar); display: flex; flex-direction: column; transition: 0.3s; border-right: 1px solid var(--border-color); z-index: 1001; flex-shrink: 0; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .sidebar-logo { max-width: 180px; max-height: 55px; object-fit: contain; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(255, 255, 255, 0.05); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; padding-bottom: 20px;}
        .menu-list::-webkit-scrollbar { width: 6px; }
        .menu-list::-webkit-scrollbar-thumb { background: #3a4149; border-radius: 3px; }

        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; border-left: 3px solid transparent; font-size: 14px; cursor: pointer; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background-color: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i:first-child { color: var(--accent); }
        .menu-category { padding: 20px 20px 5px; font-size: 11px; font-weight: bold; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px;}
        .logout-btn { padding: 15px; background-color: var(--danger); color: white; text-align: center; text-decoration: none; font-weight: bold; }

        .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: transform 0.3s ease; font-size: 11px; }
        
        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; position: relative; }
        .topbar { display: flex; justify-content: flex-start; align-items: center; padding: 15px 25px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); gap: 15px;}
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 22px; cursor: pointer; padding: 5px; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }
        
        .content-area { padding: 30px; flex: 1; max-width: 1200px; margin: 0 auto; width: 100%; box-sizing: border-box; }
        .card { background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-color); padding: 25px; margin-bottom: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .card h3 { margin-top: 0; color: white; border-bottom: 1px solid var(--border-color); padding-bottom: 15px; display: flex; align-items: center; gap: 10px;}
        
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 8px; font-size: 13px; font-weight: bold; color: var(--text-muted); }
        
        input[type="text"], input[type="password"] { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 8px; box-sizing: border-box; font-size: 14px;}
        input[type="text"]:focus, input[type="password"]:focus { border-color: var(--accent); outline: none; }
        
        .btn-save { background: var(--accent); color: white; border: none; padding: 15px; border-radius: 8px; cursor: pointer; font-weight: bold; width: 100%; font-size: 15px; transition: 0.2s; display: flex; justify-content: center; align-items: center; gap: 8px;}
        .btn-save:hover { filter: brightness(1.1); box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .btn-save:disabled { background: #555; cursor: not-allowed; }
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; display: flex; align-items: center; gap: 10px;}
        .alert.success { background: rgba(40, 167, 69, 0.15); border: 1px solid var(--success); color: var(--success); }
        .alert.danger { background: rgba(220, 53, 69, 0.15); border: 1px solid var(--danger); color: var(--danger); }
        .alert.warning { background: rgba(243, 156, 18, 0.15); border: 1px solid var(--warning); color: var(--warning); }
        
        .terminal { background: #000; border-radius: 8px; border: 1px solid var(--border-color); margin-top: 20px; height: 350px; padding: 15px; overflow-y: auto; font-family: monospace; color: #0f0; white-space: pre-wrap; font-size: 13px; line-height: 1.5; }
        .terminal::-webkit-scrollbar { width: 8px; }
        .terminal::-webkit-scrollbar-thumb { background: #3a4149; border-radius: 4px; }
        
        .terminal .log-success { color: #00ff00; }
        .terminal .log-warning { color: #ffeb3b; }
        .terminal .log-info { color: #0ea5e9; }

        .progress-container { width: 100%; background-color: #121519; border-radius: 8px; margin-top: 20px; overflow: hidden; display: none; border: 1px solid var(--border-color);}
        .progress-bar { height: 25px; background-color: var(--success); width: 0%; transition: 0.3s; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold; color: white;}

        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 25px;}
        .stat-box { background: rgba(0,0,0,0.2); padding: 20px; border-radius: 10px; border: 1px solid var(--border-color); text-align: center; }
        .stat-box i { font-size: 30px; color: var(--accent); margin-bottom: 10px;}
        .stat-box .num { font-size: 24px; font-weight: bold; color: white;}
        .stat-box .label { font-size: 12px; color: var(--text-muted); text-transform: uppercase; margin-top: 5px; font-weight: bold;}

        @media (max-width: 768px) {
            .menu-toggle { display: block; }
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .sidebar.active { left: 0; }
            .sidebar-overlay.active { display: block; }
            .content-area { padding: 15px; }
        }
    </style>
</head>
<body>
    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></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" class="sidebar-logo">
            <?php else: ?>
                <?php echo htmlspecialchars($nome_painel); ?>
            <?php endif; ?>
        </div>
        <div class="user-info">
            <div style="color:white; font-size: 14px;">Olá, <strong><?php echo htmlspecialchars($nome_usuario); ?></strong></div>
            <span class="badge"><?php echo $is_admin ? 'Administrador' : 'Revendedor'; ?></span>
            <div class="credits-badge"><i class="fas fa-coins"></i> Saldo: <?php echo number_format($user_credits, 1); ?></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>
            <a href="meus_links.php" class="menu-item active"><i class="fas fa-link" style="color: var(--accent);"></i> Central de Links</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>
            <a href="marketing.php" class="menu-item active"><i class="fas fa-bullhorn"></i> Central de Marketing</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; ?>

 <?php if($role === 'admin'): ?>
<div class="menu-category">Gerar Licença</div>
<a href="admin_licencas.php" class="menu-item active"> <i class="fas fa-key" style="color: #28a745;"></i> <span>Gerador SaaS</span> </a>
<?php endif; ?>

<div class="menu-category">Api WhatsApp</div>
                <a href="integracoes_api_whatsapp.php" class="menu-item active"><i class="fas fa-plug"></i> Integrações API WhatsApp</a>


            <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_token.php" class="menu-item active"><i class="fas fa-user-secret"></i> Token Links Xui</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="importar3.php" class="menu-item active"><i class="fas fa-file-import"></i> Importador Turbo</a>
                    <a href="dns_manager.php" class="menu-item active"><i class="fas fa-link"></i> Alterar DNS</a>
                    <a href="admin_logos.php" class="menu-item active"><i class="fas fa-image"></i> Alterar Logos</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>

                 <?php if($role === 'admin'): ?>
    <div class="menu-category">Financeiro</div>
     <!-- NOVO MENU FINANCEIRO COM SUBMENU -->
            <div class="menu-item active" onclick="toggleSubmenu('finSub')">
                <i class="fas fa-hand-holding-usd"></i><span>Financeiro</span><i class="fas fa-chevron-down arrow-icon rotate" id="arrow-finSub"></i>
            </div>
            <div class="submenu" id="finSub" style="display: block;">
                <a href="financeiro.php" class="menu-item active">Faturamento</a>
            </div>
    
    <?php endif; ?>

                <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-content">
        <header class="topbar">
            <div style="display:flex; align-items:center;">
                <button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; font-size: 18px; color:white;"><i class="fas fa-magic" style="color:var(--accent);"></i> Robô Mágico TMDB</h2>
            </div>
        </header>

        <div class="content-area">
            <?php echo $mensagem_alerta; ?>

            <div class="stats-grid">
                <div class="stat-box">
                    <i class="fas fa-film"></i>
                    <div class="num"><?php echo number_format($total_filmes_quebrados); ?></div>
                    <div class="label">Filmes s/ Capa</div>
                </div>
                <div class="stat-box" style="border-color: var(--info);">
                    <i class="fas fa-tv" style="color: var(--info);"></i>
                    <div class="num"><?php echo number_format($total_series_quebradas); ?></div>
                    <div class="label">Séries s/ Capa</div>
                </div>
            </div>

            <div class="card" style="border-top: 4px solid var(--accent);">
                <h3><i class="fas fa-cogs" style="color:var(--accent);"></i> Configuração do Robô</h3>
                <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 20px;">O painel vai ler os nomes dos seus filmes e séries e baixar as capas e as sinopses em Português automaticamente da API do TMDB.</p>
                
                <form method="POST">
                    <input type="hidden" name="action_save_tmdb" value="1">
                    <div class="form-group">
                        <label>Sua API Key (TMDB)</label>
                        <p style="font-size: 11px; color: var(--warning); margin-top: 0;">Para conseguir uma chave grátis, crie uma conta em <strong>themoviedb.org</strong>, vá em Configurações > API e gere uma chave v3.</p>
                        <input type="text" name="tmdb_api_key" id="tmdb_api_key" value="<?php echo htmlspecialchars($tmdb_key_atual); ?>" placeholder="Ex: 8a7b6c5d4e3f2g1h..." required>
                    </div>
                    <button type="submit" class="btn-save"><i class="fas fa-save"></i> SALVAR CHAVE</button>
                </form>
            </div>

            <div class="card" style="border-top: 4px solid var(--success);">
                <h3><i class="fas fa-robot" style="color:var(--success);"></i> Central de Comando</h3>
                
                <button type="button" id="btnStartFix" class="btn-save" style="background:var(--success);" onclick="iniciarRobo()" <?php echo empty($tmdb_key_atual) ? 'disabled' : ''; ?>>
                    <i class="fas fa-play"></i> INICIAR CORREÇÃO AUTOMÁTICA
                </button>
                
                <?php if(empty($tmdb_key_atual)): ?>
                    <small style="color:var(--danger); display:block; margin-top:10px; text-align:center;">* Salve a sua API Key acima para liberar o botão.</small>
                <?php endif; ?>

                <div class="progress-container" id="progressContainer">
                    <div class="progress-bar" id="progressBar">0%</div>
                </div>

                <div class="terminal" id="terminalLog">
                    <span class="log-info">[SISTEMA] Robô em standby. Aguardando comando para iniciar a varredura (Filmes e Séries)...</span><br>
                </div>
            </div>
            <?php include 'rodape.php'; ?>
        </div>
    </div>

    <script>
        const tmdbKey = "<?php echo $tmdb_key_atual; ?>";
        let isRunning = false;

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

        function toggleSubmenu(id) {
            var submenu = document.getElementById(id);
            var arrow = document.getElementById('arrow-' + id);
            if (submenu.style.display === "block") {
                submenu.style.display = "none";
                if(arrow) arrow.style.transform = "rotate(0deg)";
            } else {
                submenu.style.display = "block";
                if(arrow) arrow.style.transform = "rotate(180deg)";
            }
        }

        function log(msg, type = '') {
            const term = document.getElementById('terminalLog');
            let colorClass = '';
            if(type === 'success') colorClass = 'log-success';
            if(type === 'warning') colorClass = 'log-warning';
            if(type === 'info') colorClass = 'log-info';
            
            term.innerHTML += `<span class="${colorClass}">${msg}</span><br>`;
            term.scrollTop = term.scrollHeight;
        }

        function limparNome(nome) {
            let n = nome;
            n = n.replace(/\[.*?\]|\(.*?\)|\{.*?\}/g, ' '); 
            n = n.replace(/\b(FHD|HD|4K|UHD|H265|HEVC|DUBLADO|LEGENDADO|VOD|FILME|BR|PT-BR|PT|TS)\b/ig, ' '); 
            return n.trim().replace(/\s+/g, ' '); 
        }

        async function processarLote(endpoint, labelMedia, tmdbType) {
            log(`<br>[SISTEMA] Buscando ${labelMedia} no banco...`, 'info');
            
            const res = await fetch(`?action=${endpoint}`);
            const rawText = await res.text();
            
            let data;
            try {
                data = JSON.parse(rawText);
            } catch(parseErr) {
                log(`[ERRO CRÍTICO] Falha de comunicação. A hospedagem bloqueou a leitura de ${labelMedia}.`, 'warning');
                return { corrigidos: 0, ignorados: 0, sucesso: false };
            }
            
            if (data.status !== 'success') {
                log(`[ERRO FATAL] Falha ao ler banco de ${labelMedia}: ` + data.msg, 'warning');
                return { corrigidos: 0, ignorados: 0, sucesso: false };
            }

            const itens = data.data;
            const total = itens.length;
            
            if (total === 0) {
                log(`[INFO] Não há ${labelMedia} precisando de correção neste lote.`, 'success');
                return { corrigidos: 0, ignorados: 0, sucesso: true };
            }

            log(`[INFO] Encontrados ${total} ${labelMedia} sem capa. Iniciando buscas no TMDB...`, 'info');

            let corrigidos = 0;
            let ignorados = 0;
            const progressBar = document.getElementById('progressBar');

            for (let i = 0; i < total; i++) {
                const item = itens[i];
                // Puxa title (Series) ou stream_display_name (Movies)
                const nomeItem = item.title || item.stream_display_name; 
                const nomeLimpo = limparNome(nomeItem);
                
                let porcentagem = Math.round(((i + 1) / total) * 100);
                progressBar.style.width = porcentagem + '%';
                progressBar.innerText = `${labelMedia}: ${porcentagem}%`;

                try {
                    const tmdbRes = await fetch(`https://api.themoviedb.org/3/search/${tmdbType}?api_key=${tmdbKey}&language=pt-BR&query=${encodeURIComponent(nomeLimpo)}`);
                    const tmdbData = await tmdbRes.json();

                    if (tmdbData.results && tmdbData.results.length > 0) {
                        const info = tmdbData.results[0]; 
                        
                        const poster = info.poster_path ? `https://image.tmdb.org/t/p/w500${info.poster_path}` : '';
                        const backdrop = info.backdrop_path ? `https://image.tmdb.org/t/p/original${info.backdrop_path}` : '';
                        const plot = info.overview || '';
                        const rating = info.vote_average || '';

                        if (poster || plot) {
                            const fd = new FormData();
                            fd.append('id', item.id);
                            fd.append('type', data.type); // 'movie' ou 'tv'
                            fd.append('icon', poster);
                            fd.append('plot', plot);
                            fd.append('rating', rating);
                            fd.append('backdrop', backdrop);

                            await fetch('?action=update_media', { method: 'POST', body: fd });
                            
                            log(`[SUCESSO] ID ${item.id} | ${nomeLimpo} -> Capa conectada!`, 'success');
                            corrigidos++;
                        } else {
                            log(`[PULOU] ID ${item.id} | ${nomeLimpo} -> TMDB retornou vazio.`, 'warning');
                            ignorados++;
                        }
                    } else {
                        log(`[NÃO ENCONTRADO] ID ${item.id} | ${nomeLimpo} -> TMDB não achou.`, 'warning');
                        ignorados++;
                    }
                    
                    await new Promise(r => setTimeout(r, 250));

                } catch (e) {
                    log(`[ERRO] Falha ao processar ID ${item.id}: ` + e.message, 'warning');
                }
            }
            
            return { corrigidos, ignorados, sucesso: true };
        }

        async function iniciarRobo() {
            if(isRunning) return;
            isRunning = true;
            
            const btn = document.getElementById('btnStartFix');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> O ROBÔ ESTÁ TRABALHANDO...';
            
            document.getElementById('progressContainer').style.display = 'block';
            
            try {
                // Etapa 1: Filmes
                const resFilmes = await processarLote('get_broken_movies', 'Filmes', 'movie');
                
                // Etapa 2: Séries
                const resSeries = await processarLote('get_broken_series', 'Séries', 'tv');
                
                log(`<br>[CONCLUÍDO] Varredura Finalizada!`, 'info');
                log(`- Filmes (Corrigidos: ${resFilmes.corrigidos} | Pulados: ${resFilmes.ignorados})`, 'success');
                log(`- Séries (Corrigidos: ${resSeries.corrigidos} | Pulados: ${resSeries.ignorados})`, 'success');
                
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-play"></i> CONTINUAR VARREDURA';
                isRunning = false;
                
            } catch (err) {
                log('[ERRO CRÍTICO] Ocorreu uma falha no fluxo principal.', 'warning');
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-play"></i> TENTAR NOVAMENTE';
                isRunning = false;
            }
        }
    </script>
</body>
</html>