<?php
$user_id = $_SESSION['user_id'];
$user = currentUser();
$groups = $db->fetchAll("SELECT * FROM user_groups WHERE status = 1 AND price > 0 ORDER BY price ASC");

$current_purchase = $db->fetchOne("
    SELECT ug.*, up.expire_date
    FROM user_group_purchases up 
    JOIN user_groups ug ON up.group_id = ug.id 
    WHERE up.user_id = $user_id 
    ORDER BY up.id DESC LIMIT 1
");
?>

<!-- 当前会员 -->
<div class="card">
    <div style="display: flex; align-items: center; gap: 10px;">
        <img src="https://api.iconify.design/mdi:shield-account.svg?color=%23667eea" width="36" height="36" alt="">
        <div>
            <div style="font-weight: 600;"><?php echo htmlspecialchars($current_purchase['name'] ?? '普通会员'); ?></div>
            <div style="font-size: 12px; color: #999;">
                <?php echo isset($current_purchase['expire_date']) && $current_purchase['expire_date'] ? '有效期至 '.$current_purchase['expire_date'] : '永久'; ?>
            </div>
        </div>
        <?php if ($current_purchase && $current_purchase['discount'] < 100): ?>
        <span style="margin-left: auto; background: #667eea; color: white; padding: 4px 10px; border-radius: 20px; font-size: 12px;">
            <?php echo $current_purchase['discount']; ?>折
        </span>
        <?php endif; ?>
    </div>
</div>

<!-- 会员套餐 -->
<?php foreach ($groups as $group): ?>
<div class="card">
    <div style="display: flex; justify-content: space-between; align-items: center;">
        <div>
            <div style="font-weight: 600; font-size: 18px;"><?php echo htmlspecialchars($group['name']); ?></div>
            <div style="color: #999; font-size: 13px;"><?php echo $group['duration_days'] ? $group['duration_days'].'天' : '永久'; ?></div>
        </div>
        <div style="text-align: right;">
            <div style="font-size: 24px; font-weight: 700; color: #667eea;">¥<?php echo number_format($group['price'], 2); ?></div>
            <div style="font-size: 12px; color: #10b981;"><?php echo $group['discount']; ?>折优惠</div>
        </div>
    </div>
    <button class="btn btn-primary btn-block" style="margin-top: 12px;" onclick="buyGroup(<?php echo $group['id']; ?>, '<?php echo htmlspecialchars(addslashes($group['name'])); ?>', <?php echo $group['price']; ?>)">
        立即购买
    </button>
</div>
<?php endforeach; ?>

<script>
async function buyGroup(id, name, price) {
    const modalId = 'buyGroupModal_' + 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);
    
    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_group.php?action=purchase', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `group_id=${id}`
            });
            const d = await r.json();
            showToast(d.message);
            if (d.success) setTimeout(() => location.reload(), 1500);
        } else {
            const r = await fetch('/modules/user/buy_group.php?action=create_order', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `group_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=orders', 1500);
        } else if (++count > 60) {
            clearInterval(timer);
        }
    }, 3000);
}
</script>
<script src="/assets/js/qrcode.min.js"></script>