<?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!"; $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!"; $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!"; $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; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; padding: 0; }
        
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid #333; z-index: 1050; padding: 20px; overflow-y: auto; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .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; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--primary) 100%); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; }

        .card-custom { background: var(--bg-card) !important; border: 1px solid var(--border-color); border-radius: 12px; }
        .form-control { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; }
        .form-control:focus { border-color: var(--primary); box-shadow: none; }
        
        .nav-tabs .nav-link { color: #a6a6b7; background: #252535; margin-right: 5px; border-radius: 8px 8px 0 0; border: none; }
        .nav-tabs .nav-link.active { background: var(--primary); color: #fff; }
        
        /* Visibilidade das Labels - Corrigindo o cinza */
        .label-visivel { color: #ffffff !important; font-weight: 700 !important; text-transform: uppercase; font-size: 0.75rem; display: block; margin-bottom: 8px; }
        
        .logo-option { cursor: pointer; border: 2px solid #444; border-radius: 8px; padding: 5px; background: #252535; width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; position: relative; overflow: hidden; }
        .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; }
        .logo-option:has(input:checked) { border-color: var(--primary); background: rgba(115, 103, 240, 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; } }
        .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.5); z-index: 1040; }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>


<main class="main-content">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title">Configuração Financeira</div>
        </div>
        <div class="small text-white-50">Logado: <?= htmlspecialchars($usuarioLogado) ?></div>
    </div>

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

        <ul class="nav nav-tabs border-0 mb-4 px-2" id="finTabs">
            <li class="nav-item flex-grow-1 text-center"><button class="nav-link <?= $tab_ativa == 'config' ? 'active' : '' ?> w-100 py-3 fw-bold" data-bs-toggle="tab" data-bs-target="#config"><i class="fas fa-cog me-2"></i> Configuração</button></li>
            <li class="nav-item flex-grow-1 text-center"><button class="nav-link <?= $tab_ativa == 'planos' ? 'active' : '' ?> w-100 py-3 fw-bold" data-bs-toggle="tab" data-bs-target="#planos"><i class="fas fa-tags me-2"></i> Planos de Venda</button></li>
            <li class="nav-item flex-grow-1 text-center"><button class="nav-link <?= $tab_ativa == 'vendas' ? 'active' : '' ?> w-100 py-3 fw-bold" data-bs-toggle="tab" data-bs-target="#vendas"><i class="fas fa-shopping-cart me-2"></i> Histórico Vendas</button></li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane fade <?= $tab_ativa == 'config' ? 'show active' : '' ?>" id="config">
                <form method="POST" class="card card-custom p-4 shadow-lg mx-2">
                    <input type="hidden" name="salvar_config" value="1">
                    <h5 class="text-white mb-4 fw-bold border-bottom border-secondary pb-2"><i class="fas fa-bolt text-warning me-2"></i> Gateways Automáticos</h5>
                    
                    <div class="row">
                        <div class="col-md-6 mb-4 border-end border-secondary">
                            <label class="label-visivel text-info mb-2"><i class="fas fa-handshake me-1"></i> MERCADO PAGO (ACCESS TOKEN)</label>
                            <input type="text" name="token_mp" class="form-control p-3 mb-2" value="<?= htmlspecialchars($token_atual) ?>" placeholder="APP_USR-...">
                            <small class="text-white-50" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Token de Produção para gerar PIX Automático.</small>
                        </div>
                        
                        <div class="col-md-6 mb-4">
                            <label class="label-visivel text-primary mb-2"><i class="fas fa-money-check-alt me-1"></i> ASAAS (API KEY)</label>
                            <input type="text" name="token_asaas" class="form-control p-3 mb-2" value="<?= htmlspecialchars($token_asaas_atual) ?>" placeholder="$aact_...">
                            <small class="text-white-50" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Chave de API do Asaas para gerar PIX Automático.</small>
                        </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="text-white mb-4 fw-bold border-bottom border-secondary pb-2"><i class="fas fa-link text-info me-2"></i> URLs de Webhook para Integração</h5>
                    <div class="row">
                        <?php if ($isAdmin): ?>
                        <div class="col-md-6 mb-4 border-end border-secondary">
                            <label class="label-visivel text-warning mb-2"><i class="fas fa-user-tie me-1"></i> Webhook Revendedores (Apenas Admin)</label>
                            <input type="text" class="form-control p-3 mb-2 text-white-50 bg-dark" value="<?= $url_wh_base ?>/webhook.php" readonly onclick="this.select(); document.execCommand('copy'); alert('URL do Webhook de Revendedores copiada!');" style="cursor: pointer;">
                            <small class="text-white-50" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Copie e cole no Mercado Pago/Asaas para aprovar os pagamentos das revendas. (Clique no campo para copiar)</small>
                        </div>
                        <?php endif; ?>
                        
                        <div class="col-md-6 mb-4">
                            <label class="label-visivel text-success mb-2"><i class="fas fa-users me-1"></i> Webhook Clientes Finais</label>
                            <input type="text" class="form-control p-3 mb-2 text-white-50 bg-dark" value="<?= $url_wh_base ?>/webhook_cliente.php" readonly onclick="this.select(); document.execCommand('copy'); alert('URL do Webhook de Clientes Finais copiada!');" style="cursor: pointer;">
                            <small class="text-white-50" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Copie e cole no Mercado Pago/Asaas para aprovar os pagamentos dos clientes finais. (Clique no campo para copiar)</small>
                        </div>
                    </div>

                    <hr class="border-secondary my-4">
                    <h5 class="text-white mb-4 fw-bold border-bottom border-secondary pb-2"><i class="fas fa-university text-success me-2"></i> Depósito / PIX Manual</h5>
                    <div class="mb-4">
                        <label class="label-visivel">DADOS BANCÁRIOS</label>
                        <textarea name="dados_bancarios" class="form-control" rows="5" placeholder="Ex: Chave Pix (Celular): 11999998888"><?= htmlspecialchars($banco_atual) ?></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary btn-lg fw-bold w-100 p-3 shadow-sm"><i class="fas fa-save me-2"></i> SALVAR CONFIGURAÇÕES GERAIS</button>
                </form>
            </div>

            <div class="tab-pane fade <?= $tab_ativa == 'planos' ? 'show active' : '' ?>" id="planos">
                <div class="row g-3 mx-1">
                    <div class="col-md-5">
                        <div class="card card-custom p-4 shadow-lg">
                            <h5 class="mb-3 text-white fw-bold border-bottom border-secondary pb-2"><?= $plano_editar ? 'Editar Plano' : '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'] ?? '' ?>" 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"><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">
                                    <div class="col-6 mb-3"><label class="label-visivel">DIAS</label><input type="number" name="dias" class="form-control" value="<?= $plano_editar['dias'] ?? '' ?>" required></div>
                                    <div class="col-6 mb-3"><label class="label-visivel">VALOR (R$)</label><input type="text" name="valor" class="form-control" value="<?= $plano_editar['valor'] ?? '' ?>" required></div>
                                </div>
                                <button type="submit" class="btn btn-primary w-100 fw-bold py-3 shadow-sm"><?= $plano_editar ? 'SALVAR' : 'CRIAR' ?></button>
                            </form>
                        </div>
                    </div>
                    <div class="col-md-7">
                        <div class="card card-custom shadow-lg overflow-hidden">
                            <div class="p-3 border-bottom border-secondary"><h5 class="mb-0 text-white fw-bold">Planos Ativos</h5></div>
                            <div class="table-responsive">
                                <table class="table table-dark table-hover align-middle m-0" style="background:transparent; --bs-table-bg: transparent;">
                                    <thead><tr class="text-white-50 small"><th>LOGO</th><th>PLANO</th><th>VALOR</th><th class="text-end">AÇÕES</th></tr></thead>
                                    <tbody>
                                        <?php foreach($meus_planos as $p): ?>
                                        <tr>
                                            <td><div class="bg-light rounded p-1 d-inline-block shadow-sm"><img src="img/<?= $p['logo_perfil'] ?>" class="logo-preview-table"></div></td>
                                            <td><div class="fw-bold text-white"><?= htmlspecialchars($p['nome_plano']) ?></div><small class="text-info"><?= $p['dias'] ?> dias</small></td>
                                            <td><span class="text-success fw-bold">R$ <?= number_format($p['valor'], 2, ',', '.') ?></span></td>
                                            <td class="text-end"><a href="?edit=<?= $p['id'] ?>&tab=planos" class="btn btn-warning btn-sm me-1"><i class="fas fa-pen text-dark"></i></a><a href="?del=<?= $p['id'] ?>&tab=planos" class="btn btn-danger btn-sm" onclick="return confirm('Excluir plano?')"><i class="fas fa-trash"></i></a></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade <?= $tab_ativa == 'vendas' ? 'show active' : '' ?>" id="vendas">
                <div class="card card-custom p-4 shadow-lg mx-2">
                    <h5 class="mb-4 text-white fw-bold"><i class="fas fa-history text-success me-2"></i> Últimas Vendas Aprovadas</h5>
                    <div class="table-responsive">
                        <table class="table table-dark table-hover align-middle m-0" style="background:transparent; --bs-table-bg: transparent;">
                            <thead><tr class="text-white-50 small"><th>Data</th><th>Usuário Renovado</th><th>Valor</th><th>Status</th></tr></thead>
                            <tbody>
                                <?php foreach($vendas as $v): ?>
                                <tr><td class="text-white-50"><?= date('d/m/Y H:i', strtotime($v['data_pagamento'])) ?></td><td class="fw-bold text-info"><?= htmlspecialchars($v['usuario_id']) ?></td><td class="text-success fw-bold">R$ <?= number_format($v['valor'], 2, ',', '.') ?></td><td><span class="badge bg-success">Aprovado</span></td></tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</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'); }
</script>
</body>
</html>
