<?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 ---
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) {}

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

$msg = ""; $msg_tipo = "";
$tab_ativa = 'config'; // Aba padrão

// --- 1. SALVAR CONFIGURAÇÕES DE PAGAMENTO ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['salvar_config'])) {
    $token = trim($_POST['token_mp']);
    $banco = trim($_POST['dados_bancarios']);
    
    $sql = "INSERT INTO mp_revendedores (usuario_revendedor, access_token, dados_bancarios) VALUES (?, ?, ?) 
            ON DUPLICATE KEY UPDATE access_token = VALUES(access_token), dados_bancarios = VALUES(dados_bancarios)";
    try {
        $connUser->prepare($sql)->execute([$usuarioLogado, $token, $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!"; $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_financeira.php?tab=planos"); exit;
}

// --- CARREGAR EDIÇÃO DE PLANO ---
$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']; }

// ==========================================
// BUSCAS NO BANCO PARA EXIBIR NA TELA
// ==========================================

// A) Busca Configuração do Asaas/Banco
$token_atual = ""; $banco_atual = "";
try {
    $stmt = $connUser->prepare("SELECT access_token, dados_bancarios FROM mp_revendedores WHERE usuario_revendedor = ?");
    $stmt->execute([$usuarioLogado]);
    $dados = $stmt->fetch(PDO::FETCH_ASSOC);
    if($dados) { $token_atual = $dados['access_token']; $banco_atual = $dados['dados_bancarios']; }
} catch (Exception $e) {}

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

// C) Busca Histórico de Vendas/Pagamentos
$vendas = [];
try {
    // Puxa pagamentos aprovados vinculados aos clientes deste revendedor
    $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) {}

$nomePainel = "IPTV PANEL"; 
try { $conf = $connGeral->query("SELECT NomePainel FROM site_config LIMIT 1")->fetch(); if($conf) $nomePainel = $conf['NomePainel']; } 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">
    <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: #7367f0; --bg-body: #151521; --bg-card: #1e1e2d; --text-color: #ffffff; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden;}
        
        .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; font-weight: 500; display:flex; align-items:center; gap:10px; margin-bottom:5px; text-decoration:none; 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; padding: 30px; transition: 0.3s; }
        .card-custom { background: var(--bg-card); border: 1px solid #2b2b40; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.2); }
        .form-control { background: #2b2b40; border: 1px solid #555; color: #fff; }
        .form-control:focus { background: #2b2b40; color: #fff; border-color: var(--primary); box-shadow: 0 0 0 0.2rem rgba(115, 103, 240, 0.25); }
        
        /* ABAS */
        .nav-tabs .nav-link { color: #a6a6b7; background: #252535; border: 1px solid #333; margin-right: 5px; border-radius: 8px 8px 0 0; }
        .nav-tabs .nav-link.active { background: var(--primary); color: #fff; border-color: var(--primary); }

        /* LOGOS */
        .logo-selector { display: flex; gap: 10px; flex-wrap: wrap; }
        .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; transition: 0.2s; position: relative; }
        .logo-option img { max-width: 100%; max-height: 100%; object-fit: contain; }
        .logo-option:hover { border-color: var(--primary); }
        .logo-option input { position: absolute; opacity: 0; cursor: pointer; inset: 0; }
        .logo-option:has(input:checked) { border-color: var(--primary); background: rgba(115, 103, 240, 0.2); box-shadow: 0 0 10px var(--primary); }
        .logo-preview-table { width: 40px; height: 40px; object-fit: contain; background: #fff; border-radius: 5px; padding: 2px; }
        
        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; padding: 15px;} .mobile-toggle { display: block; } }
        .mobile-toggle { display: none; color: #fff; font-size: 1.5rem; background: none; border: none; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; } .overlay.show { display: block; }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<nav class="sidebar" id="sidebar">
    <div class="nav flex-column mt-4">
        <a href="index.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        <?php if ($isAdmin): ?>
            <div class="nav-group-title">ADMINISTRATIVO</div>
            <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Perfis</a>
            <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores</a>
            <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Admins</a>
            <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
            <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> SMTP Email</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Configurações</a>
        <?php endif; ?>
        
        <div class="nav-group-title">MENU</div>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        <a href="clientes.php" class="nav-link"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link"><i class="fas fa-stopwatch"></i> Testes</a>
        
        <a href="config_financeira.php" class="nav-link active"><i class="fas fa-wallet"></i> Financeiro & Planos</a>
        
        <a href="sair.php" class="nav-link text-danger mt-4"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>

    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
        <h3 class="fw-bold m-0"><i class="fas fa-wallet text-primary me-2"></i> Central Financeira</h3>
    </div>

    <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show fw-bold"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

    <ul class="nav nav-tabs border-0 mb-4" 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> Chaves / Pix
            </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> Meus Planos
            </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">
            <div class="row">
                <div class="col-lg-8 mb-4">
                    <form method="POST" class="card card-custom p-4">
                        <input type="hidden" name="salvar_config" value="1">
                        
                        <h5 class="text-white mb-3 fw-bold"><i class="fas fa-bolt text-warning me-2"></i> Integração Asaas / MP</h5>
                        <div class="mb-4">
                            <label class="form-label">Access Token (Produção)</label>
                            <input type="text" name="token_mp" class="form-control p-3" placeholder="Cole seu Token Asaas aqui ($aact_...)" value="<?= htmlspecialchars($token_atual) ?>">
                            <div class="mt-2 text-info small fw-bold">O sistema fará a cobrança e a renovação automática para o cliente usando este token.</div>
                        </div>

                        <hr class="border-secondary my-4">

                        <h5 class="text-white mb-3 fw-bold"><i class="fas fa-university text-success me-2"></i> Pagamento Manual (Depósito/Pix)</h5>
                        <div class="mb-4">
                            <label class="form-label">Seus Dados Bancários</label>
                            <textarea name="dados_bancarios" class="form-control" rows="5" placeholder="Exemplo:&#10;Chave Pix: (11) 99999-9999&#10;Nome: Seu Nome"><?= htmlspecialchars($banco_atual) ?></textarea>
                            <div class="mt-2 text-white-50 small">O cliente enviará o PIX para esta chave e mandará o comprovante no seu WhatsApp.</div>
                        </div>

                        <button type="submit" class="btn btn-primary btn-lg fw-bold w-100 p-3"><i class="fas fa-save me-2"></i> SALVAR CONFIGURAÇÕES</button>
                    </form>
                </div>
            </div>
        </div>

        <div class="tab-pane fade <?= $tab_ativa == 'planos' ? 'show active' : '' ?>" id="planos">
            <div class="row">
                <div class="col-md-5 mb-4">
                    <div class="card card-custom p-4">
                        <h5 class="mb-3 text-white fw-bold border-bottom border-secondary pb-2">
                            <?= $plano_editar ? '<i class="fas fa-edit text-warning"></i> Editar Plano' : '<i class="fas fa-plus text-success"></i> 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="form-label text-white small fw-bold">NOME DO PLANO</label>
                                <input type="text" name="nome" class="form-control" placeholder="Ex: Trimestral" value="<?= $plano_editar['nome_plano'] ?? '' ?>" required>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label text-white small fw-bold">LOGO / MARCA</label>
                                <div class="logo-selector">
                                    <?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.src='https://via.placeholder.com/50?text=Icon'">
                                    </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-6 mb-3">
                                    <label class="form-label text-white small fw-bold">DIAS (Tempo)</label>
                                    <input type="number" name="dias" class="form-control" placeholder="30" value="<?= $plano_editar['dias'] ?? '' ?>" required>
                                </div>
                                <div class="col-6 mb-3">
                                    <label class="form-label text-white small fw-bold">VALOR (R$)</label>
                                    <input type="text" name="valor" class="form-control" placeholder="25.00" value="<?= $plano_editar['valor'] ?? '' ?>" required>
                                </div>
                            </div>

                            <?php if($plano_editar): ?>
                                <button type="submit" class="btn btn-warning w-100 fw-bold py-3 mt-2 text-dark"><i class="fas fa-save me-2"></i> SALVAR</button>
                                <a href="config_financeira.php?tab=planos" class="btn btn-outline-secondary w-100 mt-2">Cancelar Edição</a>
                            <?php else: ?>
                                <button type="submit" class="btn btn-primary w-100 fw-bold py-3 mt-2"><i class="fas fa-plus-circle me-2"></i> CRIAR PLANO</button>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>

                <div class="col-md-7">
                    <div class="card card-custom p-4">
                        <h5 class="mb-3 text-white fw-bold border-bottom border-secondary pb-2">Planos Ativos no Painel</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>MARCA</th>
                                        <th>NOME</th>
                                        <th>VALOR</th>
                                        <th class="text-end">AÇÕES</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(count($meus_planos) > 0): ?>
                                        <?php foreach($meus_planos as $p): ?>
                                        <tr>
                                            <td>
                                                <div class="bg-light rounded p-1 d-inline-block">
                                                    <img src="img/<?= $p['logo_perfil'] ?>" class="logo-preview-table" onerror="this.style.opacity='0.5'">
                                                </div>
                                            </td>
                                            <td>
                                                <div class="fw-bold text-white mb-1"><?= htmlspecialchars($p['nome_plano']) ?></div>
                                                <div class="badge bg-secondary"><?= $p['dias'] ?> dias</div>
                                            </td>
                                            <td><span class="text-success fw-bold fs-5">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 este plano?')"><i class="fas fa-trash"></i></a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr><td colspan="4" class="text-center py-5 text-muted">Nenhum plano criado. Seus clientes só verão o plano padrão (30 Dias).</td></tr>
                                    <?php endif; ?>
                                </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">
                <h5 class="mb-4 text-white fw-bold"><i class="fas fa-money-check-alt text-success me-2"></i> Pagamentos Aprovados Recentemente</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 text-uppercase">
                                <th>Data/Hora</th>
                                <th>Usuário Renovado</th>
                                <th>Valor Recebido</th>
                                <th>Status do Sistema</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($vendas) > 0): ?>
                                <?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"><i class="fas fa-user-circle me-2"></i><?= htmlspecialchars($v['usuario_id']) ?></td>
                                    <td class="text-success fw-bold fs-6">R$ <?= number_format($v['valor'], 2, ',', '.') ?></td>
                                    <td><span class="badge bg-success py-2 px-3"><i class="fas fa-check-circle me-1"></i> Aprovado</span></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="4" class="text-center py-5 text-muted"><i class="fas fa-sad-tear fa-2x mb-2"></i><br>Nenhuma venda registrada ainda no automático.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </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>
