<?php
session_start();
$_SESSION['user'] = '(98) 79978-9097';
// --- LÓGICA AJAX (SEM REFRESH) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'generate_pix') {
    header('Content-Type: application/json');
    
    // Simula as dependências (ajuste os caminhos se necessário)
    require_once '../app/Controllers/sessions.php';
    require_once '../app/Controllers/security_access.php';
    require_once '../app/models/user.php';
    require_once '../app/Controllers/gateway.php'; 
    
    $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
    $cpf = filter_input(INPUT_POST, 'cpf', FILTER_SANITIZE_STRING);
    
    if (!$amount || $amount <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Monto inválido.']);
        exit;
    }

    // Retorno do PIX (Simulado ou Real)
    echo json_encode([
        'status' => 'success',
        'message' => 'QR Code Generado con Éxito',
        'qrcode_text' => $qrCode ?? '00020126580014BR.GOV.BCB.PIX...', 
        'qrcode_img' => $urlQR ?? 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=example',
        'amount' => number_format($amount, 2, ',', '.')
    ]);
    exit;
}

// --- PÁGINA NORMAL ---
require_once '../app/Controllers/sessions.php';
require_once '../app/Controllers/security_access.php';
require_once '../app/models/user.php';
require_once '../app/Controllers/layouts.php';
?>
<!DOCTYPE html>
<html lang="es-AR">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>Depositar - <?= htmlspecialchars($stmtConfigsPlatformResult["name_platform"] ?? 'MorganArg') ?></title>

    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700;800&family=Oswald:wght@500&display=swap" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        vip: {
                            blue: '#0EA5E9',
                            dark: '#0F172A',
                            light: '#F0F9FF',
                            gray: '#94A3B8',
                            red: '#EF4444',
                            green: '#10B981'
                        }
                    },
                    fontFamily: { sans: ['Inter', 'sans-serif'], mono: ['Oswald', 'monospace'] },
                    boxShadow: { 'glow': '0 0 20px rgba(14, 165, 233, 0.3)' }
                }
            }
        };
    </script>

    <style>
        /* --- DESIGN SYSTEM MORGAN ARG V2 --- */
        body {
            background-color: #F8FAFC;
            background-image: radial-gradient(#E2E8F0 1px, transparent 1px);
            background-size: 24px 24px;
            padding-bottom: 90px;
            -webkit-tap-highlight-color: transparent;
        }

        /* Header igual Index */
        .app-header {
            position: sticky; top: 0; z-index: 50;
            background: rgba(255,255,255,0.9); backdrop-filter: blur(10px);
            border-bottom: 1px solid #E2E8F0;
            padding: 15px 20px;
            display: flex; justify-content: space-between; align-items: center;
        }

        /* Wallet Card igual Index */
        .wallet-card {
            margin: 20px;
            background: linear-gradient(135deg, #0EA5E9 0%, #0284C7 100%);
            border-radius: 24px; padding: 24px;
            color: white; position: relative; overflow: hidden;
            box-shadow: 0 15px 40px -10px rgba(14, 165, 233, 0.4);
        }
        .wallet-card::before {
            content: ''; position: absolute; top: -50px; right: -50px;
            width: 150px; height: 150px;
            background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, transparent 60%);
        }

        /* Chips de Valor (Igual Filtros Index) */
        .value-grid {
            display: flex; gap: 8px; overflow-x: auto; padding-bottom: 10px;
            scrollbar-width: none;
        }
        .value-chip {
            padding: 10px 20px;
            background: #FFF;
            border: 1px solid #E2E8F0;
            border-radius: 50px;
            font-size: 13px; font-weight: 700; color: #64748B;
            white-space: nowrap; cursor: pointer; transition: 0.2s;
            font-family: 'Oswald', sans-serif;
        }
        .value-chip.active {
            background: #0EA5E9; color: white; border-color: #0EA5E9;
            box-shadow: 0 4px 10px rgba(14, 165, 233, 0.3);
        }

        /* Inputs (Estilo Login) */
        .input-group { position: relative; margin-bottom: 15px; }
        .vip-input {
            width: 100%; background: #FFF; border: 1px solid #E2E8F0;
            padding: 16px 16px 16px 45px; border-radius: 16px;
            font-size: 14px; color: #334155; transition: all 0.2s; outline: none;
            font-weight: 600;
        }
        .vip-input:focus { border-color: #0EA5E9; box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.1); }
        .input-icon {
            position: absolute; left: 16px; top: 18px; color: #94A3B8; 
            pointer-events: none; transition: 0.2s;
        }
        .vip-input:focus + .input-icon { color: #0EA5E9; }

        /* Botão Ação (Igual Login) */
        .btn-action {
            width: 100%; background: linear-gradient(135deg, #0EA5E9 0%, #0284C7 100%);
            color: white; padding: 16px; border-radius: 16px; font-weight: 700;
            text-transform: uppercase; font-size: 14px; letter-spacing: 1px; border: none;
            cursor: pointer; box-shadow: 0 4px 15px rgba(14, 165, 233, 0.3);
            transition: transform 0.1s, box-shadow 0.2s; margin-top: 10px;
            display: flex; align-items: center; justify-content: center; gap: 8px;
        }
        .btn-action:active { transform: scale(0.98); }
        .btn-action:disabled { background: #E2E8F0; color: #94A3B8; cursor: not-allowed; box-shadow: none; }

        /* Modal Clean (Estilo Sheet/Center) */
        .modal-backdrop {
            position: fixed; inset: 0; background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(4px);
            z-index: 100; display: none; align-items: center; justify-content: center;
            opacity: 0; transition: opacity 0.3s;
        }
        .modal-backdrop.show { display: flex; opacity: 1; }
        .modal-card {
            background: #FFF; width: 90%; max-width: 360px; border-radius: 24px;
            padding: 30px; text-align: center; transform: scale(0.9); transition: transform 0.3s;
            box-shadow: 0 20px 50px rgba(0,0,0,0.2);
        }
        .modal-backdrop.show .modal-card { transform: scale(1); }

        /* Toast Notification */
        #toast-container { position: fixed; top: 80px; right: 20px; z-index: 9999; }
        .toast-custom {
            background: #FFFFFF; border: 1px solid #E2E8F0; border-left: 4px solid #0EA5E9;
            color: #333; padding: 12px 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border-radius: 8px; display: flex; align-items: center; gap: 10px;
            transform: translateX(120%); transition: transform 0.4s;
        }
        .toast-custom.show { transform: translateX(0); }
    </style>
</head>

<body>

    <audio id="clickSound" src="https://cdn.freesound.org/previews/256/256113_3263906-lq.mp3"></audio>
    <div id="toast-container"></div>

    <div class="app-header">
        <a href="./" class="flex items-center gap-3 sound-trigger">
            <div class="w-10 h-10 rounded-xl bg-vip-light text-vip-blue flex items-center justify-center font-bold border border-vip-blue/20">
                <i data-lucide="arrow-left" class="w-5 h-5"></i>
            </div>
            <div>
                <p class="text-[10px] text-gray-400 font-bold uppercase tracking-wider">Volver al</p>
                <p class="text-sm font-bold text-gray-800 leading-none">Dashboard</p>
            </div>
        </a>
        <button class="relative p-2 text-gray-400 hover:text-vip-blue transition sound-trigger">
            <i data-lucide="headset" class="w-6 h-6"></i>
        </button>
    </div>

    <div class="wallet-card">
        <div class="flex justify-between items-start mb-6">
            <div>
                <p class="text-white/70 text-[10px] uppercase tracking-widest mb-1">Saldo Actual</p>
                <h2 class="text-3xl font-mono font-bold">R$ <?= number_format($user['balance'], 2, ',', '.') ?></h2>
            </div>
            <div class="bg-white/20 px-3 py-1 rounded-full text-[10px] font-bold uppercase border border-white/20 backdrop-blur-md">
                VIP <?= $user['vip_level'] ?? 0 ?>
            </div>
        </div>
        <div class="h-1 w-full bg-white/20 rounded-full overflow-hidden">
            <div class="h-full bg-white/80 w-3/4"></div>
        </div>
        <p class="text-[9px] text-white/60 mt-2 uppercase font-bold text-right">Sistema de Pagos Seguro</p>
    </div>

    <div class="px-5">
        
        <h3 class="text-sm font-black text-gray-800 uppercase tracking-wide mb-4">Realizar Depósito</h3>

        <div class="value-grid mb-4">
            <?php foreach ([50, 100, 200, 500, 1000, 2000] as $val): ?>
                <div class="value-chip sound-trigger" onclick="selectValue('<?= $val ?>', this)">
                    R$ <?= $val ?>
                </div>
            <?php endforeach; ?>
        </div>

        <form id="depositForm" onsubmit="handleDeposit(event)">
            <input type="hidden" name="action" value="generate_pix">
            
            <div class="input-group">
                <input 
                    type="number" 
                    id="amountInput" 
                    name="amount" 
                    class="vip-input sound-trigger" 
                    placeholder="Monto a depositar (R$)" 
                    required
                >
                <i data-lucide="dollar-sign" class="input-icon w-5 h-5"></i>
            </div>

            <div class="input-group">
                <input 
                    type="text" 
                    id="cpfInput" 
                    name="cpf" 
                    class="vip-input sound-trigger" 
                    placeholder="CPF del Titular" 
                    value="<?= htmlspecialchars($user['document'] ?? '') ?>"
                    required
                >
                <i data-lucide="fingerprint" class="input-icon w-5 h-5"></i>
            </div>

            <div class="bg-blue-50 border border-blue-100 p-3 rounded-xl flex gap-3 mb-4">
                <i data-lucide="info" class="w-5 h-5 text-vip-blue shrink-0"></i>
                <p class="text-[10px] text-gray-600 leading-tight">
                    <span class="font-bold text-vip-blue">ATENCIÓN:</span> El CPF debe coincidir con el titular de la cuenta bancaria para que la recarga sea automática.
                </p>
            </div>

            <button type="submit" id="submitBtn" class="btn-action sound-trigger">
                <span>Generar PIX</span> <i data-lucide="qr-code" class="w-4 h-4"></i>
            </button>
        </form>

    </div>

    <div id="pixModal" class="modal-backdrop">
        <div class="modal-card">
            <div class="w-16 h-16 bg-green-50 rounded-full flex items-center justify-center mx-auto mb-4 border border-green-100">
                <svg class="w-8 h-8 text-green-500 fill-current" viewBox="0 0 512 512">
                    <path d="M242.3 48.6c-9.1-6.2-21.5-6.2-30.6 0L49.1 159.2c-15.6 10.6-15.6 33.6 0 44.2l162.6 110.6c9.1 6.2 21.5 6.2 30.6 0l162.6-110.6c15.6-10.6 15.6-33.6 0-44.2L242.3 48.6zm37.2 277l-23.5 16-23.5-16L348.9 246l-50.6-34.4L256 240.4l-42.3-28.8-50.6 34.4 116.4 79.6zm-170.8-38.3L256 386l147.3-98.7L256 189.6 108.7 287.3zm147.3 126.3l119.7-81.4 17.5 11.9c13.7 9.3 13.7 29.6 0 38.9l-123.6 84c-8.1 5.5-19.1 5.5-27.2 0l-123.6-84c-13.7-9.3-13.7-29.6 0-38.9l17.5-11.9 119.7 81.4z"/>
                </svg>
            </div>
            <h3 class="text-lg font-black text-gray-800 uppercase leading-none mb-1">Pago Listo</h3>
            <p class="text-xs text-gray-400 mb-6">Escanea o copia el código abajo</p>

            <div class="bg-white p-2 border border-gray-100 rounded-xl shadow-sm inline-block mb-4">
                <img id="qrImage" src="" class="w-40 h-40 object-contain">
            </div>

            <p id="qrAmount" class="text-2xl font-mono font-bold text-gray-800 mb-4">R$ 0,00</p>

            <div class="relative mb-4">
                <input id="qrCodeText" type="text" class="w-full bg-gray-50 border border-gray-200 rounded-lg py-3 pl-3 pr-10 text-[10px] text-gray-500 font-mono" readonly>
                <button type="button" onclick="copyCode()" class="absolute right-2 top-2 text-gray-400 hover:text-vip-blue sound-trigger">
                    <i data-lucide="copy" class="w-4 h-4"></i>
                </button>
            </div>

            <button type="button" onclick="copyCode()" class="w-full py-3 bg-vip-blue text-white font-bold uppercase text-xs rounded-xl shadow-lg shadow-blue-500/30 mb-2 sound-trigger">
                Copiar Código PIX
            </button>
            <button type="button" onclick="closeModal()" class="text-xs text-gray-400 font-bold uppercase sound-trigger p-2">
                Cerrar
            </button>
        </div>
    </div>

    <?php include 'partials/menu-bottom.php'; ?>

    <script>
        lucide.createIcons();

        // 1. Som
        const audio = document.getElementById('clickSound');
        audio.volume = 0.2; 
        const playSound = () => { audio.currentTime = 0; audio.play().catch(()=>{}); };
        document.addEventListener('click', (e) => {
            if(e.target.closest('.sound-trigger')) playSound();
        });

        // 2. Máscara CPF
        const cpfEl = document.getElementById('cpfInput');
        if (cpfEl && typeof IMask !== 'undefined') {
            IMask(cpfEl, { mask: '000.000.000-00' });
        }

        // 3. Seleção de Valor (Chips)
        function selectValue(val, el) {
            document.querySelectorAll('.value-chip').forEach(c => c.classList.remove('active'));
            el.classList.add('active');
            document.getElementById('amountInput').value = val;
        }

        // 4. AJAX Deposit Logic (Core)
        async function handleDeposit(e) {
            e.preventDefault();
            
            const btn = document.getElementById('submitBtn');
            const originalText = btn.innerHTML;
            
            // Loading State
            btn.disabled = true;
            btn.innerHTML = '<i data-lucide="loader-2" class="w-5 h-5 animate-spin"></i> Procesando...';
            lucide.createIcons();

            const formData = new FormData(e.target);

            try {
                // Fetch para a própria página (PHP lá em cima processa)
                const response = await fetch('', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();

                if (data.status === 'success') {
                    // Preenche Modal
                    document.getElementById('qrImage').src = data.qrcode_img;
                    document.getElementById('qrCodeText').value = data.qrcode_text;
                    document.getElementById('qrAmount').innerText = 'R$ ' + data.amount;
                    
                    // Abre Modal
                    document.getElementById('pixModal').classList.add('show');
                    showToast('QR Code Generado!', 'success');
                } else {
                    showToast(data.message || 'Error al generar PIX', 'error');
                }

            } catch (error) {
                console.error(error);
                showToast('Error de conexión', 'error');
            } finally {
                // Reset Button
                btn.disabled = false;
                btn.innerHTML = originalText;
                lucide.createIcons();
            }
        }

        // 5. Modal & Utils
        function closeModal() {
            document.getElementById('pixModal').classList.remove('show');
        }

        function copyCode() {
            const input = document.getElementById('qrCodeText');
            input.select();
            input.setSelectionRange(0, 99999);
            navigator.clipboard.writeText(input.value).then(() => {
                showToast('Código copiado al portapapeles', 'success');
            });
        }

        // 6. Toast Notification
        function showToast(message, type = 'success') {
            const container = document.getElementById('toast-container');
            const toast = document.createElement('div');
            const isError = type !== 'success';
            const iconName = isError ? 'x-circle' : 'check-circle';
            const title = isError ? 'ERROR' : 'LISTO';
            const colorClass = isError ? 'text-vip-red' : 'text-vip-blue';
            
            toast.className = `toast-custom ${isError ? 'border-l-red-500' : ''}`;
            toast.innerHTML = `
                <div class="${colorClass}"><i data-lucide="${iconName}" class="w-6 h-6"></i></div>
                <div>
                    <p class="text-[11px] font-bold text-gray-800 uppercase tracking-wide mb-0.5">${title}</p>
                    <p class="text-[12px] text-gray-500 font-sans">${message}</p>
                </div>
            `;
            container.appendChild(toast);
            lucide.createIcons();
            requestAnimationFrame(() => toast.classList.add('show'));
            setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 600); }, 3000);
        }
    </script>
</body>
</html>