<?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');
    
    $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;
    }
    
    // ========== Session 锁防止重复提交 ==========
    $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();
    // ========== Session 锁结束 ==========
    
    // ========== 检查是否已经拥有有效会员 ==========
    $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 {
        // 使用 FOR UPDATE 锁定用户行，防止并发
        $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 = $db->fetchOne("SELECT * FROM users WHERE id = $user_id");
        if ($user && !empty($user['email']) && ($user['email_notify'] ?? 1)) {
            sendConsumeNotification($user, $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']}");
            
            // 计算返利（10%）
            $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>购买会员</h2>
        <p>升级会员享受更多折扣和权益</p>
    </div>
    
    <div class="current-membership">
        <h3>当前会员状态</h3>
        <div class="membership-card">
            <div class="membership-level">
                <span class="level-badge"><?php echo htmlspecialchars($current_purchase['name'] ?? '普通会员'); ?></span>
                <?php if ($current_purchase && $current_purchase['discount'] < 100): ?>
                    <span class="discount-badge"><?php echo $current_purchase['discount']; ?>折优惠</span>
                <?php endif; ?>
            </div>
            <?php if ($current_purchase && $current_purchase['expire_date']): ?>
                <p class="expire-info">有效期至：<?php echo $current_purchase['expire_date']; ?></p>
            <?php else: ?>
                <p class="expire-info">永久会员</p>
            <?php endif; ?>
        </div>
    </div><div class="current-membership">
        <h3>公告</h3>
        <div class="membership-card">
            <div class="membership-level">
                <p>因系统原因，使用余额购买会员会重复扣费，购买后可找客服索要卡密，返还退款。或者选择在线支付。</p>
            </div>
        </div>
    </div>
    
    <div class="groups-section">
        <h3>选择会员套餐</h3>
        <div class="groups-grid">
            <?php foreach ($groups as $group): ?>
                <div class="group-card">
                    <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">🎁 购买折扣：<?php echo $group['discount']; ?>折</div>
                        <div class="feature">⏰ 有效期：<?php echo $group['duration_days'] ? $group['duration_days'] . '天' : '永久'; ?></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']; ?>">
                            立即购买
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- 购买确认弹窗 -->
<div id="buyModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 450px;">
        <div class="modal-header">
            <h3>确认购买会员</h3>
            <span class="close">&times;</span>
        </div>
        <div class="modal-body">
            <p>会员套餐：<strong id="modal_group_name"></strong></p>
            <p>购买金额：<strong id="modal_price" style="color: var(--primary-color); font-size: 20px;"></strong></p>
            <p>支付方式：</p>
            <div class="payment-methods">
                <label class="payment-method">
                    <input type="radio" name="payment_method" value="balance" checked> 
                    <span>余额支付 (¥<?php echo number_format($user['balance'], 2); ?>)</span>
                </label>
                <?php foreach ($payment_methods as $method): ?>
                    <label class="payment-method">
                        <input type="radio" name="payment_method" value="<?php echo $method['value']; ?>"> 
                        <span><?php echo htmlspecialchars($method['name']); ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
            <?php if ($user['balance'] < 1): ?>
                <p class="balance-warning">⚠️ 余额不足，请先充值或选择在线支付</p>
            <?php endif; ?>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary cancel-btn">取消</button>
            <button class="btn btn-primary confirm-btn">确认购买</button>
        </div>
    </div>
</div>

<style>
.buy-group-container .page-header {
    margin-bottom: 24px;
}
.buy-group-container .page-header h2 {
    margin-bottom: 8px;
}
.buy-group-container .page-header p {
    color: var(--text-secondary);
}
.current-membership {
    margin-bottom: 30px;
}
.current-membership h3 {
    margin-bottom: 12px;
    font-size: 16px;
}
.membership-card {
    background: var(--primary-light);
    border-radius: var(--radius-md);
    padding: 20px;
    border: 1px solid var(--primary-color);
}
.membership-level {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
}
.level-badge {
    font-size: 18px;
    font-weight: bold;
    color: var(--primary-color);
}
.discount-badge {
    background: var(--primary-color);
    color: white;
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 12px;
}
.expire-info {
    color: var(--text-secondary);
    font-size: 13px;
}
.groups-section h3 {
    margin-bottom: 20px;
    font-size: 16px;
}
.groups-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
}
.group-card {
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-md);
    padding: 24px;
    text-align: center;
    transition: transform 0.2s, box-shadow 0.2s;
}
.group-card:hover {
    transform: translateY(-5px);
    box-shadow: var(--shadow-lg);
}
.group-header {
    margin-bottom: 16px;
}
.group-header h3 {
    font-size: 22px;
    margin-bottom: 8px;
}
.price {
    font-size: 28px;
    font-weight: bold;
    color: var(--primary-color);
}
.group-desc {
    color: var(--text-secondary);
    margin-bottom: 20px;
}
.group-features {
    text-align: left;
    margin-bottom: 24px;
    padding: 16px;
    background: var(--bg-secondary);
    border-radius: var(--radius-sm);
}
.feature {
    padding: 5px 0;
}
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    width: 90%;
    max-width: 450px;
}
.modal-header {
    padding: 15px 20px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-body {
    padding: 20px;
}
.modal-footer {
    padding: 15px 20px;
    border-top: 1px solid var(--border-color);
    display: flex;
    gap: 10px;
    justify-content: flex-end;
}
.close {
    cursor: pointer;
    font-size: 24px;
}
.payment-methods {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin: 10px 0;
}
.payment-method {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    padding: 8px 12px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    transition: all 0.2s;
}
.payment-method:hover {
    border-color: var(--primary-color);
}
.payment-method input {
    margin: 0;
}
.balance-warning {
    margin-top: 10px;
    font-size: 12px;
    color: var(--warning-color);
}
</style>

<script>
// 防重复提交标志
let isProcessing = false;

// 轮询函数
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=orders';
                    }, 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 ? '支付宝' : '微信';
    
    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 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;
    
    console.log('找到会员按钮数量:', buyBtns.length);
    
    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';
        console.log('显示弹窗:', groupName, price);
    }
    
    buyBtns.forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            if (isProcessing) {
                window.showToast('请勿重复点击', 'warning');
                return;
            }
            console.log('点击购买按钮:', this.dataset.id, this.dataset.name);
            showModal(this.dataset.id, this.dataset.name, this.dataset.price);
        });
    });
    
    document.querySelectorAll('.close, .cancel-btn').forEach(el => {
        el.addEventListener('click', 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('正在处理中，请稍后...', 'warning');
            return;
        }
        
        console.log('确认购买:', currentGroup.id, paymentMethod);
        
        // 立即禁用按钮，防止重复点击
        isProcessing = true;
        const confirmBtn = this;
        const originalText = confirmBtn.innerHTML;
        confirmBtn.disabled = true;
        confirmBtn.innerHTML = '处理中...';
        
        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('购买成功', 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    window.showToast(data.message || '购买失败', 'error');
                    isProcessing = false;
                    confirmBtn.disabled = false;
                    confirmBtn.innerHTML = originalText;
                }
                closeModal();
            })
            .catch(error => {
                console.error('错误:', error);
                window.showToast('网络错误', 'error');
                isProcessing = false;
                confirmBtn.disabled = false;
                confirmBtn.innerHTML = originalText;
                closeModal();
            });
        } else {
            // 在线支付 - 创建订单
            console.log('开始创建在线支付订单...');
            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 => {
                console.log('创建订单响应:', data);
                if (data.success) {
                    console.log('订单创建成功，开始支付:', data.order_no, data.amount);
                    
                    // 保存订单信息和支付方式
                    localStorage.setItem('pending_order', data.order_no);
                    localStorage.setItem('pending_method', paymentMethod);
                    
                    // 直接调用支付 API
                    const payUrl = '/modules/payment/api.php?order_no=' + encodeURIComponent(data.order_no) + 
                                   '&amount=' + encodeURIComponent(data.amount) + 
                                   '&type=' + encodeURIComponent(paymentMethod) + 
                                   '&name=' + encodeURIComponent(data.name);
                    
                    console.log('支付URL:', payUrl);
                    
                    fetch(payUrl)
                        .then(response => response.json())
                        .then(payData => {
                            console.log('支付响应:', 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(payData.msg || '获取支付信息失败', 'error');
                            }
                            isProcessing = false;
                            confirmBtn.disabled = false;
                            confirmBtn.innerHTML = originalText;
                        })
                        .catch(error => {
                            console.error('支付请求错误:', error);
                            window.showToast('网络错误: ' + error.message, 'error');
                            isProcessing = false;
                            confirmBtn.disabled = false;
                            confirmBtn.innerHTML = originalText;
                        });
                } else {
                    window.showToast(data.message || '创建订单失败', 'error');
                    isProcessing = false;
                    confirmBtn.disabled = false;
                    confirmBtn.innerHTML = originalText;
                }
                closeModal();
            })
            .catch(error => {
                console.error('错误:', error);
                window.showToast('网络错误', 'error');
                isProcessing = false;
                confirmBtn.disabled = false;
                confirmBtn.innerHTML = originalText;
                closeModal();
            });
        }
    });
    
    modal.addEventListener('click', function(e) {
        if (e.target === modal) closeModal();
    });
});
</script>