<?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');
    
    $group_id = intval($_POST['group_id'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? 'alipay';
    
    $group = $db->fetchOne("SELECT * FROM user_groups WHERE id = $group_id AND status = 1 AND price > 0");
    if (!$group) {
        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, item_id, amount, status, expire_at) VALUES ('$order_no', $user_id, 'group', $group_id, {$group['price']}, 'pending', '$expire_at')");    
    echo json_encode(['success' => true, 'order_no' => $order_no, 'amount' => $group['price'], 'name' => $group['name']]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'purchase') {
    header('Content-Type: application/json');
    
    $group_id = intval($_POST['group_id'] ?? 0);
    
    $group = $db->fetchOne("SELECT * FROM user_groups WHERE id = $group_id AND status = 1 AND price > 0");
    if (!$group) {
        echo json_encode(['success' => false, 'message' => '会员套餐不存在']);
        exit;
    }
    
    $lock_key = "purchase_lock_{$user_id}_{$group_id}";
    if (isset($_SESSION[$lock_key]) && $_SESSION[$lock_key] > time() - 10) {
        echo json_encode(['success' => false, 'message' => '操作过于频繁，请稍后再试']);
        exit;
    }
    $_SESSION[$lock_key] = time();
    
    $existing_purchase = $db->fetchOne("SELECT id, expire_date FROM user_group_purchases WHERE user_id = $user_id AND group_id = $group_id");
    $is_expired = false;
    if ($existing_purchase) {
        if ($existing_purchase['expire_date'] && strtotime($existing_purchase['expire_date']) < time()) {
            $is_expired = true;
        } else {
            echo json_encode(['success' => false, 'message' => '您已拥有该会员，无需重复购买']);
            exit;
        }
    }
    
    $db->query("START TRANSACTION");
    
    try {
        $user_check = $db->fetchOne("SELECT balance FROM users WHERE id = $user_id FOR UPDATE");
        
        if ($user_check['balance'] < $group['price']) {
            throw new Exception('余额不足');
        }
        
        $db->query("UPDATE users SET balance = balance - {$group['price']} WHERE id = $user_id");
        updateUserBalance($user_id, -$group['price'], "购买会员：{$group['name']}");
        
        $expire_date = $group['duration_days'] > 0 ? date('Y-m-d H:i:s', strtotime("+{$group['duration_days']} days")) : null;
        
        if ($existing_purchase && $is_expired) {
            if ($expire_date) {
                $db->query("UPDATE user_group_purchases SET expire_date = '$expire_date' WHERE id = {$existing_purchase['id']}");
            } else {
                $db->query("UPDATE user_group_purchases SET expire_date = NULL WHERE id = {$existing_purchase['id']}");
            }
        } elseif ($existing_purchase) {
            throw new Exception('您已拥有该会员');
        } else {
            $db->query("INSERT INTO user_group_purchases (user_id, group_id, expire_date) VALUES ($user_id, $group_id, " . ($expire_date ? "'$expire_date'" : "NULL") . ")");
        }
        
        $db->query("UPDATE users SET group_id = $group_id WHERE id = $user_id");
        
        $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, $group['name'], $group['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 = $group['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;
}

$groups = $db->fetchAll("SELECT * FROM user_groups WHERE status = 1 AND price > 0 ORDER BY price ASC");
$payment_methods = getEnabledPaymentMethods();

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

<div class="buy-group-container">
    <!-- 页面头部 -->
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:account-group.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            购买会员
        </h2>
        <p class="page-desc">升级会员享受更多折扣和权益</p>
    </div>
    
    <!-- 当前会员状态 -->
    <div class="current-section">
        <div class="section-title">
            <img src="https://api.iconify.design/mdi:account-check.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
            当前会员状态
        </div>
        <div class="membership-card">
            <div class="membership-level">
                <span class="level-badge">
                    <img src="https://api.iconify.design/mdi:shield-account.svg?color=%23667eea" width="18" height="18" style="margin-right: 6px;" alt="">
                    <?php echo htmlspecialchars($current_purchase['name'] ?? '普通会员'); ?>
                </span>
                <?php if ($current_purchase && $current_purchase['discount'] < 100): ?>
                    <span class="discount-badge">
                        <img src="https://api.iconify.design/mdi:percent.svg?color=white" width="12" height="12" alt="">
                        <?php echo $current_purchase['discount']; ?>折优惠
                    </span>
                <?php endif; ?>
            </div>
            <?php if ($current_purchase && $current_purchase['expire_date']): ?>
                <p class="expire-info">
                    <img src="https://api.iconify.design/mdi:calendar.svg?color=%236b7280" width="14" height="14" style="margin-right: 6px;" alt="">
                    有效期至：<?php echo $current_purchase['expire_date']; ?>
                </p>
            <?php else: ?>
                <p class="expire-info">
                    <img src="https://api.iconify.design/mdi:infinity.svg?color=%2310b981" width="14" height="14" style="margin-right: 6px;" alt="">
                    永久会员
                </p>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- 公告 -->
    <div class="current-section">
        <div class="section-title">
            <img src="https://api.iconify.design/mdi:bullhorn.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
            公告
        </div>
        <div class="announcement-card">
            <img src="https://api.iconify.design/mdi:information.svg?color=%23f59e0b" width="20" height="20" style="margin-right: 10px;" alt="">
            <span>因系统原因，使用余额购买会员会重复扣费，购买后可找客服索要卡密，返还退款。或者选择在线支付。</span>
        </div>
    </div>
    
    <!-- 会员套餐 -->
    <div class="groups-section">
        <div class="section-title">
            <img src="https://api.iconify.design/mdi:package-variant.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
            选择会员套餐
        </div>
        <div class="groups-grid">
            <?php foreach ($groups as $group): ?>
                <div class="group-card">
                    <div class="group-icon">
                        <img src="https://api.iconify.design/mdi:account-group.svg?color=%23667eea" width="36" height="36" alt="">
                    </div>
                    <div class="group-header">
                        <h3><?php echo htmlspecialchars($group['name']); ?></h3>
                        <div class="price">¥<?php echo number_format($group['price'], 2); ?></div>
                    </div>
                    <p class="group-desc"><?php echo htmlspecialchars($group['description'] ?: '暂无描述'); ?></p>
                    <div class="group-features">
                        <div class="feature">
                            <img src="https://api.iconify.design/mdi:tag.svg?color=%23667eea" width="16" height="16" alt="">
                            <span>购买折扣：<strong><?php echo $group['discount']; ?>折</strong></span>
                        </div>
                        <div class="feature">
                            <img src="https://api.iconify.design/mdi:calendar-clock.svg?color=%23f59e0b" width="16" height="16" alt="">
                            <span>有效期：<strong><?php echo $group['duration_days'] ? $group['duration_days'] . '天' : '永久'; ?></strong></span>
                        </div>
                    </div>
                    <div class="group-footer">
                        <button class="btn btn-primary buy-group-btn" data-id="<?php echo $group['id']; ?>" data-name="<?php echo htmlspecialchars($group['name']); ?>" data-price="<?php echo $group['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>
    </div>
</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_group_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-group-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;
}

/* 区块 */
.current-section {
    margin-bottom: 24px;
}
.section-title {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 14px;
}

/* 会员卡片 */
.membership-card {
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.08) 0%, rgba(102, 126, 234, 0.02) 100%);
    border-radius: var(--radius-lg);
    padding: 20px 24px;
    border: 1px solid rgba(102, 126, 234, 0.2);
}
.membership-level {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 10px;
    flex-wrap: wrap;
}
.level-badge {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 700;
    color: var(--primary-color);
}
.discount-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    background: var(--primary-color);
    color: white;
    padding: 4px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
}
.expire-info {
    display: flex;
    align-items: center;
    color: var(--text-secondary);
    font-size: 14px;
    margin: 0;
}

/* 公告卡片 */
.announcement-card {
    display: flex;
    align-items: center;
    background: #fef3c7;
    border-radius: var(--radius-lg);
    padding: 16px 20px;
    border: 1px solid rgba(245, 158, 11, 0.2);
    color: #92400e;
    font-size: 14px;
}

/* 套餐网格 */
.groups-section {
    margin-top: 32px;
}
.groups-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 24px;
}
.group-card {
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-lg);
    padding: 28px 24px;
    text-align: center;
    transition: all 0.3s ease;
}
.group-card:hover {
    transform: translateY(-5px);
    box-shadow: var(--shadow-lg);
    border-color: var(--primary-color);
}
.group-icon {
    width: 64px;
    height: 64px;
    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: 0 auto 16px;
}
.group-header {
    margin-bottom: 16px;
}
.group-header h3 {
    font-size: 22px;
    font-weight: 600;
    margin-bottom: 8px;
    color: var(--text-primary);
}
.price {
    font-size: 32px;
    font-weight: 700;
    color: var(--primary-color);
}
.group-desc {
    color: var(--text-secondary);
    margin-bottom: 20px;
    font-size: 14px;
    min-height: 44px;
}
.group-features {
    text-align: left;
    margin-bottom: 24px;
    padding: 16px;
    background: var(--bg-secondary);
    border-radius: var(--radius-md);
}
.feature {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 8px 0;
    font-size: 14px;
    color: var(--text-secondary);
}
.feature strong {
    color: var(--text-primary);
}
.group-footer .btn {
    width: 100%;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 12px 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);
}

/* 弹窗 */
.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;
}

/* 响应式 */
@media (max-width: 768px) {
    .groups-grid {
        grid-template-columns: 1fr;
    }
    .page-desc {
        margin-left: 0;
    }
    .membership-level {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }
}
</style>

<script>
let isProcessing = false;

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=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="/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);
}

document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('buyModal');
    const buyBtns = document.querySelectorAll('.buy-group-btn');
    let currentGroup = null;
    
    function closeModal() {
        modal.style.display = 'none';
    }
    
    function showModal(groupId, groupName, price) {
        currentGroup = { id: groupId, name: groupName, price: price };
        document.getElementById('modal_group_name').innerText = groupName;
        document.getElementById('modal_price').innerText = '¥' + parseFloat(price).toFixed(2);
        modal.style.display = 'flex';
    }
    
    buyBtns.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() {
        const paymentMethod = document.querySelector('input[name="payment_method"]:checked')?.value;
        if (!currentGroup) return;
        
        if (isProcessing) {
            window.showToast && window.showToast('正在处理中，请稍后...', 'warning');
            return;
        }
        
        isProcessing = true;
        const confirmBtn = this;
        const originalHtml = confirmBtn.innerHTML;
        confirmBtn.disabled = true;
        confirmBtn.innerHTML = '<span class="loading-spinner"></span> 处理中...';
        
        if (paymentMethod === 'balance') {
            fetch('/modules/user/buy_group.php?action=purchase', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `group_id=${currentGroup.id}&_t=${Date.now()}`
            })
            .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');
                    isProcessing = false;
                    confirmBtn.disabled = false;
                    confirmBtn.innerHTML = originalHtml;
                }
                closeModal();
            })
            .catch(error => {
                console.error('错误:', error);
                window.showToast && window.showToast('网络错误', 'error');
                isProcessing = false;
                confirmBtn.disabled = false;
                confirmBtn.innerHTML = originalHtml;
                closeModal();
            });
        } else {
            fetch('/modules/user/buy_group.php?action=create_order', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `group_id=${currentGroup.id}&payment_method=${paymentMethod}&_t=${Date.now()}`
            })
            .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(response => response.json())
                        .then(payData => {
                            if (payData.code == 1 && payData.qrcode) {
                                showPaymentModal(paymentMethod, data.amount, payData.qrcode, data.order_no);
                            } else if (payData.payurl) {
                                window.location.href = payData.payurl;
                            } else if (payData.urlscheme) {
                                window.location.href = payData.urlscheme;
                            } else {
                                window.showToast && window.showToast(payData.msg || '获取支付信息失败', 'error');
                            }
                            isProcessing = false;
                            confirmBtn.disabled = false;
                            confirmBtn.innerHTML = originalHtml;
                        })
                        .catch(error => {
                            console.error('支付请求错误:', error);
                            window.showToast && window.showToast('网络错误', 'error');
                            isProcessing = false;
                            confirmBtn.disabled = false;
                            confirmBtn.innerHTML = originalHtml;
                        });
                } else {
                    window.showToast && window.showToast(data.message || '创建订单失败', 'error');
                    isProcessing = false;
                    confirmBtn.disabled = false;
                    confirmBtn.innerHTML = originalHtml;
                }
                closeModal();
            })
            .catch(error => {
                console.error('错误:', error);
                window.showToast && window.showToast('网络错误', 'error');
                isProcessing = false;
                confirmBtn.disabled = false;
                confirmBtn.innerHTML = originalHtml;
                closeModal();
            });
        }
    });
});

// 加载动画样式
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>