<?php
// ==========================================================
// ARQUIVO: donate.php
// TEMA: Cyber Dark + Busca Email Automático
// ==========================================================

ini_set('display_errors', 0); // Ocultar erros PHP na tela para não quebrar layout
error_reporting(E_ALL);

session_start();

// --- 1. CARREGAMENTO E CONEXÃO ---
if (file_exists('vendor/autoload.php')) { require 'vendor/autoload.php'; } 
elseif (file_exists('../vendor/autoload.php')) { require '../vendor/autoload.php'; }

if (file_exists('includes/conexao.php')) require 'includes/conexao.php';
elseif (file_exists('../includes/conexao.php')) require '../includes/conexao.php';

// Redireciona se não estiver logado
if (!isset($_SESSION['account_id']) && !isset($_SESSION['id'])) { 
    header("Location: login.php?redirect=donate.php"); 
    exit; 
}

// Normaliza ID da Sessão
$account_id = $_SESSION['account_id'] ?? $_SESSION['id'];

// --- 2. BUSCA DADOS DO USUÁRIO (NOVIDADE) ---
$user_email = "";
try {
    $stmtUser = $pdo->prepare("SELECT email FROM accounts WHERE id = ?");
    $stmtUser->execute([$account_id]);
    $uData = $stmtUser->fetch(PDO::FETCH_ASSOC);
    if ($uData) {
        $user_email = $uData['email'];
    }
} catch (Exception $e) {
    // Se der erro, segue com email vazio
}

// Se o email veio vazio do banco, tenta pegar da sessão
if(empty($user_email)) {
    $user_email = $_SESSION['email'] ?? '';
}

// --- 3. CONFIGURAÇÕES MP ---
$points_per_real = 1.0; 
$bonus_min = 50.0;
$bonus_pct = 0;

try {
    $stmt = $pdo->query("SELECT * FROM mp_config WHERE id = 1");
    $conf = $stmt->fetch(PDO::FETCH_ASSOC);
    if($conf) {
        $points_per_real = (float)$conf['points_per_real'];
        $bonus_min = (float)($conf['bonus_min_amount'] ?? 50);
        $bonus_pct = (int)($conf['bonus_percentage'] ?? 0);
    }
} catch(Exception $e) {}

// Busca Ofertas
try {
    $offers = $pdo->query("SELECT * FROM mp_offers ORDER BY amount ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $offers = []; }

$DEFAULT_AMOUNT = 20.00;

include 'includes/header.php';
?>

<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    /* --- DESIGN CYBER DARK --- */
    :root {
        --bg-deep: #020617;
        --bg-card: #0f172a;
        --primary: #3b82f6;
        --accent: #facc15;
        --success: #10b981;
        --text-bright: #ffffff;
        --text-soft: rgba(255, 255, 255, 0.7);
        --border-light: rgba(255, 255, 255, 0.1);
    }
    
    body { 
        background-color: var(--bg-deep); 
        color: var(--text-bright); 
        font-family: 'Segoe UI', sans-serif; 
    }
    
    .donate-hero { 
        background: radial-gradient(circle at center, #1e1b4b 0%, #020617 100%); 
        padding: 60px 0 40px 0; 
        text-align: center; 
        border-bottom: 1px solid var(--border-light); 
        margin-bottom: 40px;
    }
    
    .hero-title { 
        font-family: 'Segoe UI', sans-serif; 
        font-size: 3rem; 
        font-weight: 800; 
        text-transform: uppercase; 
        background: linear-gradient(to right, #fff, #60a5fa);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: 10px;
    }

    .donate-card { 
        background: var(--bg-card); 
        border: 1px solid var(--border-light); 
        border-radius: 12px; 
        transition: all 0.3s ease; 
        position: relative; 
        overflow: hidden; 
    }
    
    .offer-card { cursor: pointer; text-align: center; padding: 25px; height: 100%; }
    .offer-card:hover { transform: translateY(-5px); border-color: var(--primary); background: #1e293b; }
    .offer-card.selected { 
        border: 2px solid var(--primary); 
        background: rgba(59, 130, 246, 0.1); 
    }

    /* Inputs */
    .form-control, .form-select, .input-group-text { 
        background-color: #1e293b !important; 
        border: 1px solid var(--border-light) !important; 
        color: white !important; 
    }
    .form-control:focus { border-color: var(--primary) !important; box-shadow: 0 0 10px rgba(59, 130, 246, 0.3); }
    
    /* Checkout Sidebar */
    .checkout-area { 
        background: rgba(15, 23, 42, 0.95); 
        border: 1px solid var(--border-light); 
        border-radius: 12px; 
        box-shadow: 0 10px 40px rgba(0,0,0,0.5); 
        position: sticky; top: 20px;
    }
    
    .nav-pills .nav-link { 
        background: rgba(255,255,255,0.05); 
        color: var(--text-soft); 
        border: 1px solid var(--border-light); 
        margin-right: 5px; 
    }
    .nav-pills .nav-link.active { 
        background: var(--primary); 
        color: white; 
    }

    .btn-pay { 
        background: linear-gradient(45deg, #10b981, #059669); 
        border: none; color: white; 
        font-weight: 800; 
        text-transform: uppercase; 
        padding: 15px; 
        width: 100%; 
        border-radius: 8px;
        transition: 0.3s; 
    }
    .btn-pay:hover { filter: brightness(1.1); transform: translateY(-2px); }
</style>

<div class="donate-hero">
    <div class="container" data-aos="fade-down">
        <h1 class="hero-title">Adquirir Pontos</h1>
        <p class="text-soft">Selecione um pacote e receba automaticamente.</p>
    </div>
</div>

<div class="container my-5">
    <div class="row g-4">
        
        <div class="col-lg-7" data-aos="fade-right">
            
            <div class="donate-card p-4 mb-4 selectable-card selected" id="card-custom" 
                 data-amount="<?php echo $DEFAULT_AMOUNT; ?>" data-points="0" onclick="selectCustom()">
                
                <div class="d-flex align-items-center mb-3">
                    <div class="bg-primary rounded-circle d-flex justify-content-center align-items-center me-3" style="width: 50px; height: 50px;">
                        <i class="fas fa-calculator text-white fs-4"></i>
                    </div>
                    <div>
                        <h4 class="fw-bold text-white m-0">Valor Livre</h4>
                        <small class="text-soft">Digite quanto quer doar</small>
                    </div>
                </div>

                <div class="row align-items-center">
                    <div class="col-md-6 mb-3 mb-md-0">
                        <label class="small fw-bold text-soft mb-1">VALOR (R$)</label>
                        <div class="input-group input-group-lg">
                            <span class="input-group-text bg-dark border-secondary text-success fw-bold">R$</span>
                            <input type="number" step="1.00" min="1.00" id="customAmount" class="form-control fw-bold fs-4 text-white" 
                                   value="<?php echo $DEFAULT_AMOUNT; ?>" oninput="updateCalculation()">
                        </div>
                    </div>
                    <div class="col-md-6 text-center text-md-start ps-md-4">
                        <small class="d-block text-soft fw-bold mb-1">VOCÊ RECEBE:</small>
                        <div class="display-5 lh-1 text-warning fw-bold">
                            <span id="customPointsCalc">0</span> <span class="fs-6 text-white opacity-50">Pts</span>
                        </div>
                    </div>
                </div>
                <div id="bonusAlert" class="mt-3 text-center"></div>
            </div>

            <?php if(!empty($offers)): ?>
            <h5 class="fw-bold text-white mb-3 ps-3 border-start border-4 border-warning">PACOTES</h5>
            <div class="row g-3">
                <?php foreach($offers as $offer): ?>
                <div class="col-md-6">
                    <div class="donate-card offer-card selectable-card" 
                         onclick="selectPackage(this, <?php echo $offer['amount']; ?>, <?php echo $offer['points']; ?>)">
                        <h3 class="fw-bold text-white mt-2">R$ <?php echo number_format($offer['amount'], 2, ',', '.'); ?></h3>
                        <div class="bg-dark bg-opacity-50 p-2 rounded border border-white border-opacity-10 mt-3">
                            <div class="text-warning fw-bold fs-2"><?php echo number_format($offer['points'], 0, ',', '.'); ?></div>
                            <small class="text-white fw-bold opacity-75">PONTOS</small>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <div class="col-lg-5" data-aos="fade-left">
            <div class="checkout-area">
                <div class="p-4">
                    <h5 class="m-0 fw-bold text-white mb-3"><i class="fas fa-shopping-cart text-primary me-2"></i> RESUMO</h5>
                    
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-soft">Valor:</span>
                        <span class="fs-4 fw-bold text-success" id="checkout-total">R$ 0,00</span>
                    </div>
                    <div class="d-flex justify-content-between mb-4 pb-3 border-bottom border-light">
                        <span class="text-soft">Pontos:</span>
                        <span class="fs-4 text-warning fw-bold" id="checkout-points">0</span>
                    </div>

                    <form id="paymentForm">
                        <input type="hidden" id="finalAccountId" value="<?php echo $account_id; ?>">
                        
                        <div class="mb-3">
                            <label class="small text-soft fw-bold mb-1">SEU E-MAIL (Pode alterar se quiser)</label>
                            <input type="email" id="email" class="form-control" 
                                   value="<?php echo htmlspecialchars($user_email); ?>" required>
                        </div>

                        <ul class="nav nav-pills nav-fill mb-3" id="paymentTabs">
                            <li class="nav-item">
                                <button class="nav-link active" id="pix-tab" data-bs-toggle="pill" data-bs-target="#pix-area" type="button" onclick="setMethod('pix')">
                                    <i class="fas fa-qrcode me-2"></i> PIX
                                </button>
                            </li>
                            <li class="nav-item">
                                <button class="nav-link" id="card-tab" data-bs-toggle="pill" data-bs-target="#card-area" type="button" onclick="setMethod('card')">
                                    <i class="fas fa-credit-card me-2"></i> CARTÃO
                                </button>
                            </li>
                        </ul>
                        <input type="hidden" id="selectedMethod" value="pix">

                        <div class="tab-content">
                            <div class="tab-pane fade show active" id="pix-area">
                                <div class="mb-3">
                                    <label class="small text-soft fw-bold">SEU CPF (Obrigatório)</label>
                                    <input type="text" id="docNumber" class="form-control" placeholder="Apenas números" maxlength="14" required>
                                </div>
                                <div class="mb-3">
                                    <label class="small text-soft fw-bold">NOME COMPLETO</label>
                                    <input type="text" id="firstName" class="form-control" placeholder="Titular" required>
                                </div>
                                <button type="button" onclick="processPayment()" class="btn btn-pay w-100 shadow-lg">GERAR PIX</button>
                            </div>

                            <div class="tab-pane fade" id="card-area">
                                <div class="alert alert-primary bg-opacity-10 border-primary text-white small p-3 mb-3 text-center">
                                    <i class="fas fa-shield-alt fs-4 mb-2 d-block text-primary"></i>
                                    Ambiente Seguro Mercado Pago.
                                </div>
                                <button type="button" onclick="processPayment()" class="btn btn-pay w-100 shadow-lg" style="background: #009ee3;">
                                    IR PARA PAGAMENTO <i class="fas fa-external-link-alt ms-2"></i>
                                </button>
                            </div>
                        </div>
                    </form>
                    
                    <div id="pix-result" class="mt-4" style="display:none;">
                        <div class="text-center bg-white p-3 rounded">
                            <h6 class="text-dark fw-bold mb-2">Escaneie o QR Code:</h6>
                            <img id="qrImage" src="" style="width: 200px; height: 200px;">
                            <hr>
                            <textarea id="pixCode" class="form-control mb-2 text-center" style="font-size: 12px; height: 50px;" readonly></textarea>
                            <button class="btn btn-outline-dark btn-sm w-100" onclick="copyPix()">COPIAR CÓDIGO</button>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<script>
    AOS.init();
    const pointsRatio = <?php echo $points_per_real; ?>;
    const bonusMin = <?php echo $bonus_min; ?>;
    const bonusPct = <?php echo $bonus_pct; ?>;
    let currentAmount = <?php echo $DEFAULT_AMOUNT; ?>;
    let currentPoints = 0;

    function updateCalculation() {
        const inputVal = parseFloat(document.getElementById('customAmount').value) || 0;
        let pts = Math.floor(inputVal * pointsRatio);
        let bonus = 0;
        const alertBox = document.getElementById('bonusAlert');
        
        if(inputVal >= bonusMin && bonusPct > 0) {
            bonus = Math.floor(pts * (bonusPct / 100));
            alertBox.innerHTML = `<span class="badge bg-success bg-opacity-25 border border-success p-2 w-100 text-success fw-bold">BÔNUS: +${bonus} PTS</span>`;
        } else {
            alertBox.innerHTML = '';
        }
        pts += bonus;
        document.getElementById('customPointsCalc').innerText = pts;
        updateCheckoutUI(inputVal, pts);
    }

    function selectCustom() {
        document.querySelectorAll('.selectable-card').forEach(c => c.classList.remove('selected'));
        document.getElementById('card-custom').classList.add('selected');
        updateCalculation();
    }

    function selectPackage(el, amount, points) {
        document.querySelectorAll('.selectable-card').forEach(c => c.classList.remove('selected'));
        el.classList.add('selected');
        updateCheckoutUI(amount, points);
    }

    function updateCheckoutUI(amount, points) {
        currentAmount = amount;
        currentPoints = points;
        document.getElementById('checkout-total').innerText = 'R$ ' + amount.toFixed(2).replace('.', ',');
        document.getElementById('checkout-points').innerText = points;
    }

    function setMethod(method) {
        document.getElementById('selectedMethod').value = method;
    }

    function processPayment() {
        const method = document.getElementById('selectedMethod').value;
        const email = document.getElementById('email').value;
        
        if(currentAmount < 1) { Swal.fire('Ops', 'Valor mínimo R$ 1,00', 'warning'); return; }
        if(!email.includes('@')) { Swal.fire('Ops', 'Email inválido', 'error'); return; }

        let payload = {
            amount: currentAmount,
            pointsAmount: currentPoints,
            accountId: document.getElementById('finalAccountId').value,
            email: email,
            paymentMethod: method,
            payerFirstName: 'Visitante',
            documentNumber: ''
        };

        if(method === 'pix') {
            const cpf = document.getElementById('docNumber').value.replace(/\D/g, '');
            const name = document.getElementById('firstName').value;
            if(cpf.length < 11) { Swal.fire('Ops', 'CPF inválido para PIX', 'error'); return; }
            if(name.length < 3) { Swal.fire('Ops', 'Nome obrigatório para PIX', 'error'); return; }
            payload.documentNumber = cpf;
            payload.payerFirstName = name;
        }

        const btn = document.querySelector('.tab-pane.active .btn-pay');
        const oldText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> PROCESSANDO...';

        fetch('process_payment.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(payload)
        })
        .then(r => r.json())
        .then(data => {
            btn.disabled = false;
            btn.innerHTML = oldText;

            if(data.status === 'error') {
                // AGORA O ALERT VAI MOSTRAR O ERRO REAL
                Swal.fire('Erro', data.message, 'error');
                return;
            }

            if(data.action === 'pix') {
                document.getElementById('pix-result').style.display = 'block';
                document.getElementById('qrImage').src = 'data:image/png;base64,' + data.qr_code_base64;
                document.getElementById('pixCode').value = data.qr_code;
                document.getElementById('pix-result').scrollIntoView({behavior: "smooth"});
            }
            else if(data.action === 'redirect') {
                window.location.href = data.url;
            }
        })
        .catch(err => {
            console.error(err);
            btn.disabled = false;
            btn.innerHTML = oldText;
            Swal.fire('Erro', 'Falha na comunicação.', 'error');
        });
    }

    function copyPix() {
        const copyText = document.getElementById("pixCode");
        copyText.select();
        document.execCommand("copy");
        Swal.fire({toast: true, position: 'top-end', icon: 'success', title: 'Copiado!', showConfirmButton: false, timer: 1500});
    }

    updateCalculation();
</script>

<?php include 'includes/footer.php'; ?>