<?php
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;
}

// ========== 处理卡密充值 AJAX ==========
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'; // online=在线支付, card=卡密充值
?>

<div class="recharge-container">
    <div class="page-header">
        <h2>余额充值</h2>
        <p>当前余额：<strong style="color: var(--primary-color); font-size: 24px;">¥<?php echo number_format($user['balance'], 2); ?></strong></p>
    </div>
    
    <?php if ($error): ?>
        <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>
    
    <!-- 切换标签 -->
    <div class="recharge-tabs" style="display: flex; margin-bottom: 30px; border-bottom: 1px solid var(--border-color); max-width: 500px; margin-left: auto; margin-right: auto;">
        <div class="recharge-tab <?php echo $recharge_method == 'online' ? 'active' : ''; ?>" data-method="online" style="flex: 1; text-align: center; padding: 12px; cursor: pointer; color: var(--text-secondary); border-bottom: 2px solid <?php echo $recharge_method == 'online' ? 'var(--primary-color)' : 'transparent'; ?>; <?php echo $recharge_method == 'online' ? 'color: var(--primary-color);' : ''; ?>">
            💳 在线支付
        </div>
        <div class="recharge-tab <?php echo $recharge_method == 'card' ? 'active' : ''; ?>" data-method="card" style="flex: 1; text-align: center; padding: 12px; cursor: pointer; color: var(--text-secondary); border-bottom: 2px solid <?php echo $recharge_method == 'card' ? 'var(--primary-color)' : 'transparent'; ?>; <?php echo $recharge_method == 'card' ? 'color: var(--primary-color);' : ''; ?>">
            🎫 卡密充值
        </div>
    </div>
    
    <!-- 在线支付面板 -->
    <div id="onlinePanel" class="recharge-panel" style="display: <?php echo $recharge_method == 'online' ? 'block' : 'none'; ?>;">
        <div class="recharge-card">
            <h3>选择充值金额</h3>
            <div class="amount-options">
                <?php foreach ($recharge_options as $opt): ?>
                    <div class="amount-option" data-amount="<?php echo $opt; ?>">
                        ¥<?php echo $opt; ?>
                    </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">
    <h4>支付方式</h4>
    <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">
                    <?php if ($method['value'] == 'alipay'): ?>
                        <img src="/assets/svg/alipay-ys.svg" style="width: 24px; height: 24px; vertical-align: middle;">
                    <?php else: ?>
                        <img src="/assets/svg/wxpay-ys.svg" style="width: 24px; height: 24px; vertical-align: middle;">
                    <?php endif; ?>
                </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">立即充值</button>
            </form>
        </div>
    </div>
    
    <!-- 卡密充值面板 -->
    <div id="cardPanel" class="recharge-panel" style="display: <?php echo $recharge_method == 'card' ? 'block' : 'none'; ?>;">
        <div class="recharge-card">
            <h3>卡密充值</h3>
            <p style="text-align: center; color: var(--text-secondary); margin-bottom: 20px;">输入卡密直接充值到账户余额</p>
            
            <div style="margin-bottom: 20px;">
                <input type="text" id="card_code" placeholder="请输入卡密（格式：XXXX-XXXX-XXXX-XXXX）" style="width: 100%; padding: 14px; border-radius: 12px; border: 1px solid var(--border-color); background: var(--bg-primary); font-size: 14px; text-align: center;">
            </div>
            
            <div id="card_result" style="margin-bottom: 20px; display: none; padding: 12px; border-radius: 12px; text-align: center;"></div>
            
            <button id="cardRechargeBtn" class="btn btn-primary btn-block">立即充值</button>
            
            <div class="recharge-info" style="margin-top: 20px;">
                <p>💡 提示：卡密由管理员生成，如有问题请联系客服</p>
            </div>
        </div>
    </div>
    
    <div class="recharge-info" style="max-width: 500px; margin: 20px auto 0; text-align: center;">
        <p>📞 如有问题请联系客服</p>
    </div>
</div>

<style>
.recharge-card {
    max-width: 500px;
    margin: 0 auto;
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    padding: 30px;
    border: 1px solid var(--border-color);
}
.recharge-card h3 {
    margin-bottom: 20px;
    text-align: center;
}
.amount-options {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 15px;
    margin-bottom: 30px;
}
.amount-option {
    text-align: center;
    padding: 12px;
    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.custom {
    padding: 0;
    overflow: hidden;
}
.amount-option.custom input {
    width: 100%;
    height: 100%;
    padding: 12px;
    border: none;
    text-align: center;
    background: transparent;
    outline: none;
}
.payment-section {
    margin-bottom: 25px;
}
.payment-section h4 {
    margin-bottom: 12px;
    font-size: 14px;
    color: var(--text-secondary);
}
.payment-methods {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
}
.payment-method {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    padding: 10px 20px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-md);
    transition: all 0.2s;
}
.payment-method:hover {
    border-color: var(--primary-color);
}
.payment-method input {
    margin: 0;
}
.payment-method.selected {
    border-color: var(--primary-color);
    background: var(--primary-light);
}
.method-icon {
    font-size: 18px;
}
.method-name {
    font-weight: 500;
}
.recharge-tab {
    transition: all 0.2s;
}
.recharge-tab:hover {
    color: var(--primary-color);
}
.recharge-info {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
    font-size: 13px;
    color: var(--text-secondary);
}
</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.style.color = 'var(--text-secondary)';
            t.style.borderBottomColor = 'transparent';
        });
        this.style.color = 'var(--primary-color)';
        this.style.borderBottomColor = 'var(--primary-color)';
        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 = '';
            }
        });
    }
    
    // 支付方式选择样式
    const paymentMethods = document.querySelectorAll('.payment-method');
    paymentMethods.forEach(method => {
        const radio = method.querySelector('input[type="radio"]');
        if (radio) {
            radio.addEventListener('change', function() {
                paymentMethods.forEach(m => m.classList.remove('selected'));
                if (this.checked) {
                    method.classList.add('selected');
                }
            });
            if (radio.checked) {
                method.classList.add('selected');
            }
        }
    });
    
    // 轮询函数
    function startPolling(orderNo, modalElement) {
        console.log('开始轮询订单:', orderNo);
        let count = 0;
        const maxAttempts = 60;
        
        const interval = setInterval(() => {
            count++;
            console.log('第' + count + '次查询订单状态');
            
            fetch('/api/check_order.php?order_no=' + encodeURIComponent(orderNo))
                .then(response => response.json())
                .then(data => {
                    console.log('订单状态:', data);
                    if (data.status === 'paid') {
                        clearInterval(interval);
                        localStorage.removeItem('pending_order');
                        localStorage.removeItem('pending_method');
                        if (modalElement && modalElement.parentNode) {
                            modalElement.remove();
                        }
                        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('支付超时，请稍后查看订单状态', 'warning');
                    }
                })
                .catch(error => {
                    console.error('查询订单状态错误:', error);
                });
        }, 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 ? '支付宝' : '微信';
        
        // SVG 图标
        const iconHtml = isAlipay 
            ? '<img src="/assets/svg/alipay.svg" style="width: 32px; height: 32px; vertical-align: middle;">'
            : '<img src="/assets/svg/wxpay.svg" style="width: 32px; height: 32px; vertical-align: middle;">';
        
        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:100%;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) {
        console.log('发现未完成订单:', pendingOrder);
        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('支付成功！', 'success');
                    setTimeout(() => {
                        window.location.href = '/admin.php?page=orders';
                    }, 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('获取订单金额失败', '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; vertical-align: middle;">'
                                    : '<img src="/assets/svg/wxpay.svg" style="width: 32px; height: 32px; vertical-align: middle;">';
                                
                                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.text())
                                    .then(text => {
                                        let payData;
                                        try {
                                            payData = JSON.parse(text);
                                        } catch (e) {
                                            console.error('解析失败:', text);
                                            window.showToast('获取支付信息失败', 'error');
                                            modalOverlay.remove();
                                            localStorage.removeItem('pending_order');
                                            localStorage.removeItem('pending_method');
                                            return;
                                        }
                                        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(payData?.msg || '获取二维码失败', 'error');
                                            modalOverlay.remove();
                                            localStorage.removeItem('pending_order');
                                            localStorage.removeItem('pending_method');
                                        }
                                    })
                                    .catch(error => {
                                        console.error('获取二维码错误:', error);
                                        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('获取订单信息失败', '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) {
                alert('请选择或输入充值金额');
                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 => {
                console.log('创建订单响应:', data);
                if (data.success) {
                    const orderNo = data.order_no;
                    localStorage.setItem('pending_order', orderNo);
                    localStorage.setItem('pending_method', paymentMethod);
                    
                    // 调用支付 API
                    const payUrl = '/modules/payment/api.php?order_no=' + encodeURIComponent(orderNo) + 
                                   '&amount=' + encodeURIComponent(amount) + 
                                   '&type=' + encodeURIComponent(paymentMethod) + 
                                   '&name=' + encodeURIComponent('账户充值');
                    
                    fetch(payUrl)
    .then(res => res.text())
    .then(text => {
        let payData;
        try {
            payData = JSON.parse(text);
        } catch (e) {
            console.error('支付响应解析失败:', text);
            window.showToast('获取支付信息失败', 'error');
            return;
        }
        if (payData.code == 1 && payData.qrcode) {
            showPaymentModal(paymentMethod, amount, payData.qrcode, orderNo);
        } else {
            window.showToast(payData.msg || '获取支付信息失败', 'error');
        }
    })
                        .catch(error => {
                            console.error('支付请求错误:', error);
                            window.showToast('网络错误', 'error');
                        });
                } else {
                    window.showToast(data.message || '创建订单失败', 'error');
                }
            })
            .catch(error => {
                console.error('错误:', error);
                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 = 'rgba(239,68,68,0.1)';
                resultDiv.style.color = '#ef4444';
                resultDiv.innerHTML = '❌ 请输入卡密';
                return;
            }
            
            this.disabled = true;
            this.innerHTML = '充值中...';
            
            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 = 'rgba(16,185,129,0.1)';
                    resultDiv.style.color = '#10b981';
                    resultDiv.innerHTML = '✅ ' + data.message;
                    setTimeout(() => location.reload(), 2000);
                } else {
                    resultDiv.style.background = 'rgba(239,68,68,0.1)';
                    resultDiv.style.color = '#ef4444';
                    resultDiv.innerHTML = '❌ ' + data.message;
                }
            } catch (error) {
                resultDiv.style.display = 'block';
                resultDiv.style.background = 'rgba(239,68,68,0.1)';
                resultDiv.style.color = '#ef4444';
                resultDiv.innerHTML = '❌ 网络错误，请重试';
            } finally {
                this.disabled = false;
                this.innerHTML = '立即充值';
            }
        });
    }
});
</script>