<?php
ob_start();
require_once dirname(__DIR__, 2) . '/config.php';

$user_id = $_SESSION['user_id'];
$user = currentUser();

// ========== 处理 AJAX 请求 ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'create_order') {
    header('Content-Type: application/json');
    
    $app_id = intval($_POST['app_id'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? 'alipay';
    
    $app = $db->fetchOne("SELECT * FROM apps WHERE id = $app_id AND status = 1");
    if (!$app) {
        echo json_encode(['success' => false, 'message' => '应用不存在']);
        exit;
    }
    
    $price = getDiscountedPrice($app['price'], $user_id);
    $order_no = generateOrderNo();
    $expire_at = date('Y-m-d H:i:s', strtotime('+30 minutes'));

    $db->query("INSERT INTO orders (order_no, user_id, type, item_id, amount, status, expire_at) VALUES ('$order_no', $user_id, 'app', $app_id, $price, 'pending', '$expire_at')");
    
    echo json_encode(['success' => true, 'order_no' => $order_no, 'amount' => $price, 'name' => $app['name']]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'purchase') {
    header('Content-Type: application/json');
    
    $lock_key = "purchase_lock_{$user_id}";
    if (isset($_SESSION[$lock_key]) && $_SESSION[$lock_key] > time() - 5) {
        echo json_encode(['success' => false, 'message' => '操作过于频繁，请稍后再试']);
        exit;
    }
    $_SESSION[$lock_key] = time();
    
    $app_id = intval($_POST['app_id'] ?? 0);
    
    $app = $db->fetchOne("SELECT * FROM apps WHERE id = $app_id AND status = 1");
    if (!$app) {
        echo json_encode(['success' => false, 'message' => '应用不存在']);
        exit;
    }
    
    $price = getDiscountedPrice($app['price'], $user_id);
    
    if ($user['balance'] < $price) {
        echo json_encode(['success' => false, 'message' => '余额不足，请先充值']);
        exit;
    }
    
    $db->query("START TRANSACTION");
    
    try {
        $check_balance = $db->fetchOne("SELECT balance FROM users WHERE id = $user_id FOR UPDATE");
        if ($check_balance['balance'] < $price) {
            throw new Exception('余额不足');
        }
        
        updateUserBalance($user_id, -$price, "购买应用：{$app['name']}");
        
        $license_code = generateLicenseCode();
        $expire_date = $app['duration_days'] > 0 ? date('Y-m-d', strtotime("+{$app['duration_days']} days")) : null;
        $app_key = $app['app_key'];
        $db->query("INSERT INTO licenses (license_code, app_key, app_id, user_id, expire_date, used) VALUES ('$license_code', '$app_key', $app_id, $user_id, " . ($expire_date ? "'$expire_date'" : "NULL") . ", 0)");
        
        $db->query("COMMIT");
        unset($_SESSION[$lock_key]);
        
        require_once dirname(__DIR__, 2) . '/includes/mail_helper.php';
        $user_info = $db->fetchOne("SELECT * FROM users WHERE id = $user_id");
        if ($user_info && !empty($user_info['email']) && ($user_info['email_notify'] ?? 1)) {
            sendConsumeNotification($user_info, $app['name'], $price, '余额支付');
        }
        
        $invite_record = $db->fetchOne("SELECT * FROM invite_records WHERE invitee_id = $user_id AND status = 0");
        if ($invite_record) {
            $db->query("UPDATE invite_records SET status = 1 WHERE id = {$invite_record['id']}");
            
            $rebate_rate = 10;
            $rebate_amount = $price * $rebate_rate / 100;
            
            if ($rebate_amount > 0) {
                $db->query("INSERT INTO rebate_records (user_id, from_user_id, order_id, amount, rate) 
                            VALUES ({$invite_record['inviter_id']}, $user_id, 0, $rebate_amount, $rebate_rate)");
                $db->query("UPDATE users SET rebate_balance = rebate_balance + $rebate_amount WHERE id = {$invite_record['inviter_id']}");
            }
        }
        
        echo json_encode(['success' => true, 'message' => '购买成功']);
        
    } catch (Exception $e) {
        $db->query("ROLLBACK");
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

$apps = $db->fetchAll("SELECT * FROM apps WHERE status = 1 ORDER BY id DESC");
$payment_methods = getEnabledPaymentMethods();
?>

<div class="buy-app-container">
    <!-- 页面头部 -->
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:cart.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            购买应用授权
        </h2>
        <p class="page-desc">选择您需要授权的应用</p>
    </div>
    
    <!-- 应用卡片网格 -->
    <div class="apps-grid">
        <?php foreach ($apps as $app): ?>
            <?php 
            $display_price = getDiscountedPrice($app['price'], $user_id);
            $has_discount = $display_price < $app['price'];
            ?>
            <div class="app-card">
                <div class="app-icon">
                    <img src="https://api.iconify.design/mdi:application.svg?color=%23667eea" width="32" height="32" alt="">
                </div>
                <div class="app-header">
                    <h3><?php echo htmlspecialchars($app['name']); ?></h3>
                    <div class="price">
                        <?php if ($has_discount): ?>
                            <span class="original-price">¥<?php echo number_format($app['price'], 2); ?></span>
                            <span class="discount-price">¥<?php echo number_format($display_price, 2); ?></span>
                        <?php else: ?>
                            <span class="price-amount">¥<?php echo number_format($display_price, 2); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <p class="app-desc"><?php echo htmlspecialchars($app['description'] ?: '暂无描述'); ?></p>
                <div class="app-meta">
                    <span class="meta-item">
                        <img src="https://api.iconify.design/mdi:calendar-clock.svg?color=%23f59e0b" width="16" height="16" alt="">
                        授权期限：<?php echo $app['duration_days'] ? $app['duration_days'] . '天' : '永久'; ?>
                    </span>
                </div>
                <div class="app-footer">
                    <button class="btn btn-primary buy-btn" 
                            data-id="<?php echo $app['id']; ?>" 
                            data-name="<?php echo htmlspecialchars($app['name']); ?>" 
                            data-price="<?php echo $display_price; ?>">
                        <img src="https://api.iconify.design/mdi:cart.svg?color=white" width="16" height="16" style="margin-right: 6px;" alt="">
                        立即购买
                    </button>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    
    <?php if (empty($apps)): ?>
        <div class="empty-state">
            <img src="https://api.iconify.design/mdi:package-variant-closed.svg?color=%239ca3af" width="64" height="64" alt="">
            <p>暂无可用应用</p>
        </div>
    <?php endif; ?>
</div>

<!-- 购买确认弹窗 -->
<div id="buyModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>
                <img src="https://api.iconify.design/mdi:cart-check.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
                确认购买
            </h3>
            <button type="button" class="modal-close">
                <img src="https://api.iconify.design/mdi:close.svg?color=%239ca3af" width="20" height="20" alt="">
            </button>
        </div>
        <div class="modal-body">
            <div class="confirm-item">
                <span class="label">应用名称：</span>
                <strong id="modal_app_name"></strong>
            </div>
            <div class="confirm-item">
                <span class="label">购买金额：</span>
                <strong id="modal_price" class="price-highlight"></strong>
            </div>
            <div class="payment-section">
                <p class="section-label">
                    <img src="https://api.iconify.design/mdi:credit-card.svg?color=%236b7280" width="16" height="16" style="margin-right: 6px;" alt="">
                    支付方式：
                </p>
                <div class="payment-methods">
                    <label class="payment-method">
                        <input type="radio" name="payment_method" value="balance" checked> 
                        <span class="method-content">
                            <img src="https://api.iconify.design/mdi:wallet.svg?color=%23667eea" width="18" height="18" alt="">
                            <span class="method-name">余额支付</span>
                            <span class="method-balance">(余额 ¥<?php echo number_format($user['balance'], 2); ?>)</span>
                        </span>
                    </label>
                    <?php foreach ($payment_methods as $method): ?>
                        <label class="payment-method">
                            <input type="radio" name="payment_method" value="<?php echo $method['value']; ?>"> 
                            <span class="method-content">
                                <img src="/assets/svg/<?php echo $method['value'] == 'alipay' ? 'alipay-ys' : 'wxpay-ys'; ?>.svg" width="18" height="18" alt="">
                                <span class="method-name"><?php echo htmlspecialchars($method['name']); ?></span>
                            </span>
                        </label>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php if ($user['balance'] < 1): ?>
                <div class="balance-warning">
                    <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23f59e0b" width="16" height="16" style="margin-right: 6px;" alt="">
                    余额不足，请先充值或选择在线支付
                </div>
            <?php endif; ?>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary cancel-btn">
                <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                取消
            </button>
            <button class="btn btn-primary confirm-btn">
                <img src="https://api.iconify.design/mdi:check.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                确认购买
            </button>
        </div>
    </div>
</div>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.buy-app-container {
    max-width: 100%;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    margin-bottom: 28px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 6px;
}
.page-desc {
    font-size: 14px;
    color: var(--text-secondary);
    margin-left: 36px;
}

/* 应用卡片网格 */
.apps-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 24px;
}
.app-card {
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-lg);
    padding: 24px;
    transition: all 0.3s ease;
}
.app-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow-lg);
    border-color: var(--primary-color);
}
.app-icon {
    width: 52px;
    height: 52px;
    border-radius: var(--radius-md);
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 16px;
}
.app-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
}
.app-header h3 {
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}
.price {
    text-align: right;
}
.original-price {
    text-decoration: line-through;
    font-size: 12px;
    color: var(--text-muted);
    display: block;
}
.discount-price, .price-amount {
    font-size: 20px;
    font-weight: 700;
    color: var(--primary-color);
}
.app-desc {
    color: var(--text-secondary);
    margin-bottom: 16px;
    line-height: 1.6;
    font-size: 14px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    min-height: 44px;
}
.app-meta {
    margin-bottom: 20px;
    padding: 14px 0;
    border-top: 1px solid var(--border-color);
    border-bottom: 1px solid var(--border-color);
}
.meta-item {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: var(--text-secondary);
}
.app-footer {
    margin-top: 8px;
}
.app-footer .btn {
    width: 100%;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 11px 20px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
}

/* 空状态 */
.empty-state {
    text-align: center;
    padding: 80px 20px;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px dashed var(--border-color);
    margin-top: 20px;
}
.empty-state img {
    opacity: 0.5;
    margin-bottom: 16px;
}
.empty-state p {
    color: var(--text-muted);
    font-size: 16px;
}

/* 弹窗 */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    width: 90%;
    max-width: 450px;
    box-shadow: var(--shadow-lg);
}
.modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    margin: 0;
}
.modal-close {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    border-radius: var(--radius-sm);
    transition: background 0.2s;
    display: flex;
}
.modal-close:hover {
    background: var(--bg-secondary);
}
.modal-body {
    padding: 24px;
}
.modal-footer {
    padding: 16px 24px 24px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}

.confirm-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}
.confirm-item .label {
    width: 80px;
    color: var(--text-secondary);
}
.price-highlight {
    font-size: 24px;
    color: var(--primary-color);
}

.payment-section {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
}
.section-label {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    font-weight: 500;
}
.payment-methods {
    display: flex;
    flex-direction: column;
    gap: 10px;
}
.payment-method {
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 12px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    transition: all 0.2s;
}
.payment-method:hover {
    border-color: var(--primary-color);
    background: rgba(102, 126, 234, 0.03);
}
.payment-method input {
    margin-right: 12px;
    accent-color: var(--primary-color);
}
.method-content {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
}
.method-name {
    flex: 1;
    font-weight: 500;
}
.method-balance {
    font-size: 13px;
    color: var(--text-muted);
}

.balance-warning {
    display: flex;
    align-items: center;
    margin-top: 16px;
    padding: 10px 14px;
    background: #fef3c7;
    border-radius: var(--radius-sm);
    font-size: 13px;
    color: #92400e;
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: white;
    animation: spin 0.6s linear infinite;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}

/* 响应式 */
@media (max-width: 768px) {
    .apps-grid {
        grid-template-columns: 1fr;
    }
    .page-desc {
        margin-left: 0;
    }
}
</style>

<script>
let isProcessing = false;
let currentApp = null;
const modal = document.getElementById('buyModal');

function closeModal() {
    modal.style.display = 'none';
    currentApp = null;
}

function showModal(appId, appName, price) {
    currentApp = { id: appId, name: appName, price: price };
    document.getElementById('modal_app_name').innerText = appName;
    document.getElementById('modal_price').innerText = '¥' + parseFloat(price).toFixed(2);
    modal.style.display = 'flex';
}

// 绑定购买按钮
document.querySelectorAll('.buy-btn').forEach(btn => {
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        if (isProcessing) {
            window.showToast && window.showToast('正在处理中，请稍后...', 'warning');
            return;
        }
        showModal(this.dataset.id, this.dataset.name, this.dataset.price);
    });
});

// 关闭弹窗
document.querySelector('.modal-close')?.addEventListener('click', closeModal);
document.querySelector('.cancel-btn')?.addEventListener('click', closeModal);
modal.addEventListener('click', function(e) {
    if (e.target === modal) closeModal();
});

// 确认购买
document.querySelector('.confirm-btn').addEventListener('click', function() {
    if (isProcessing) {
        window.showToast && window.showToast('正在处理中，请稍后...', 'warning');
        return;
    }
    
    const paymentMethod = document.querySelector('input[name="payment_method"]:checked')?.value;
    if (!currentApp) return;
    
    isProcessing = true;
    const confirmBtn = this;
    const originalHtml = confirmBtn.innerHTML;
    confirmBtn.innerHTML = '<span class="loading-spinner"></span> 处理中...';
    confirmBtn.disabled = true;
    
    if (paymentMethod === 'balance') {
        fetch('/modules/user/buy_app.php?action=purchase', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `app_id=${currentApp.id}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.showToast && window.showToast('购买成功', 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                window.showToast && window.showToast(data.message || '购买失败', 'error');
                confirmBtn.innerHTML = originalHtml;
                confirmBtn.disabled = false;
                isProcessing = false;
            }
            closeModal();
        })
        .catch(error => {
            console.error('错误:', error);
            window.showToast && window.showToast('网络错误', 'error');
            confirmBtn.innerHTML = originalHtml;
            confirmBtn.disabled = false;
            isProcessing = false;
            closeModal();
        });
    } else {
        fetch('/modules/user/buy_app.php?action=create_order', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `app_id=${currentApp.id}&payment_method=${paymentMethod}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                localStorage.setItem('pending_order', data.order_no);
                localStorage.setItem('pending_method', paymentMethod);
                
                const payUrl = '/modules/payment/api.php?order_no=' + encodeURIComponent(data.order_no) + 
                               '&amount=' + encodeURIComponent(data.amount) + 
                               '&type=' + encodeURIComponent(paymentMethod) + 
                               '&name=' + encodeURIComponent(data.name);
                
                fetch(payUrl)
                    .then(res => res.json())
                    .then(payData => {
                        if (payData.code == 1 && payData.qrcode) {
                            showPaymentModal(paymentMethod, data.amount, payData.qrcode, data.order_no);
                        } else {
                            window.showToast && window.showToast(payData.msg || '支付失败', 'error');
                        }
                        confirmBtn.innerHTML = originalHtml;
                        confirmBtn.disabled = false;
                        isProcessing = false;
                    })
                    .catch(error => {
                        console.error('支付请求错误:', error);
                        window.showToast && window.showToast('网络错误', 'error');
                        confirmBtn.innerHTML = originalHtml;
                        confirmBtn.disabled = false;
                        isProcessing = false;
                    });
            } else {
                window.showToast && window.showToast(data.message || '创建订单失败', 'error');
                confirmBtn.innerHTML = originalHtml;
                confirmBtn.disabled = false;
                isProcessing = false;
            }
            closeModal();
        })
        .catch(error => {
            console.error('错误:', error);
            window.showToast && window.showToast('网络错误', 'error');
            confirmBtn.innerHTML = originalHtml;
            confirmBtn.disabled = false;
            isProcessing = false;
            closeModal();
        });
    }
});

// 支付弹窗和轮询函数（保持不变）
function startPolling(orderNo, modalElement) {
    let count = 0;
    const maxAttempts = 60;
    
    const interval = setInterval(() => {
        count++;
        
        fetch('/api/check_order.php?order_no=' + encodeURIComponent(orderNo))
            .then(response => response.json())
            .then(data => {
                if (data.status === 'paid') {
                    clearInterval(interval);
                    localStorage.removeItem('pending_order');
                    localStorage.removeItem('pending_method');
                    if (modalElement && modalElement.parentNode) {
                        modalElement.remove();
                    }
                    window.showToast && window.showToast('支付成功！', 'success');
                    setTimeout(() => location.href = '/admin.php?page=orders', 1500);
                } else if (count >= maxAttempts) {
                    clearInterval(interval);
                    localStorage.removeItem('pending_order');
                    localStorage.removeItem('pending_method');
                    window.showToast && window.showToast('支付超时，请稍后查看订单状态', 'warning');
                }
            });
    }, 3000);
}

function showPaymentModal(paymentMethod, amount, qrcode, orderNo) {
    const isAlipay = paymentMethod === 'alipay';
    const bgColor = isAlipay ? 'linear-gradient(135deg, #1677FF, #0d5cb6)' : 'linear-gradient(135deg, #07C160, #059669)';
    const title = isAlipay ? '支付宝扫码支付' : '微信扫码支付';
    const btnColor = isAlipay ? '#1677FF' : '#07C160';
    const payName = isAlipay ? '支付宝' : '微信';
    
    const iconHtml = isAlipay 
        ? '<img src="/assets/svg/alipay.svg" style="width: 32px; height: 32px;" alt="">'
        : '<img src="https://api.iconify.design/mdi:wechat.svg?color=white" style="width: 32px; height: 32px;" alt="">';
    
    const modalOverlay = document.createElement('div');
    modalOverlay.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;z-index:10001;';
    
    modalOverlay.innerHTML = `
        <div style="background:var(--bg-primary);border-radius:20px;padding:30px;max-width:380px;width:90%;text-align:center;">
            <div style="background: ${bgColor}; padding:20px; border-radius:16px; margin-bottom:20px;">
                <div style="display:flex; align-items:center; justify-content:center; gap:10px;">
                    ${iconHtml}
                    <h3 style="color:white; margin:0;">${title}</h3>
                </div>
            </div>
            <p style="color:var(--text-secondary);margin-bottom:10px;">请使用${payName}扫码支付</p>
            <p style="font-size:24px;font-weight:bold;color:${btnColor};margin-bottom:15px;">¥${amount}</p>
            <div id="qrcode-container" style="margin:15px auto;width:200px;height:200px;"></div>
            <p style="color:var(--text-muted);font-size:12px;">支付成功后自动跳转</p>
            <button class="close-modal-btn" style="margin-top:20px;padding:10px 25px;background:${btnColor};color:white;border:none;border-radius:30px;cursor:pointer;">关闭</button>
        </div>
    `;
    
    document.body.appendChild(modalOverlay);
    
    if (typeof QRCode !== 'undefined') {
        new QRCode(document.getElementById('qrcode-container'), {
            text: qrcode,
            width: 200,
            height: 200,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
        });
    } else {
        const img = document.createElement('img');
        img.src = qrcode;
        img.style.width = '200px';
        img.style.height = '200px';
        document.getElementById('qrcode-container').appendChild(img);
    }
    
    modalOverlay.querySelector('.close-modal-btn').onclick = () => {
        modalOverlay.remove();
        localStorage.removeItem('pending_order');
        localStorage.removeItem('pending_method');
    };
    
    modalOverlay.onclick = (e) => {
        if (e.target === modalOverlay) {
            modalOverlay.remove();
            localStorage.removeItem('pending_order');
            localStorage.removeItem('pending_method');
        }
    };
    
    startPolling(orderNo, modalOverlay);
}
</script>