<?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');
    
    $amount = floatval($_POST['amount'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? 'alipay';
    
    if ($amount <= 0) {
        echo json_encode(['success' => false, 'message' => '金额错误']);
        exit;
    }
    
    $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, amount, status, expire_at) VALUES ('$order_no', $user_id, 'recharge', $amount, 'pending', '$expire_at')");
    
    echo json_encode(['success' => true, 'order_no' => $order_no]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'card_recharge') {
    header('Content-Type: application/json');
    
    $card_code_input = trim($_POST['card_code'] ?? '');
    
    if (empty($card_code_input)) {
        echo json_encode(['success' => false, 'message' => '请输入卡密']);
        exit;
    }
    
    $card_code = strtoupper(trim($card_code_input));
    $card = $db->fetchOne("SELECT * FROM card_codes WHERE card_code = '$card_code'");
    
    if (!$card) {
        $clean_code = str_replace('-', '', $card_code);
        if (strlen($clean_code) == 16) {
            $formatted = substr($clean_code, 0, 4) . '-' . substr($clean_code, 4, 4) . '-' . substr($clean_code, 8, 4) . '-' . substr($clean_code, 12, 4);
            $card = $db->fetchOne("SELECT * FROM card_codes WHERE card_code = '$formatted'");
        }
    }
    
    if (!$card) {
        echo json_encode(['success' => false, 'message' => '卡密不存在']);
        exit;
    }
    
    if ($card['status'] == 1) {
        echo json_encode(['success' => false, 'message' => '卡密已被使用']);
        exit;
    }
    
    if ($card['expire_at'] && strtotime($card['expire_at']) < time()) {
        echo json_encode(['success' => false, 'message' => '卡密已过期']);
        exit;
    }
    
    $db->query("START TRANSACTION");
    
    try {
        $db->query("UPDATE users SET balance = balance + {$card['amount']} WHERE id = $user_id");
        $db->query("UPDATE card_codes SET status = 1, used_by = $user_id, used_at = NOW() WHERE id = {$card['id']}");
        addBalanceLog($user_id, $card['amount'], 'recharge', "卡密充值：{$card['card_code']}");
        
        $db->query("COMMIT");
        
        $user_after = $db->fetchOne("SELECT * FROM users WHERE id = $user_id");
        
        require_once dirname(__DIR__, 2) . '/includes/mail_helper.php';
        if (!empty($user_after['email']) && ($user_after['email_notify'] ?? 1)) {
            sendCardRechargeNotification($user_after, $card['amount'], $card['card_code']);
        }
        
        echo json_encode(['success' => true, 'message' => '充值成功！金额：¥' . number_format($card['amount'], 2)]);
        
    } catch (Exception $e) {
        $db->query("ROLLBACK");
        echo json_encode(['success' => false, 'message' => '充值失败，请重试']);
    }
    exit;
}

$recharge_options = [10, 50, 100, 200, 500];
$error = '';
$payment_methods = getEnabledPaymentMethods();
$recharge_method = $_GET['method'] ?? 'online';
?>

<div class="recharge-container">
    <!-- 页面头部 -->
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:wallet.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            余额充值
        </h2>
        <div class="balance-display">
            <span class="balance-label">当前余额：</span>
            <span class="balance-value">¥<?php echo number_format($user['balance'], 2); ?></span>
        </div>
    </div>
    
    <?php if ($error): ?>
        <div class="alert alert-error">
            <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="20" height="20" style="margin-right: 8px;" alt="">
            <?php echo htmlspecialchars($error); ?>
        </div>
    <?php endif; ?>
    
    <!-- 切换标签 -->
    <div class="recharge-tabs">
        <div class="recharge-tab <?php echo $recharge_method == 'online' ? 'active' : ''; ?>" data-method="online">
            <img src="https://api.iconify.design/mdi:credit-card.svg?color=<?php echo $recharge_method == 'online' ? 'white' : '%236b7280'; ?>" width="18" height="18" style="margin-right: 8px;" alt="">
            在线支付
        </div>
        <div class="recharge-tab <?php echo $recharge_method == 'card' ? 'active' : ''; ?>" data-method="card">
            <img src="https://api.iconify.design/mdi:ticket.svg?color=<?php echo $recharge_method == 'card' ? 'white' : '%236b7280'; ?>" width="18" height="18" style="margin-right: 8px;" alt="">
            卡密充值
        </div>
    </div>
    
    <!-- 在线支付面板 -->
    <div id="onlinePanel" class="recharge-panel" style="display: <?php echo $recharge_method == 'online' ? 'block' : 'none'; ?>;">
        <div class="recharge-card">
            <div class="section-title">
                <img src="https://api.iconify.design/mdi:cash-multiple.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
                选择充值金额
            </div>
            <div class="amount-options">
                <?php foreach ($recharge_options as $opt): ?>
                    <div class="amount-option" data-amount="<?php echo $opt; ?>">
                        <span class="currency">¥</span>
                        <span class="amount"><?php echo $opt; ?></span>
                    </div>
                <?php endforeach; ?>
                <div class="amount-option custom">
                    <input type="number" id="custom_amount" placeholder="自定义" step="0.01" min="1">
                </div>
            </div>
            
            <div class="payment-section">
                <div class="section-title">
                    <img src="https://api.iconify.design/mdi:credit-card.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
                    支付方式
                </div>
                <div class="payment-methods">
                    <?php foreach ($payment_methods as $method): ?>
                        <label class="payment-method">
                            <input type="radio" name="payment_method" value="<?php echo $method['value']; ?>" <?php echo $method['value'] == 'alipay' ? 'checked' : ''; ?>>
                            <span class="method-icon">
                                <img src="/assets/svg/<?php echo $method['value'] == 'alipay' ? 'alipay-ys' : 'wxpay-ys'; ?>.svg" width="28" height="28" alt="">
                            </span>
                            <span class="method-name"><?php echo htmlspecialchars($method['name']); ?></span>
                        </label>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <form id="rechargeForm" class="recharge-form">
                <input type="hidden" name="amount" id="selected_amount" value="">
                <button type="submit" class="btn btn-primary btn-block">
                    <img src="https://api.iconify.design/mdi:wallet.svg?color=white" width="18" height="18" style="margin-right: 8px;" alt="">
                    立即充值
                </button>
            </form>
        </div>
    </div>
    
    <!-- 卡密充值面板 -->
    <div id="cardPanel" class="recharge-panel" style="display: <?php echo $recharge_method == 'card' ? 'block' : 'none'; ?>;">
        <div class="recharge-card">
            <div class="section-title">
                <img src="https://api.iconify.design/mdi:ticket.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
                卡密充值
            </div>
            <p class="card-tip">输入卡密直接充值到账户余额</p>
            
            <div class="card-input-wrapper">
                <img src="https://api.iconify.design/mdi:ticket.svg?color=%23667eea" width="18" height="18" class="card-input-icon" alt="">
                <input type="text" id="card_code" placeholder="XXXX-XXXX-XXXX-XXXX">
            </div>
            
            <div id="card_result" class="card-result" style="display: none;"></div>
            
            <button id="cardRechargeBtn" class="btn btn-primary btn-block">
                <img src="https://api.iconify.design/mdi:check-circle.svg?color=white" width="18" height="18" style="margin-right: 8px;" alt="">
                立即充值
            </button>
            
            <div class="recharge-tip">
                <img src="https://api.iconify.design/mdi:information.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                卡密由管理员生成，如有问题请联系客服
            </div>
        </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;
}

.recharge-container {
    max-width: 560px;
    margin: 0 auto;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 28px;
    flex-wrap: wrap;
    gap: 16px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}
.balance-display {
    display: flex;
    align-items: baseline;
    gap: 8px;
    padding: 10px 20px;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.08) 0%, rgba(102, 126, 234, 0.02) 100%);
    border-radius: 30px;
}
.balance-label {
    font-size: 14px;
    color: var(--text-secondary);
}
.balance-value {
    font-size: 24px;
    font-weight: 700;
    color: var(--primary-color);
}

/* 提示消息 */
.alert {
    display: flex;
    align-items: center;
    padding: 14px 20px;
    border-radius: var(--radius-md);
    margin-bottom: 24px;
    font-size: 14px;
}
.alert-error {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #991b1b;
}

/* 切换标签 */
.recharge-tabs {
    display: flex;
    margin-bottom: 28px;
    background: var(--bg-secondary);
    border-radius: var(--radius-lg);
    padding: 4px;
}
.recharge-tab {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 12px 16px;
    font-size: 15px;
    font-weight: 500;
    color: var(--text-secondary);
    cursor: pointer;
    border-radius: var(--radius-md);
    transition: all 0.2s;
}
.recharge-tab:hover {
    color: var(--primary-color);
}
.recharge-tab.active {
    background: var(--primary-color);
    color: white;
}

/* 充值卡片 */
.recharge-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 28px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.section-title {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 20px;
}

/* 金额选项 */
.amount-options {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    margin-bottom: 28px;
}
.amount-option {
    text-align: center;
    padding: 14px 8px;
    border: 2px solid var(--border-color);
    border-radius: var(--radius-md);
    cursor: pointer;
    transition: all 0.2s;
    font-weight: 500;
}
.amount-option:hover {
    border-color: var(--primary-color);
}
.amount-option.selected {
    background: var(--primary-color);
    border-color: var(--primary-color);
    color: white;
}
.amount-option .currency {
    font-size: 14px;
}
.amount-option .amount {
    font-size: 20px;
    font-weight: 700;
}
.amount-option.custom {
    padding: 0;
    overflow: hidden;
}
.amount-option.custom input {
    width: 100%;
    height: 100%;
    padding: 14px 8px;
    border: none;
    text-align: center;
    background: transparent;
    outline: none;
    font-size: 15px;
}

/* 支付方式 */
.payment-section {
    margin-bottom: 28px;
}
.payment-methods {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
}
.payment-method {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    padding: 12px 16px;
    border: 2px solid var(--border-color);
    border-radius: var(--radius-md);
    transition: all 0.2s;
}
.payment-method:hover {
    border-color: var(--primary-color);
}
.payment-method:has(input:checked) {
    border-color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.payment-method input {
    accent-color: var(--primary-color);
    width: 18px;
    height: 18px;
}
.method-name {
    font-weight: 500;
    color: var(--text-primary);
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 14px 24px;
    border-radius: var(--radius-md);
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
}
.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-block {
    width: 100%;
}

/* 卡密充值 */
.card-tip {
    text-align: center;
    color: var(--text-secondary);
    margin-bottom: 20px;
    font-size: 14px;
}
.card-input-wrapper {
    position: relative;
    margin-bottom: 20px;
}
.card-input-icon {
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
}
.card-input-wrapper input {
    width: 100%;
    padding: 14px 16px 14px 48px;
    border: 2px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 15px;
    text-align: center;
    letter-spacing: 2px;
    transition: all 0.2s;
}
.card-input-wrapper input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.card-result {
    margin-bottom: 20px;
    padding: 14px;
    border-radius: var(--radius-md);
    text-align: center;
    font-weight: 500;
}
.recharge-tip {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
    font-size: 13px;
    color: var(--text-secondary);
}

/* 响应式 */
@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .balance-display {
        width: 100%;
        justify-content: space-between;
    }
    .amount-options {
        grid-template-columns: repeat(2, 1fr);
    }
    .payment-methods {
        flex-direction: column;
    }
    .recharge-card {
        padding: 20px;
    }
}
</style>

<script>
// 切换充值方式
document.querySelectorAll('.recharge-tab').forEach(tab => {
    tab.addEventListener('click', function() {
        const method = this.dataset.method;
        window.history.pushState({}, '', '?method=' + method);
        document.querySelectorAll('.recharge-tab').forEach(t => {
            t.classList.remove('active');
        });
        this.classList.add('active');
        document.getElementById('onlinePanel').style.display = method === 'online' ? 'block' : 'none';
        document.getElementById('cardPanel').style.display = method === 'card' ? 'block' : 'none';
    });
});

// ========== 在线支付代码 ==========
document.addEventListener('DOMContentLoaded', function() {
    const options = document.querySelectorAll('.amount-option:not(.custom)');
    const customInput = document.getElementById('custom_amount');
    const selectedAmount = document.getElementById('selected_amount');
    const rechargeForm = document.getElementById('rechargeForm');
    
    options.forEach(opt => {
        opt.addEventListener('click', function() {
            options.forEach(o => o.classList.remove('selected'));
            this.classList.add('selected');
            selectedAmount.value = this.dataset.amount;
            if (customInput) customInput.value = '';
        });
    });
    
    if (customInput) {
        customInput.addEventListener('input', function() {
            options.forEach(o => o.classList.remove('selected'));
            let val = parseFloat(this.value);
            if (!isNaN(val) && val > 0) {
                selectedAmount.value = val;
            } else {
                selectedAmount.value = '';
            }
        });
    }
    
    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(() => {
                            window.location.href = '/admin.php?page=balance_log';
                        }, 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="/assets/svg/wxpay.svg" 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);
    }
    
    function checkPendingOrder() {
        const pendingOrder = localStorage.getItem('pending_order');
        const pendingMethod = localStorage.getItem('pending_method');
        if (pendingOrder && pendingMethod) {
            fetch('/api/check_order.php?order_no=' + encodeURIComponent(pendingOrder))
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'paid') {
                        localStorage.removeItem('pending_order');
                        localStorage.removeItem('pending_method');
                        window.showToast && window.showToast('支付成功！', 'success');
                        setTimeout(() => {
                            window.location.href = '/admin.php?page=balance_log';
                        }, 1500);
                    } else {
                        if (confirm('检测到有未完成的订单，是否继续等待支付？')) {
                            fetch('/api/get_order_amount.php?order_no=' + encodeURIComponent(pendingOrder))
                                .then(res => res.json())
                                .then(orderData => {
                                    const amount = orderData.amount || 0;
                                    if (amount <= 0) {
                                        window.showToast && window.showToast('获取订单金额失败', 'error');
                                        localStorage.removeItem('pending_order');
                                        localStorage.removeItem('pending_method');
                                        return;
                                    }
                                    
                                    const isAlipay = pendingMethod === 'alipay';
                                    const bgColor = isAlipay ? 'linear-gradient(135deg, #1677FF, #0d5cb6)' : 'linear-gradient(135deg, #07C160, #059669)';
                                    const title = isAlipay ? '支付宝扫码支付' : '微信扫码支付';
                                    const btnColor = isAlipay ? '#1677FF' : '#07C160';
                                    
                                    const iconHtml = isAlipay 
                                        ? '<img src="/assets/svg/alipay.svg" style="width: 32px; height: 32px;" alt="">'
                                        : '<img src="/assets/svg/wxpay.svg" 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>订单号: ${pendingOrder}</p>
                                            <p>金额: ¥${parseFloat(amount).toFixed(2)}</p>
                                            <div id="qrcode-container" style="margin:20px auto;width:200px;height:200px;"></div>
                                            <p>请完成支付...</p>
                                            <button id="cancelWait" style="margin-top:20px;padding:10px 25px;background:${btnColor};color:white;border:none;border-radius:30px;cursor:pointer;">取消</button>
                                        </div>
                                    `;
                                    document.body.appendChild(modalOverlay);
                                    
                                    fetch('/modules/payment/api.php?order_no=' + encodeURIComponent(pendingOrder) + 
                                          '&amount=' + encodeURIComponent(amount) + 
                                          '&type=' + encodeURIComponent(pendingMethod) + 
                                          '&name=' + encodeURIComponent('账户充值'))
                                        .then(res => res.json())
                                        .then(payData => {
                                            if (payData && payData.qrcode) {
                                                const container = document.getElementById('qrcode-container');
                                                if (container) {
                                                    container.innerHTML = '';
                                                    new QRCode(container, {
                                                        text: payData.qrcode,
                                                        width: 200,
                                                        height: 200
                                                    });
                                                }
                                            } else {
                                                window.showToast && window.showToast(payData?.msg || '获取二维码失败', 'error');
                                                modalOverlay.remove();
                                                localStorage.removeItem('pending_order');
                                                localStorage.removeItem('pending_method');
                                            }
                                        })
                                        .catch(error => {
                                            console.error('获取二维码错误:', error);
                                            window.showToast && window.showToast('网络错误，请重新下单', 'error');
                                            modalOverlay.remove();
                                            localStorage.removeItem('pending_order');
                                            localStorage.removeItem('pending_method');
                                        });
                                    
                                    document.getElementById('cancelWait').onclick = () => {
                                        modalOverlay.remove();
                                        localStorage.removeItem('pending_order');
                                        localStorage.removeItem('pending_method');
                                    };
                                    startPolling(pendingOrder, modalOverlay);
                                })
                                .catch(error => {
                                    console.error('获取订单金额错误:', error);
                                    window.showToast && window.showToast('获取订单信息失败', 'error');
                                    localStorage.removeItem('pending_order');
                                    localStorage.removeItem('pending_method');
                                });
                        } else {
                            localStorage.removeItem('pending_order');
                            localStorage.removeItem('pending_method');
                        }
                    }
                });
        }
    }
    
    if (rechargeForm) {
        rechargeForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const amount = selectedAmount.value;
            const paymentMethod = document.querySelector('input[name="payment_method"]:checked').value;
            
            if (!amount || amount <= 0) {
                window.showToast && window.showToast('请选择或输入充值金额', 'error');
                return;
            }
            
            fetch('/modules/user/recharge.php?action=create_order', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `amount=${amount}&payment_method=${paymentMethod}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const orderNo = data.order_no;
                    localStorage.setItem('pending_order', orderNo);
                    localStorage.setItem('pending_method', paymentMethod);
                    
                    const payUrl = '/modules/payment/api.php?order_no=' + encodeURIComponent(orderNo) + 
                                   '&amount=' + encodeURIComponent(amount) + 
                                   '&type=' + encodeURIComponent(paymentMethod) + 
                                   '&name=' + encodeURIComponent('账户充值');
                    
                    fetch(payUrl)
                        .then(res => res.json())
                        .then(payData => {
                            if (payData.code == 1 && payData.qrcode) {
                                showPaymentModal(paymentMethod, amount, payData.qrcode, orderNo);
                            } else {
                                window.showToast && window.showToast(payData.msg || '获取支付信息失败', 'error');
                            }
                        })
                        .catch(error => {
                            console.error('支付请求错误:', error);
                            window.showToast && window.showToast('网络错误', 'error');
                        });
                } else {
                    window.showToast && window.showToast(data.message || '创建订单失败', 'error');
                }
            })
            .catch(error => {
                console.error('错误:', error);
                window.showToast && window.showToast('网络错误', 'error');
            });
        });
    }
    
    checkPendingOrder();
    
    // ========== 卡密充值 ==========
    const cardRechargeBtn = document.getElementById('cardRechargeBtn');
    if (cardRechargeBtn) {
        cardRechargeBtn.addEventListener('click', async function() {
            const cardCode = document.getElementById('card_code').value.trim();
            const resultDiv = document.getElementById('card_result');
            
            if (!cardCode) {
                resultDiv.style.display = 'block';
                resultDiv.style.background = '#fef2f2';
                resultDiv.style.color = '#ef4444';
                resultDiv.innerHTML = '<img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="16" height="16" style="margin-right: 6px;" alt="">请输入卡密';
                return;
            }
            
            this.disabled = true;
            this.innerHTML = '<span class="loading-spinner"></span> 充值中...';
            
            try {
                const response = await fetch('/modules/user/recharge.php?action=card_recharge', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'card_code=' + encodeURIComponent(cardCode)
                });
                const data = await response.json();
                
                resultDiv.style.display = 'block';
                if (data.success) {
                    resultDiv.style.background = '#d1fae5';
                    resultDiv.style.color = '#065f46';
                    resultDiv.innerHTML = '<img src="https://api.iconify.design/mdi:check-circle.svg?color=%23065f46" width="16" height="16" style="margin-right: 6px;" alt="">' + data.message;
                    setTimeout(() => location.reload(), 2000);
                } else {
                    resultDiv.style.background = '#fef2f2';
                    resultDiv.style.color = '#991b1b';
                    resultDiv.innerHTML = '<img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23991b1b" width="16" height="16" style="margin-right: 6px;" alt="">' + data.message;
                }
            } catch (error) {
                resultDiv.style.display = 'block';
                resultDiv.style.background = '#fef2f2';
                resultDiv.style.color = '#991b1b';
                resultDiv.innerHTML = '<img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23991b1b" width="16" height="16" style="margin-right: 6px;" alt="">网络错误，请重试';
            } finally {
                this.disabled = false;
                this.innerHTML = '<img src="https://api.iconify.design/mdi:check-circle.svg?color=white" width="18" height="18" style="margin-right: 8px;" alt="">立即充值';
            }
        });
    }
});

// 加载动画样式
const style = document.createElement('style');
style.textContent = `
    .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;
        margin-right: 8px;
    }
    @keyframes spin {
        to { transform: rotate(360deg); }
    }
`;
document.head.appendChild(style);
</script>