<?php
session_start();
ini_set('display_errors', 0);
error_reporting(0);

require_once 'config.php';

// CORREÇÃO: Força a conexão interna, pois as tabelas de pagamento só existem no painel local
$pdo = getConexaoInterna(); 
$pdo->exec("SET NAMES utf8mb4");

// --- PROTEÇÃO DE ADMINISTRADOR ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    die("<div style='padding:20px; font-family:sans-serif; text-align:center;'>Acesso negado. Apenas administradores podem acessar esta página. <br><a href='dashboard.php'>Voltar</a></div>");
}

$id_usuario = $_SESSION['user_id'];
$nome_usuario = $_SESSION['username'] ?? 'Admin';
$role = 'admin';

// --- GERAÇÃO DINÂMICA DA URL DO WEBHOOK ---
$is_https = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
$protocolo = $is_https ? "https://" : "http://";
$dominio = $_SERVER['HTTP_HOST'];

$url_webhook_mp = $protocolo . $dominio . "/webhook_mp.php";
$url_webhook_asaas = $protocolo . $dominio . "/webhook_asaas.php";

// ========================================================================
// --- AUTO-CRIAÇÃO DAS TABELAS ---
// ========================================================================
try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("CREATE TABLE IF NOT EXISTS `planos_creditos` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `titulo` varchar(100) NOT NULL,
        `qtd_creditos` int(11) NOT NULL,
        `valor` decimal(10,2) NOT NULL,
        `icone` varchar(50) DEFAULT 'fas fa-star',
        `is_popular` int(1) DEFAULT 0,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    
    // Garante que a tabela de pagamentos também exista para não dar erro
    $pdo->exec("CREATE TABLE IF NOT EXISTS `config_pagamentos` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `mp_token` varchar(255) DEFAULT NULL,
        `asaas_token` varchar(255) DEFAULT NULL,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    
} catch (PDOException $e) {}

// --- AÇÕES DO FORMULÁRIO ---
$mensagem = "";

if (isset($_POST['acao']) && $_POST['acao'] == 'salvar_gateways') {
    $mp_token = $_POST['mp_token'];
    $asaas_token = $_POST['asaas_token'];
    
    $check = $pdo->query("SELECT id FROM config_pagamentos")->rowCount();
    if ($check > 0) {
        $stmt = $pdo->prepare("UPDATE config_pagamentos SET mp_token = ?, asaas_token = ?");
        $stmt->execute([$mp_token, $asaas_token]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO config_pagamentos (mp_token, asaas_token) VALUES (?, ?)");
        $stmt->execute([$mp_token, $asaas_token]);
    }
    $mensagem = "<div class='alert-success'><i class='fas fa-check-circle'></i> Gateways salvos com sucesso!</div>";
}

if (isset($_POST['acao']) && $_POST['acao'] == 'adicionar_plano') {
    $titulo = $_POST['titulo'];
    $qtd_creditos = (int)$_POST['qtd_creditos'];
    $valor = str_replace(',', '.', str_replace('.', '', $_POST['valor']));
    $icone = $_POST['icone'];
    $is_popular = isset($_POST['is_popular']) ? 1 : 0;

    $stmt = $pdo->prepare("INSERT INTO planos_creditos (titulo, qtd_creditos, valor, icone, is_popular) VALUES (?, ?, ?, ?, ?)");
    if($stmt->execute([$titulo, $qtd_creditos, $valor, $icone, $is_popular])) {
        $mensagem = "<div class='alert-success'><i class='fas fa-check-circle'></i> Plano adicionado com sucesso!</div>";
    }
}

if (isset($_POST['acao']) && $_POST['acao'] == 'editar_plano') {
    $id_plano = (int)$_POST['edit_id'];
    $titulo = $_POST['edit_titulo'];
    $qtd_creditos = (int)$_POST['edit_qtd_creditos'];
    $valor = str_replace(',', '.', str_replace('.', '', $_POST['edit_valor']));
    $icone = $_POST['edit_icone'];
    $is_popular = isset($_POST['edit_is_popular']) ? 1 : 0;

    $stmt = $pdo->prepare("UPDATE planos_creditos SET titulo=?, qtd_creditos=?, valor=?, icone=?, is_popular=? WHERE id=?");
    if($stmt->execute([$titulo, $qtd_creditos, $valor, $icone, $is_popular, $id_plano])) {
        $mensagem = "<div class='alert-success'><i class='fas fa-check-circle'></i> Plano atualizado com sucesso!</div>";
    }
}

if (isset($_GET['deletar'])) {
    $id_del = (int)$_GET['deletar'];
    $pdo->query("DELETE FROM planos_creditos WHERE id = $id_del");
    header("Location: admin_loja_creditos.php");
    exit;
}

// --- BUSCA DADOS ATUAIS ---
$config_pag = $pdo->query("SELECT * FROM config_pagamentos LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$planos = $pdo->query("SELECT * FROM planos_creditos ORDER BY valor ASC")->fetchAll(PDO::FETCH_ASSOC);

// Buscar nome do painel
$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 = $config_painel['nome_painel'] ?: $nome_painel;
        $logo_url = $config_painel['logo_url'] ?: $logo_url;
        $cor_primaria = $config_painel['cor_primaria'] ?: $cor_primaria;
    }
} catch (Exception $e) { }
?>
<!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>Admin Loja - <?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; --info: #17a2b8; }
        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); flex-shrink: 0; z-index: 1001; }
        .sidebar-header { padding: 25px 20px; text-align: center; color: white; border-bottom: 1px solid var(--border-color); font-weight: bold; font-size: 18px;}
        .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(0, 123, 255, 0.2); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; }
        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; font-size: 14px; }
        .menu-item i { 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: 3px solid var(--accent); }
        .menu-item.active i { color: var(--accent); }
        .menu-category { padding: 20px 20px 8px; font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; }
        .logout-btn { padding: 15px; background-color: #dc3545; color: white; text-align: center; text-decoration: none; font-weight: bold; }

        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; position: relative; width: 100vw; max-width: 100%;}
        .topbar { padding: 15px 30px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center;}
        
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 24px; cursor: pointer; padding-right: 15px;}
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); z-index: 1000; }

        .content-area { padding: 30px; }
        .card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; padding: 25px; margin-bottom: 25px; }
        .card h3 { margin-top: 0; color: white; border-bottom: 1px solid var(--border-color); padding-bottom: 15px; margin-bottom: 20px; }
        
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 8px; font-size: 13px; font-weight: bold; color: var(--text-muted); }
        .form-control { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 6px; box-sizing: border-box; }
        .form-control:focus { outline: none; border-color: var(--accent); }
        
        .btn { padding: 12px 20px; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; color: white; transition: 0.2s; }
        .btn-primary { background: var(--accent); }
        .btn-primary:hover { filter: brightness(1.1); }
        .btn-danger { background: var(--danger); text-decoration: none; padding: 8px 12px; font-size: 12px; display: inline-block;}
        .btn-info { background: var(--info); text-decoration: none; padding: 8px 12px; font-size: 12px; margin-right: 5px;}
        
        .alert-success { background: rgba(40, 167, 69, 0.15); border: 1px solid var(--success); color: var(--success); padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; }

        .webhook-box { background: rgba(23, 162, 184, 0.1); border: 1px dashed var(--info); padding: 15px; border-radius: 8px; margin-top: 15px; margin-bottom: 10px;}
        .webhook-box p { margin: 0 0 8px 0; font-size: 13px; color: var(--info); font-weight: bold; display: flex; align-items: center; gap: 5px;}
        .copy-group { display: flex; gap: 8px; }
        .copy-group input { flex: 1; background: #121519; border: 1px solid var(--border-color); color: var(--text-main); padding: 10px; border-radius: 6px; font-size: 13px; outline: none; min-width: 0; }
        .copy-group button { background: var(--info); color: white; border: none; padding: 10px 15px; border-radius: 6px; cursor: pointer; font-weight: bold; transition: 0.2s; display: flex; align-items: center; gap: 5px; flex-shrink: 0;}
        .copy-group button:hover { filter: brightness(1.1); }
        
        .btn-tutorial { background: #8b5cf6; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: bold; transition: 0.2s; display: flex; align-items: center; gap: 8px; margin-top: 10px; width: 100%; justify-content: center; font-size: 13px; }
        .btn-tutorial:hover { background: #7c3aed; }

        .table-responsive { overflow-x: auto; width: 100%; display: block; -webkit-overflow-scrolling: touch; }
        .tabela-planos { width: 100%; border-collapse: collapse; margin-top: 20px; min-width: 600px; }
        .tabela-planos th, .tabela-planos td { padding: 15px; text-align: left; border-bottom: 1px solid var(--border-color); }
        .tabela-planos th { color: var(--text-muted); font-size: 12px; text-transform: uppercase; }
        .tabela-planos td { color: white; font-size: 14px; }
        .tabela-planos tr:hover { background: rgba(0,0,0,0.1); }
        .badge-popular { background: var(--warning); color: #121519; padding: 3px 8px; border-radius: 12px; font-size: 10px; font-weight: bold; }
        
        .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }

        /* MODAIS */
        .modal-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 2000; justify-content: center; align-items: center; backdrop-filter: blur(5px); }
        .modal-box { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 15px; padding: 30px; width: 90%; max-width: 500px; position: relative; box-shadow: 0 20px 40px rgba(0,0,0,0.5); }
        .modal-close { position: absolute; top: 15px; right: 20px; background: none; border: none; color: var(--text-muted); font-size: 24px; cursor: pointer; }
        .modal-close:hover { color: var(--danger); }

        .tutorial-content { text-align: left; color: var(--text-main); font-size: 14px; line-height: 1.6; max-height: 400px; overflow-y: auto; padding-right: 10px; }
        .tutorial-content h4 { color: var(--accent); margin-top: 15px; margin-bottom: 15px; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; font-size: 16px; }
        .tutorial-content ol { padding-left: 20px; margin: 0; }
        .tutorial-content li { margin-bottom: 15px; }
        .tutorial-content strong { color: white; }

        /* ADAPTAÇÃO PARA CELULAR */
        @media (max-width: 768px) {
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .sidebar.active { left: 0; }
            .menu-toggle { display: block; }
            .sidebar-overlay.active { display: block; }
            .topbar { padding: 15px 20px; justify-content: flex-start; }
            .topbar h2 { font-size: 16px !important; }
            .content-area { padding: 15px; }
            .grid-2 { grid-template-columns: 1fr; } /* Transforma as 2 colunas em 1 só */
            .card { padding: 15px; }
            .copy-group { flex-direction: column; } /* Quebra o botão de copiar para baixo no mobile */
        }
    </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)): ?>
                <img src="<?php echo htmlspecialchars($logo_url); ?>" 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">Administrador</span>
        </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; color:white;">Configurações da Loja de Créditos</h2>
            </div>
        </header>

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

            <div class="grid-2">
                <div class="card">
                    <h3><i class="fas fa-university" style="color: var(--info);"></i> Conexão com Bancos</h3>
                    <form method="POST">
                        <input type="hidden" name="acao" value="salvar_gateways">
                        
                        <div class="form-group">
                            <label><i class="fas fa-handshake"></i> Token Mercado Pago (Access Token):</label>
                            <input type="text" name="mp_token" class="form-control" value="<?php echo htmlspecialchars($config_pag['mp_token'] ?? ''); ?>" placeholder="APP_USR-123456789...">
                        </div>
                        
                        <div class="webhook-box">
                            <p><i class="fas fa-link"></i> URL de Retorno (Webhook) - Mercado Pago:</p>
                            <div class="copy-group">
                                <input type="text" id="link_mp" value="<?php echo $url_webhook_mp; ?>" readonly>
                                <button type="button" onclick="copiarLink('link_mp')"><i class="fas fa-copy"></i> Copiar</button>
                            </div>
                            <button type="button" class="btn-tutorial" onclick="abrirTutorial('mp')"><i class="fas fa-chalkboard-teacher"></i> Como configurar no Mercado Pago?</button>
                        </div>

                        <div class="form-group" style="margin-top: 30px;">
                            <label><i class="fas fa-building"></i> API Key Asaas:</label>
                            <input type="text" name="asaas_token" class="form-control" value="<?php echo htmlspecialchars($config_pag['asaas_token'] ?? ''); ?>" placeholder="$aact_YTU5YTE0M2M...">
                        </div>

                        <div class="webhook-box">
                            <p><i class="fas fa-link"></i> URL de Retorno (Webhook) - Asaas:</p>
                            <div class="copy-group">
                                <input type="text" id="link_asaas" value="<?php echo $url_webhook_asaas; ?>" readonly>
                                <button type="button" onclick="copiarLink('link_asaas')"><i class="fas fa-copy"></i> Copiar</button>
                            </div>
                            <button type="button" class="btn-tutorial" onclick="abrirTutorial('asaas')"><i class="fas fa-chalkboard-teacher"></i> Como configurar no Asaas?</button>
                        </div>

                        <button type="submit" class="btn btn-primary" style="width: 100%; margin-top: 20px;"><i class="fas fa-save"></i> Salvar Tokens</button>
                    </form>
                </div>

                <div class="card">
                    <h3><i class="fas fa-plus-circle" style="color: var(--success);"></i> Criar Novo Pacote de Créditos</h3>
                    <form method="POST">
                        <input type="hidden" name="acao" value="adicionar_plano">
                        
                        <div class="form-group">
                            <label>Nome do Pacote (Ex: Básico, Master):</label>
                            <input type="text" name="titulo" class="form-control" required>
                        </div>

                        <div class="grid-2">
                            <div class="form-group">
                                <label>Quantidade de Créditos:</label>
                                <input type="number" name="qtd_creditos" class="form-control" required min="1">
                            </div>
                            <div class="form-group">
                                <label>Valor (R$):</label>
                                <input type="text" name="valor" class="form-control" required placeholder="Ex: 50.00">
                            </div>
                        </div>

                        <div class="grid-2">
                            <div class="form-group">
                                <label>Ícone (FontAwesome):</label>
                                <input type="text" name="icone" class="form-control" value="fas fa-star">
                            </div>
                            <div class="form-group" style="display: flex; align-items: center; gap: 10px; margin-top: 25px;">
                                <input type="checkbox" name="is_popular" id="pop" style="width: 20px; height: 20px;">
                                <label for="pop" style="margin: 0; color: white;">Marcar como "Mais Vendido"</label>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-primary" style="background: var(--success); width: 100%; margin-top: 10px;"><i class="fas fa-plus"></i> Adicionar Plano</button>
                    </form>
                </div>
            </div>

            <div class="card">
                <h3><i class="fas fa-list" style="color: var(--accent);"></i> Pacotes Ativos na Loja</h3>
                
                <?php if (count($planos) > 0): ?>
                    <div class="table-responsive">
                        <table class="tabela-planos">
                            <thead>
                                <tr>
                                    <th>Pacote</th>
                                    <th>Créditos</th>
                                    <th>Preço (R$)</th>
                                    <th>Destaque</th>
                                    <th style="text-align: right;">Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($planos as $p): ?>
                                <tr>
                                    <td><i class="<?php echo $p['icone']; ?>" style="color: var(--text-muted); margin-right: 8px;"></i> <?php echo htmlspecialchars($p['titulo']); ?></td>
                                    <td><strong style="color: var(--accent);"><?php echo $p['qtd_creditos']; ?></strong> crds</td>
                                    <td><strong style="color: var(--success);">R$ <?php echo number_format($p['valor'], 2, ',', '.'); ?></strong></td>
                                    <td><?php echo $p['is_popular'] ? '<span class="badge-popular">Mais Vendido</span>' : '-'; ?></td>
                                    <td style="text-align: right; min-width: 180px;">
                                        <button class="btn btn-info" onclick="abrirEdicao(<?php echo htmlspecialchars(json_encode($p)); ?>)"><i class="fas fa-edit"></i> Editar</button>
                                        <a href="?deletar=<?php echo $p['id']; ?>" class="btn-danger" onclick="return confirm('Certeza que deseja apagar este plano?');"><i class="fas fa-trash"></i> Apagar</a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <p style="color: var(--text-muted); text-align: center; padding: 20px;">Nenhum pacote cadastrado. Crie um pacote acima para ele aparecer na loja dos revendedores.</p>
                <?php endif; ?>
            </div>

        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <div class="modal-overlay" id="modalEditar">
        <div class="modal-box">
            <button class="modal-close" onclick="fecharEdicao()"><i class="fas fa-times"></i></button>
            <h3 style="margin-top: 0; color: white; border-bottom: 1px solid var(--border-color); padding-bottom: 15px;"><i class="fas fa-edit" style="color: var(--info);"></i> Editar Plano</h3>
            
            <form method="POST">
                <input type="hidden" name="acao" value="editar_plano">
                <input type="hidden" name="edit_id" id="edit_id">
                
                <div class="form-group" style="text-align: left;">
                    <label>Nome do Pacote:</label>
                    <input type="text" name="edit_titulo" id="edit_titulo" class="form-control" required>
                </div>

                <div class="grid-2" style="text-align: left;">
                    <div class="form-group">
                        <label>Créditos:</label>
                        <input type="number" name="edit_qtd_creditos" id="edit_qtd_creditos" class="form-control" required min="1">
                    </div>
                    <div class="form-group">
                        <label>Valor (R$):</label>
                        <input type="text" name="edit_valor" id="edit_valor" class="form-control" required>
                    </div>
                </div>

                <div class="grid-2" style="text-align: left;">
                    <div class="form-group">
                        <label>Ícone:</label>
                        <input type="text" name="edit_icone" id="edit_icone" class="form-control">
                    </div>
                    <div class="form-group" style="display: flex; align-items: center; gap: 10px; margin-top: 25px;">
                        <input type="checkbox" name="edit_is_popular" id="edit_is_popular" style="width: 20px; height: 20px;">
                        <label for="edit_is_popular" style="margin: 0; color: white;">"Mais Vendido"</label>
                    </div>
                </div>

                <button type="submit" class="btn btn-primary" style="background: var(--info); width: 100%; margin-top: 15px;"><i class="fas fa-save"></i> Salvar Alterações</button>
            </form>
        </div>
    </div>

    <div class="modal-overlay" id="modalTutorial">
        <div class="modal-box" style="max-width: 600px;">
            <button class="modal-close" onclick="fecharTutorial()"><i class="fas fa-times"></i></button>
            <h3 style="margin-top: 0; color: white; border-bottom: 1px solid var(--border-color); padding-bottom: 15px; text-align: left;">
                <i class="fas fa-book-open" style="color: #8b5cf6;"></i> Passo a Passo: <span id="tutTitulo"></span>
            </h3>
            
            <div class="tutorial-content" id="tutConteudoMP" style="display: none;">
                <h4>Ativando as Notificações no Mercado Pago</h4>
                <ol>
                    <li>Acesse o site <strong><a href="https://www.mercadopago.com.br/developers/panel/applications" target="_blank" style="color:var(--info);">Mercado Pago Developers</a></strong> e faça login com a sua conta.</li>
                    <li>No menu esquerdo, clique em <strong>"Suas integrações"</strong> e selecione a sua Aplicação (ou crie uma nova caso ainda não tenha feito isso para pegar o Token).</li>
                    <li>No menu lateral de dentro da sua aplicação, procure por <strong>"Notificações"</strong> e clique em <strong>"Webhooks"</strong>.</li>
                    <li>No campo <strong>"URL de produção"</strong>, cole o link que você copiou aqui no nosso painel.</li>
                    <li>Na seção <strong>"Eventos"</strong>, marque apenas a caixinha <strong>"Pagamentos" (Payments)</strong>.</li>
                    <li>Desça até o final e clique em <strong>"Salvar"</strong>. Pronto! O Mercado Pago já vai começar a avisar o nosso painel.</li>
                </ol>
            </div>

            <div class="tutorial-content" id="tutConteudoAsaas" style="display: none;">
                <h4>Ativando as Notificações no Asaas</h4>
                <ol>
                    <li>Acesse a sua conta do <strong><a href="https://www.asaas.com" target="_blank" style="color:var(--info);">Asaas</a></strong> pelo computador.</li>
                    <li>No canto superior direito, clique na sua foto de perfil / nome e vá em <strong>"Minha Conta"</strong> (ou Configurações).</li>
                    <li>No menu lateral esquerdo, procure pela aba <strong>"Integrações"</strong> e depois clique em <strong>"Webhooks"</strong>.</li>
                    <li>Clique no botão para <strong>"Adicionar Webhook"</strong>.</li>
                    <li>Dê um nome para ele (ex: <em>Webhook Painel IPTV</em>), e no campo <strong>"URL"</strong> cole o link que você copiou aqui da página.</li>
                    <li>Na seção de <strong>Eventos (Interrupções)</strong>, marque apenas as opções referentes a pagamento concluído: <strong>"Pagamento Recebido"</strong> e <strong>"Pagamento Confirmado"</strong>.</li>
                    <li>Salve as configurações. O Asaas agora está conectado e funcionando!</li>
                </ol>
            </div>
        </div>
    </div>

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

        function copiarLink(idElemento) {
            var copyText = document.getElementById(idElemento);
            copyText.select();
            copyText.setSelectionRange(0, 99999);
            document.execCommand("copy");
            alert("URL copiada com sucesso! Siga o tutorial para configurar no banco.");
        }

        function abrirEdicao(plano) {
            document.getElementById('edit_id').value = plano.id;
            document.getElementById('edit_titulo').value = plano.titulo;
            document.getElementById('edit_qtd_creditos').value = plano.qtd_creditos;
            document.getElementById('edit_valor').value = parseFloat(plano.valor).toFixed(2).replace('.', ',');
            document.getElementById('edit_icone').value = plano.icone;
            document.getElementById('edit_is_popular').checked = (plano.is_popular == 1);
            
            document.getElementById('modalEditar').style.display = 'flex';
        }

        function fecharEdicao() {
            document.getElementById('modalEditar').style.display = 'none';
        }

        // FUNÇÕES DO TUTORIAL
        function abrirTutorial(tipo) {
            document.getElementById('tutConteudoMP').style.display = 'none';
            document.getElementById('tutConteudoAsaas').style.display = 'none';
            
            if(tipo === 'mp') {
                document.getElementById('tutTitulo').innerText = 'Mercado Pago';
                document.getElementById('tutConteudoMP').style.display = 'block';
            } else {
                document.getElementById('tutTitulo').innerText = 'Asaas';
                document.getElementById('tutConteudoAsaas').style.display = 'block';
            }
            document.getElementById('modalTutorial').style.display = 'flex';
        }

        function fecharTutorial() {
            document.getElementById('modalTutorial').style.display = 'none';
        }
    </script>
</body>
</html>
