<?php
$user_id = $_SESSION['user_id'];
$user = currentUser();
$recharge_options = [10, 50, 100, 200, 500];
?>

<div class="card" style="text-align: center;">
    <div style="font-size: 14px; color: #999;">当前余额</div>
    <div style="font-size: 40px; font-weight: 700; color: #667eea;">¥<?php echo number_format($user['balance'], 2); ?></div>
</div>

<!-- 在线充值 -->
<div class="card">
    <h3 style="margin-bottom: 16px; font-size: 15px;">在线充值</h3>
    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 16px;">
        <?php foreach ($recharge_options as $opt): ?>
        <button class="amount-option" data-amount="<?php echo $opt; ?>" style="padding: 12px; border: 1px solid #e5e7eb; border-radius: 8px; background: white;">
            ¥<?php echo $opt; ?>
        </button>
        <?php endforeach; ?>
    </div>
    <input type="number" id="customAmount" placeholder="自定义金额" step="0.01" min="1" style="width:100%;padding:12px;border:1px solid #e5e7eb;border-radius:8px;margin-bottom:12px;">
    <select id="payMethod" style="width:100%;padding:12px;border:1px solid #e5e7eb;border-radius:8px;margin-bottom:12px;">
        <option value="alipay">支付宝</option>
        <option value="wxpay">微信支付</option>
    </select>
    <button class="btn btn-primary btn-block" onclick="rechargeOnline()">
        <img src="https://api.iconify.design/mdi:wallet.svg?color=white" width="18" height="18" alt="">
        立即充值
    </button>
</div>

<!-- 卡密充值 -->
<div class="card">
    <h3 style="margin-bottom: 16px; font-size: 15px;">卡密充值</h3>
    <input type="text" id="cardCode" placeholder="请输入卡密" style="width:100%;padding:12px;border:1px solid #e5e7eb;border-radius:8px;margin-bottom:12px;">
    <button class="btn btn-primary btn-block" onclick="rechargeCard()">
        <img src="https://api.iconify.design/mdi:ticket.svg?color=white" width="18" height="18" alt="">
        卡密充值
    </button>
</div>

<script>
let selectedAmount = 0;
document.querySelectorAll('.amount-option').forEach(btn => {
    btn.addEventListener('click', function() {
        document.querySelectorAll('.amount-option').forEach(b => b.style.background = 'white');
        this.style.background = '#667eea';
        this.style.color = 'white';
        selectedAmount = parseFloat(this.dataset.amount);
        document.getElementById('customAmount').value = '';
    });
});

async function rechargeOnline() {
    let amount = selectedAmount || parseFloat(document.getElementById('customAmount').value);
    if (!amount || amount <= 0) { showToast('请输入金额'); return; }
    const method = document.getElementById('payMethod').value;
    
    const r = await fetch('/modules/user/recharge.php?action=create_order', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `amount=${amount}&payment_method=${method}`
    });
    const d = await r.json();
    if (d.success) {
        const pay = await fetch(`/modules/payment/api.php?order_no=${d.order_no}&amount=${amount}&type=${method}&name=账户充值`);
        const payData = await pay.json();
        if (payData.qrcode) {
            showPaymentModal(method, amount, payData.qrcode, d.order_no);
        } else if (payData.payurl) {
            location.href = payData.payurl;
        }
    } else {
        showToast(d.message);
    }
}

async function rechargeCard() {
    const code = document.getElementById('cardCode').value.trim();
    if (!code) { showToast('请输入卡密'); return; }
    
    const r = await fetch('/modules/user/recharge.php?action=card_recharge', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `card_code=${encodeURIComponent(code)}`
    });
    const d = await r.json();
    showToast(d.message);
    if (d.success) setTimeout(() => location.reload(), 1500);
}

function showPaymentModal(method, amount, qrcode, orderNo) {
    const html = `
        <div style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.7);z-index:999;display:flex;align-items:center;justify-content:center;">
            <div style="background:white;border-radius:16px;padding:20px;width:280px;text-align:center;">
                <h3>${method=='alipay'?'支付宝':'微信'}扫码</h3>
                <p>¥${amount}</p>
                <div id="qrcode"></div>
                <button onclick="this.closest('div[style*=fixed]').remove()" style="margin-top:16px;padding:10px 20px;background:#f5f5f5;border:none;border-radius:8px;">关闭</button>
            </div>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', html);
    new QRCode(document.getElementById('qrcode'), {text: qrcode, width: 200, height: 200});
    
    let count = 0;
    const timer = setInterval(async () => {
        const r = await fetch(`/api/check_order.php?order_no=${orderNo}`);
        const d = await r.json();
        if (d.status === 'paid') {
            clearInterval(timer);
            showToast('充值成功');
            setTimeout(() => location.reload(), 1500);
        } else if (++count > 60) clearInterval(timer);
    }, 3000);
}
</script>
<script src="/assets/js/qrcode.min.js"></script>