<?php
$user_id = $_SESSION['user_id'];
$user = currentUser();
$apps = $db->fetchAll("SELECT * FROM apps WHERE status = 1 ORDER BY id DESC");
?>

<?php foreach ($apps as $app): ?>
<?php $price = getDiscountedPrice($app['price'], $user_id); ?>
<div class="card">
    <div style="display: flex; gap: 12px;">
        <img src="https://api.iconify.design/mdi:application.svg?color=%23667eea" width="44" height="44" alt="">
        <div style="flex:1;">
            <div style="font-weight: 600;"><?php echo htmlspecialchars($app['name']); ?></div>
            <div style="color: #999; font-size: 12px;"><?php echo $app['duration_days'] ? $app['duration_days'].'天' : '永久'; ?></div>
        </div>
        <div style="text-align: right;">
            <div style="font-size: 20px; font-weight: 700; color: #667eea;">¥<?php echo number_format($price, 2); ?></div>
            <?php if ($price < $app['price']): ?>
            <div style="font-size: 12px; color: #999; text-decoration: line-through;">¥<?php echo number_format($app['price'], 2); ?></div>
            <?php endif; ?>
        </div>
    </div>
    <?php if ($app['description']): ?>
    <p style="font-size: 13px; color: #666; margin: 10px 0;"><?php echo htmlspecialchars($app['description']); ?></p>
    <?php endif; ?>
    <button class="btn btn-primary btn-block" onclick="buyApp(<?php echo $app['id']; ?>, '<?php echo htmlspecialchars(addslashes($app['name'])); ?>', <?php echo $price; ?>)">
        <img src="https://api.iconify.design/mdi:cart.svg?color=white" width="18" height="18" alt="">
        立即购买
    </button>
</div>
<?php endforeach; ?>

<script>
async function buyApp(id, name, price) {
    // 创建弹窗
    const modalId = 'buyModal_' + Date.now();
    const html = `
        <div id="${modalId}" style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:999;padding:20px;display:flex;align-items:center;justify-content:center;">
            <div style="background:white;border-radius:16px;padding:20px;width:100%;max-width:350px;">
                <h3 style="margin-bottom:12px;">确认购买</h3>
                <p style="margin-bottom:12px;"><strong>${name}</strong> - ¥${price.toFixed(2)}</p>
                <select id="payMethod_${modalId}" style="width:100%;padding:12px;border:1px solid #e5e7eb;border-radius:8px;margin-bottom:16px;">
                    <option value="balance">余额支付 (余额 ¥<?php echo number_format($user['balance'], 2); ?>)</option>
                    <option value="alipay">支付宝</option>
                    <option value="wxpay">微信支付</option>
                </select>
                <div style="display:flex;gap:8px;">
                    <button onclick="document.getElementById('${modalId}').remove()" style="flex:1;padding:12px;background:#f5f5f5;border:none;border-radius:8px;">取消</button>
                    <button id="confirmBtn_${modalId}" style="flex:1;padding:12px;background:#667eea;color:white;border:none;border-radius:8px;">确认</button>
                </div>
            </div>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', html);
    
    // 等待 DOM 更新后绑定事件
    await new Promise(resolve => setTimeout(resolve, 50));
    
    const modal = document.getElementById(modalId);
    const paySelect = document.getElementById(`payMethod_${modalId}`);
    const confirmBtn = document.getElementById(`confirmBtn_${modalId}`);
    
    confirmBtn.onclick = async () => {
        const method = paySelect.value;
        modal.remove();
        
        if (method === 'balance') {
            const r = await fetch('/modules/user/buy_app.php?action=purchase', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `app_id=${id}`
            });
            const d = await r.json();
            showToast(d.message);
            if (d.success) setTimeout(() => location.href = '?page=licenses', 1500);
        } else {
            const r = await fetch('/modules/user/buy_app.php?action=create_order', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `app_id=${id}&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=${price}&type=${method}&name=${encodeURIComponent(name)}`);
                const payData = await pay.json();
                if (payData.qrcode) {
                    showPaymentModal(method, price, payData.qrcode, d.order_no);
                } else if (payData.payurl) {
                    location.href = payData.payurl;
                } else {
                    showToast(payData.msg || '获取支付信息失败');
                }
            } else {
                showToast(d.message);
            }
        }
    };
    
    // 点击背景关闭
    modal.onclick = (e) => {
        if (e.target === modal) modal.remove();
    };
}

function showPaymentModal(method, amount, qrcode, orderNo) {
    const modalId = 'payModal_' + Date.now();
    const html = `
        <div id="${modalId}" 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 style="font-size:20px;font-weight:700;margin:10px 0;">¥${amount}</p>
                <div id="qrcode_${modalId}" style="display:flex;justify-content:center;"></div>
                <button onclick="document.getElementById('${modalId}').remove()" style="margin-top:16px;padding:10px 20px;background:#f5f5f5;border:none;border-radius:8px;width:100%;">关闭</button>
            </div>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', html);
    
    setTimeout(() => {
        new QRCode(document.getElementById(`qrcode_${modalId}`), {text: qrcode, width: 200, height: 200});
    }, 50);
    
    pollOrderStatus(orderNo, modalId);
}

function pollOrderStatus(orderNo, modalId) {
    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);
            const modal = document.getElementById(modalId);
            if (modal) modal.remove();
            showToast('支付成功');
            setTimeout(() => location.href = '?page=licenses', 1500);
        } else if (++count > 60) {
            clearInterval(timer);
        }
    }, 3000);
}
</script>
<script src="/assets/js/qrcode.min.js"></script>