<?php
session_start();
require_once 'conexao.php';

// Verifica Login
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    header("Location: login.php"); exit;
}

$isAdmin = (isset($_SESSION['nivel']) && strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'];

// --- GARANTE QUE A TABELA DE PAGAMENTOS EXISTA E ADICIONA ASAAS ---
try {
    $connUser->exec("CREATE TABLE IF NOT EXISTS pagamentos (
        id INT AUTO_INCREMENT PRIMARY KEY,
        id_pagamento_mp VARCHAR(100),
        usuario_id VARCHAR(100),
        status VARCHAR(50),
        valor DECIMAL(10,2),
        data_pagamento TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
} catch(Exception $e) {}

// Adiciona coluna do Asaas na tabela mp_revendedores silenciosamente
try { $connUser->exec("ALTER TABLE mp_revendedores ADD COLUMN access_token_asaas VARCHAR(255) DEFAULT ''"); } catch(Exception $e) {}


// --- 3. CORREÇÃO DO MENU LATERAL (MENSAGENS NÃO LIDAS) ---
$total_msg_nao_lidas = 0;
try {
    $stmtMsg = $connUser->prepare("SELECT COUNT(*) FROM chamados_suporte WHERE destinatario = ? AND lida = 'nao'");
    $stmtMsg->execute([$usuarioLogado]);
    $total_msg_nao_lidas = $stmtMsg->fetchColumn();
} catch (Exception $e) { }



$logos_disponiveis = [
    'claro.png' => 'Claro',
    'net.png'   => 'NET',
    'sky.png'   => 'Sky',
    'vivo.png'  => 'Vivo',
    'iptv.png'  => 'Genérico'
];

$msg = ""; $msg_tipo = "";
$tab_ativa = 'config'; 

// --- 1. SALVAR CONFIGURAÇÕES DE PAGAMENTO (MP E ASAAS) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['salvar_config'])) {
    $token = trim($_POST['token_mp']);
    $token_asaas = trim($_POST['token_asaas']); // Novo campo Asaas
    $banco = trim($_POST['dados_bancarios']);
    
    $sql = "INSERT INTO mp_revendedores (usuario_revendedor, access_token, access_token_asaas, dados_bancarios) VALUES (?, ?, ?, ?) 
            ON DUPLICATE KEY UPDATE access_token = VALUES(access_token), access_token_asaas = VALUES(access_token_asaas), dados_bancarios = VALUES(dados_bancarios)";
    try {
        $connUser->prepare($sql)->execute([$usuarioLogado, $token, $token_asaas, $banco]);
        $msg = "Configurações financeiras salvas com sucesso!"; $msg_tipo = "success";
        $tab_ativa = 'config';
    } catch (Exception $e) {
        $msg = "Erro ao salvar: " . $e->getMessage(); $msg_tipo = "danger";
    }
}

// --- 2. CRIAR NOVO PLANO ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['criar_plano'])) {
    $nome = trim($_POST['nome']);
    $dias = (int)$_POST['dias'];
    $valor = str_replace(',', '.', $_POST['valor']); 
    $logo = $_POST['logo_perfil'];

    if ($nome && $dias > 0 && $valor > 0) {
        $sql = "INSERT INTO planos_revenda (id_revendedor, nome_plano, dias, valor, logo_perfil) VALUES (?, ?, ?, ?, ?)";
        $connUser->prepare($sql)->execute([$usuarioLogado, $nome, $dias, $valor, $logo]);
        $msg = "Plano criado com sucesso!"; $msg_tipo = "success";
        $tab_ativa = 'planos';
    }
}

// --- 3. ATUALIZAR PLANO ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['atualizar_plano'])) {
    $id_plano = (int)$_POST['id_plano'];
    $nome = trim($_POST['nome']);
    $dias = (int)$_POST['dias'];
    $valor = str_replace(',', '.', $_POST['valor']); 
    $logo = $_POST['logo_perfil'];

    if ($nome && $dias > 0 && $valor > 0) {
        $sql = "UPDATE planos_revenda SET nome_plano=?, dias=?, valor=?, logo_perfil=? WHERE id=? AND id_revendedor=?";
        $connUser->prepare($sql)->execute([$nome, $dias, $valor, $logo, $id_plano, $usuarioLogado]);
        $msg = "Plano atualizado com sucesso!"; $msg_tipo = "success";
        $tab_ativa = 'planos';
    }
}

// --- 4. EXCLUIR PLANO ---
if (isset($_GET['del'])) {
    $id = (int)$_GET['del'];
    $connUser->prepare("DELETE FROM planos_revenda WHERE id = ? AND id_revendedor = ?")->execute([$id, $usuarioLogado]);
    header("Location: config_mp_revenda.php?tab=planos"); exit;
}

// --- BUSCAS NO BANCO ---
$token_atual = ""; $token_asaas_atual = ""; $banco_atual = "";
try {
    $stmt = $connUser->prepare("SELECT access_token, access_token_asaas, dados_bancarios FROM mp_revendedores WHERE usuario_revendedor = ?");
    $stmt->execute([$usuarioLogado]);
    $dados = $stmt->fetch(PDO::FETCH_ASSOC);
    if($dados) { 
        $token_atual = $dados['access_token']; 
        $token_asaas_atual = $dados['access_token_asaas'] ?? ''; 
        $banco_atual = $dados['dados_bancarios']; 
    }
} catch (Exception $e) {}

$stmtPlanos = $connUser->prepare("SELECT * FROM planos_revenda WHERE id_revendedor = ? ORDER BY dias ASC");
$stmtPlanos->execute([$usuarioLogado]);
$meus_planos = $stmtPlanos->fetchAll(PDO::FETCH_ASSOC);

$vendas = [];
try {
    $stmtPagamentos = $connUser->prepare("SELECT p.* FROM pagamentos p JOIN usuario u ON p.usuario_id = u.usuario WHERE u.CadUser = ? ORDER BY p.data_pagamento DESC LIMIT 50");
    $stmtPagamentos->execute([$usuarioLogado]);
    $vendas = $stmtPagamentos->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}

$plano_editar = null;
if (isset($_GET['edit'])) {
    $id_edit = (int)$_GET['edit'];
    $stmt = $connUser->prepare("SELECT * FROM planos_revenda WHERE id=? AND id_revendedor=?");
    $stmt->execute([$id_edit, $usuarioLogado]);
    $plano_editar = $stmt->fetch(PDO::FETCH_ASSOC);
    $tab_ativa = 'planos';
}
if (isset($_GET['tab'])) { $tab_ativa = $_GET['tab']; }

$nomePainel = "IPTV PANEL"; $corPrimaria = "#7367f0"; 
try { $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(); if($conf) { $nomePainel = $conf['NomePainel']; $corPrimaria = $conf['TemaPainel']; } } catch(Exception $e){}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <?php include 'tema_global.php'; ?>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Financeiro | <?= htmlspecialchars($nomePainel) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { 
            --primary: <?= $corPrimaria ?>; 
            --bg-body: #151521; 
            --bg-card: #1e1e2d; 
            --text-color: #d0d2d6; 
            --border-color: #2b2b40;
            --overlay-desk: rgba(0, 0, 0, 0.65); 
            --overlay-mob: rgba(0, 0, 0, 0.85);
        }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; padding: 0; }
        
        /* SCROLLBAR */
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-track { background: var(--bg-body); }
        ::-webkit-scrollbar-thumb { background: #444; border-radius: 4px; }
        ::-webkit-scrollbar-thumb:hover { background: var(--primary); }

        /* MENU LATERAL */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid var(--border-color); z-index: 1050; padding: 20px; overflow-y: auto; transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .sidebar .nav-link { white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; color: #a6a6b7; padding: 12px 15px; border-radius: 8px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .sidebar .nav-link i.fa-fw { margin-right: 8px; text-align: center; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }

        .main-content { margin-left: 260px; transition: 0.3s; min-height: 100vh; padding-bottom: 30px;}
        
        /* HEADER */
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--overlay-desk) 100%), var(--primary); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 30px;}
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; margin: 0; }

        /* CARDS E ELEMENTOS */
        .card-custom { background: var(--bg-card) !important; border: 1px solid var(--border-color); border-radius: 12px; }
        .form-control, .form-select { background: #111 !important; border: 1px solid var(--border-color) !important; color: #fff !important; border-radius: 8px; padding: 10px 15px; transition: 0.2s; }
        .form-control:focus, .form-select:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 0.25rem rgba(115, 103, 240, 0.25) !important; }
        
        /* MENU ABAS (TABS) PREMIUM */
        .nav-pills-custom { background: rgba(0,0,0,0.2); padding: 8px; border-radius: 12px; gap: 8px; display: flex; flex-wrap: wrap; }
        .nav-pills-custom .nav-link { color: #a6a6b7; border-radius: 8px; font-weight: 600; padding: 12px 20px; transition: 0.3s; flex: 1; text-align: center; }
        .nav-pills-custom .nav-link:hover { color: #fff; background: rgba(255,255,255,0.05); }
        .nav-pills-custom .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 10px rgba(0,0,0,0.3); }

        .label-visivel { color: #ffffff !important; font-weight: 700 !important; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; display: block; margin-bottom: 8px; }
        
        /* TABELAS */
        .table-dark { --bs-table-bg: transparent; margin-bottom: 0; border-collapse: separate; border-spacing: 0; }
        .table-dark th { border-bottom: 1px solid var(--border-color); color: #a6a6b7; font-size: 0.8rem; text-transform: uppercase; font-weight: 700; padding: 15px; white-space: nowrap;}
        .table-dark td { border-bottom: 1px solid var(--border-color); vertical-align: middle; padding: 15px; font-size: 0.9rem;}

        /* RADIO BUTTON LOGOS */
        .logo-option { cursor: pointer; border: 2px solid var(--border-color); border-radius: 10px; padding: 5px; background: #111; width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; position: relative; overflow: hidden; transition: 0.2s;}
        .logo-option input { position: absolute; opacity: 0; inset: 0; cursor: pointer; }
        .logo-option img { max-width: 35px !important; max-height: 35px !important; height: auto !important; width: auto !important; object-fit: contain !important; transition: 0.2s;}
        .logo-option:has(input:checked) { border-color: var(--primary); background: rgba(115, 103, 240, 0.1); transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.2);}
        .logo-preview-table { width: 22px !important; height: 22px !important; object-fit: contain !important; }

        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; } 
            .mobile-toggle { display: block !important; margin-right: 15px; } 
            .top-header { flex-direction: row; padding: 15px 20px; background: linear-gradient(var(--overlay-mob), var(--overlay-mob)), var(--primary); }
            .nav-pills-custom { flex-direction: column; }
            .nav-pills-custom .nav-link { width: 100%; text-align: left; }
        }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 1040; backdrop-filter: blur(3px); }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>
<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<main class="main-content">
    <div class="top-header">
        <div class="d-flex align-items-center w-100">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title"><i class="fas fa-wallet me-2 d-none d-md-inline-block"></i> Configuração Financeira</div>
        </div>
        <div class="d-none d-lg-block ms-4 text-white-50 small fw-bold text-nowrap bg-dark px-3 py-1 rounded-pill border border-secondary shadow-sm">
            <i class="fas fa-user-circle me-1 text-primary"></i> <?= htmlspecialchars($usuarioLogado) ?>
        </div>
    </div>

    <div class="container-fluid px-3 px-md-4">
        <?php if($msg): ?>
            <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm mb-4 fw-bold">
                <?= $msg ?>
                <button class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- ABAS PREMIUM -->
        <ul class="nav nav-pills-custom mb-4 shadow-sm" id="finTabs">
            <li class="nav-item">
                <button class="nav-link <?= $tab_ativa == 'config' ? 'active' : '' ?>" data-bs-toggle="tab" data-bs-target="#config"><i class="fas fa-cog me-2"></i> Configurações da API</button>
            </li>
            <li class="nav-item">
                <button class="nav-link <?= $tab_ativa == 'planos' ? 'active' : '' ?>" data-bs-toggle="tab" data-bs-target="#planos"><i class="fas fa-tags me-2"></i> Meus Planos de Venda</button>
            </li>
            <li class="nav-item">
                <button class="nav-link <?= $tab_ativa == 'vendas' ? 'active' : '' ?>" data-bs-toggle="tab" data-bs-target="#vendas"><i class="fas fa-shopping-cart me-2"></i> Relatório de Vendas</button>
            </li>
        </ul>

        <div class="tab-content">
            <!-- ABA: CONFIGURAÇÕES -->
            <div class="tab-pane fade <?= $tab_ativa == 'config' ? 'show active' : '' ?>" id="config">
                <form method="POST" class="card card-custom p-4 shadow-sm border-0">
                    <input type="hidden" name="salvar_config" value="1">
                    
                    <h5 class="fw-bold mb-4" style="color: var(--text-color);"><i class="fas fa-bolt text-warning me-2"></i> Gateways de Pagamento (PIX Automático)</h5>
                    
                    <div class="row g-4">
                        <div class="col-md-6">
                            <div class="p-3 rounded" style="background: rgba(0, 207, 232, 0.05); border: 1px solid rgba(0, 207, 232, 0.2);">
                                <label class="label-visivel text-info"><i class="fas fa-handshake me-1"></i> MERCADO PAGO (Access Token)</label>
                                <input type="text" name="token_mp" class="form-control" value="<?= htmlspecialchars($token_atual) ?>" placeholder="APP_USR-...">
                                <small class="text-white-50 mt-2 d-block"><i class="fas fa-info-circle me-1"></i> Token de Produção para gerar PIX Automático via Mercado Pago.</small>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="p-3 rounded" style="background: rgba(115, 103, 240, 0.05); border: 1px solid rgba(115, 103, 240, 0.2);">
                                <label class="label-visivel text-primary"><i class="fas fa-money-check-alt me-1"></i> ASAAS (API Key)</label>
                                <input type="text" name="token_asaas" class="form-control" value="<?= htmlspecialchars($token_asaas_atual) ?>" placeholder="$aact_...">
                                <small class="text-white-50 mt-2 d-block"><i class="fas fa-info-circle me-1"></i> Chave de API do Asaas para gerar PIX Automático.</small>
                            </div>
                        </div>
                    </div>

                    <?php 
                        $protocolo_wh = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                        $pasta_wh = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
                        $url_wh_base = $protocolo_wh . $_SERVER['HTTP_HOST'] . $pasta_wh;
                    ?>
                    
                    <hr class="border-secondary my-4">
                    <h5 class="fw-bold mb-4" style="color: var(--text-color);"><i class="fas fa-link text-info me-2"></i> URLs de Webhook (Aprovação Automática)</h5>
                    <div class="row g-4">
                        <?php if ($isAdmin): ?>
                        <div class="col-md-6">
                            <div class="p-3 rounded bg-dark border border-secondary h-100">
                                <label class="label-visivel text-warning"><i class="fas fa-user-tie me-1"></i> Webhook Revendedores (Apenas Admin)</label>
                                <div class="input-group">
                                    <input type="text" class="form-control text-white-50" value="<?= $url_wh_base ?>/webhook.php" readonly id="wh_rev">
                                    <button class="btn btn-outline-secondary" type="button" onclick="copiarValor('wh_rev')" title="Copiar"><i class="fas fa-copy"></i></button>
                                </div>
                                <small class="text-white-50 mt-2 d-block"><i class="fas fa-info-circle me-1"></i> Configure no seu Mercado Pago/Asaas para aprovar a venda de créditos dos revendedores.</small>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <div class="col-md-6">
                            <div class="p-3 rounded bg-dark border border-secondary h-100">
                                <label class="label-visivel text-success"><i class="fas fa-users me-1"></i> Webhook Clientes Finais</label>
                                <div class="input-group">
                                    <input type="text" class="form-control text-white-50" value="<?= $url_wh_base ?>/webhook_cliente.php" readonly id="wh_cli">
                                    <button class="btn btn-outline-secondary" type="button" onclick="copiarValor('wh_cli')" title="Copiar"><i class="fas fa-copy"></i></button>
                                </div>
                                <small class="text-white-50 mt-2 d-block"><i class="fas fa-info-circle me-1"></i> Configure no seu Mercado Pago/Asaas para aprovar as faturas dos clientes finais.</small>
                            </div>
                        </div>
                    </div>

                    <hr class="border-secondary my-4">
                    <h5 class="fw-bold mb-3" style="color: var(--text-color);"><i class="fas fa-university text-success me-2"></i> Depósito / PIX Manual (Fallback)</h5>
                    <div class="mb-4">
                        <label class="label-visivel">Seus Dados Bancários</label>
                        <textarea name="dados_bancarios" class="form-control" rows="4" placeholder="Ex: Chave Pix (Celular): 11999998888. Mostrado caso o sistema automático falhe."><?= htmlspecialchars($banco_atual) ?></textarea>
                    </div>
                    
                    <div class="text-end">
                        <button type="submit" class="btn btn-primary fw-bold px-5 py-2 shadow-sm rounded-pill"><i class="fas fa-save me-2"></i> SALVAR CONFIGURAÇÕES GERAIS</button>
                    </div>
                </form>
            </div>

            <!-- ABA: PLANOS -->
            <div class="tab-pane fade <?= $tab_ativa == 'planos' ? 'show active' : '' ?>" id="planos">
                <div class="row g-4">
                    <!-- Form Criar/Editar -->
                    <div class="col-lg-4">
                        <div class="card card-custom p-4 shadow-sm border-0">
                            <h5 class="mb-4 fw-bold" style="color: var(--text-color);"><i class="fas <?= $plano_editar ? 'fa-pen text-warning' : 'fa-plus-circle text-success' ?> me-2"></i><?= $plano_editar ? 'Editar Plano Existente' : 'Criar Novo Plano' ?></h5>
                            <form method="POST">
                                <?php if($plano_editar): ?>
                                    <input type="hidden" name="id_plano" value="<?= $plano_editar['id'] ?>">
                                    <input type="hidden" name="atualizar_plano" value="1">
                                <?php else: ?>
                                    <input type="hidden" name="criar_plano" value="1">
                                <?php endif; ?>
                                
                                <div class="mb-3">
                                    <label class="label-visivel">NOME DO PLANO</label>
                                    <input type="text" name="nome" class="form-control" value="<?= $plano_editar['nome_plano'] ?? '' ?>" placeholder="Ex: Plano Trimestral" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="label-visivel">LOGO / MARCA</label>
                                    <div class="d-flex flex-wrap gap-2">
                                        <?php foreach($logos_disponiveis as $img => $nome_img): 
                                            $checked = ($plano_editar && $plano_editar['logo_perfil'] == $img) ? 'checked' : '';
                                            if(!$plano_editar && $img == 'iptv.png') $checked = 'checked';
                                        ?>
                                        <label class="logo-option" title="<?= $nome_img ?>">
                                            <input type="radio" name="logo_perfil" value="<?= $img ?>" <?= $checked ?>>
                                            <img src="img/<?= $img ?>" alt="<?= $nome_img ?>" onerror="this.style.opacity='0.5'">
                                        </label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                
                                <div class="row g-2 mb-4">
                                    <div class="col-6">
                                        <label class="label-visivel">DIAS</label>
                                        <input type="number" name="dias" class="form-control text-center" value="<?= $plano_editar['dias'] ?? '' ?>" placeholder="Ex: 30" required>
                                    </div>
                                    <div class="col-6">
                                        <label class="label-visivel">VALOR (R$)</label>
                                        <input type="text" name="valor" class="form-control text-center text-success fw-bold" value="<?= $plano_editar['valor'] ?? '' ?>" placeholder="Ex: 35.00" required>
                                    </div>
                                </div>
                                
                                <button type="submit" class="btn btn-<?= $plano_editar ? 'warning text-dark' : 'success' ?> w-100 fw-bold py-2 shadow-sm rounded-pill">
                                    <i class="fas fa-check me-1"></i> <?= $plano_editar ? 'SALVAR ALTERAÇÕES' : 'CADASTRAR PLANO' ?>
                                </button>
                                <?php if($plano_editar): ?>
                                    <a href="config_mp_revenda.php?tab=planos" class="btn btn-outline-secondary w-100 fw-bold py-2 mt-2 rounded-pill">CANCELAR EDIÇÃO</a>
                                <?php endif; ?>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Lista de Planos -->
                    <div class="col-lg-8">
                        <div class="card card-custom shadow-sm overflow-hidden border-0 h-100">
                            <div class="p-4 border-bottom border-secondary bg-transparent">
                                <h5 class="mb-0 fw-bold" style="color: var(--text-color);"><i class="fas fa-list text-info me-2"></i> Seus Planos Ativos</h5>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-dark table-hover align-middle m-0">
                                    <thead><tr><th>Logotipo</th><th>Nome do Plano</th><th class="text-center">Duração</th><th class="text-center">Preço</th><th class="text-end pe-4">Ações</th></tr></thead>
                                    <tbody>
                                        <?php if(empty($meus_planos)): ?>
                                            <tr><td colspan="5" class="text-center py-5 text-white-50">Você ainda não cadastrou nenhum plano de venda.</td></tr>
                                        <?php else: foreach($meus_planos as $p): ?>
                                        <tr>
                                            <td style="width:1%;"><div class="bg-dark border border-secondary rounded p-2 d-inline-flex align-items-center justify-content-center shadow-sm" style="width:40px;height:40px;"><img src="img/<?= $p['logo_perfil'] ?>" class="logo-preview-table"></div></td>
                                            <td><div class="fw-bold" style="color: var(--text-color);"><?= htmlspecialchars($p['nome_plano']) ?></div></td>
                                            <td class="text-center"><span class="badge bg-secondary p-2"><?= $p['dias'] ?> dias</span></td>
                                            <td class="text-center"><span class="text-success fw-bold fs-6">R$ <?= number_format($p['valor'], 2, ',', '.') ?></span></td>
                                            <td class="text-end pe-4">
                                                <a href="?edit=<?= $p['id'] ?>&tab=planos" class="btn btn-outline-warning btn-sm me-2 shadow-sm rounded-3" title="Editar"><i class="fas fa-pen"></i></a>
                                                <a href="?del=<?= $p['id'] ?>&tab=planos" class="btn btn-outline-danger btn-sm shadow-sm rounded-3" title="Excluir" onclick="return confirm('Tem certeza que deseja apagar este plano?')"><i class="fas fa-trash"></i></a>
                                            </td>
                                        </tr>
                                        <?php endforeach; endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ABA: VENDAS -->
            <div class="tab-pane fade <?= $tab_ativa == 'vendas' ? 'show active' : '' ?>" id="vendas">
                <div class="card card-custom p-0 shadow-sm border-0">
                    <div class="p-4 border-bottom border-secondary bg-transparent">
                        <h5 class="mb-0 fw-bold" style="color: var(--text-color);"><i class="fas fa-history text-success me-2"></i> Últimos Pagamentos Aprovados (API)</h5>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-dark table-hover align-middle m-0">
                            <thead><tr><th class="ps-4">Data da Aprovação</th><th>Usuário Renovado</th><th>Valor Recebido</th><th class="text-center pe-4">Status</th></tr></thead>
                            <tbody>
                                <?php if(empty($vendas)): ?>
                                    <tr><td colspan="4" class="text-center py-5 text-white-50">Nenhuma venda registrada nos sistemas automáticos ainda.</td></tr>
                                <?php else: foreach($vendas as $v): ?>
                                <tr>
                                    <td class="ps-4 text-white-50"><i class="fas fa-calendar-check me-2"></i><?= date('d/m/Y H:i', strtotime($v['data_pagamento'])) ?></td>
                                    <td class="fw-bold text-info"><i class="fas fa-user me-2 opacity-50"></i><?= htmlspecialchars($v['usuario_id']) ?></td>
                                    <td class="text-success fw-bold">R$ <?= number_format($v['valor'], 2, ',', '.') ?></td>
                                    <td class="text-center pe-4"><span class="badge bg-success bg-opacity-10 text-success border border-success p-2"><i class="fas fa-check-circle me-1"></i> Aprovado</span></td>
                                </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php include 'rodape.php'; ?>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu(){ document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }
    
    function copiarValor(id) {
        var input = document.getElementById(id);
        input.select();
        input.setSelectionRange(0, 99999);
        navigator.clipboard.writeText(input.value).then(() => {
            alert("Copiado com sucesso!");
        });
    }
</script>
</body>
</html>