<?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');
    
    $app_id = intval($_POST['app_id'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? 'alipay';
    $is_agent = isset($_POST['is_agent']) ? intval($_POST['is_agent']) : 0;
    
    $app = $db->fetchOne("SELECT * FROM apps WHERE id = $app_id AND status = 1");
    if (!$app) {
        echo json_encode(['success' => false, 'message' => '应用不存在']);
        exit;
    }
    
    // 计算价格（如果有代理价格，使用代理价格）
    if ($is_agent && isset($_SESSION['agent_price']) && $_SESSION['agent_app_id'] == $app_id) {
        $price = $_SESSION['agent_price'];
        $agent_id = $_SESSION['agent_id'];
        
        // 获取代理商产品的折扣设置
        $agent_product = $db->fetchOne("SELECT discount_enabled, discount_type, discount_value, stack_discount 
                                         FROM agent_products WHERE agent_id = $agent_id AND id = $app_id");
        if ($agent_product && $agent_product['discount_enabled']) {
            if ($agent_product['discount_type'] == 'percent') {
                $price = $price * (100 - $agent_product['discount_value']) / 100;
            } else {
                $price = max(0, $price - $agent_product['discount_value']);
            }
            $price = round($price, 2);
        }
    } else {
        $price = getDiscountedPrice($app['price'], $user_id);
        $agent_id = 0;
    }
    
    $order_no = generateOrderNo();
$expire_at = date('Y-m-d H:i:s', strtotime('+30 minutes'));

// 插入订单（如果有代理商，记录代理商信息）
if ($agent_id > 0) {
    // 获取佣金比例
    $agent_app = $db->fetchOne("SELECT commission_rate FROM agent_apps WHERE agent_id = $agent_id AND app_id = $app_id");
    $commission_rate = $agent_app['commission_rate'] ?? 0;
    $agent_commission = $price * $commission_rate / 100;
    
    // 插入代理商订单
    $db->query("INSERT INTO agent_orders (order_no, agent_id, customer_id, app_id, amount, agent_commission, status) 
                VALUES ('$order_no', $agent_id, $user_id, $app_id, $price, $agent_commission, 'pending')");
}

// 插入普通订单（添加过期时间）
$db->query("INSERT INTO orders (order_no, user_id, type, item_id, amount, status, expire_at) VALUES ('$order_no', $user_id, 'app', $app_id, $price, 'pending', '$expire_at')");
    
    echo json_encode(['success' => true, 'order_no' => $order_no, 'amount' => $price, 'name' => $app['name'], 'is_agent' => $agent_id > 0]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'purchase') {
    header('Content-Type: application/json');
    
    // ========== 防重复提交机制 ==========
    $lock_key = "purchase_lock_{$user_id}";
    if (isset($_SESSION[$lock_key]) && $_SESSION[$lock_key] > time() - 5) {
        echo json_encode(['success' => false, 'message' => '操作过于频繁，请稍后再试']);
        exit;
    }
    $_SESSION[$lock_key] = time();
    
    $app_id = intval($_POST['app_id'] ?? 0);
    $is_agent = isset($_POST['is_agent']) ? intval($_POST['is_agent']) : 0;
    
    $app = $db->fetchOne("SELECT * FROM apps WHERE id = $app_id AND status = 1");
    if (!$app) {
        echo json_encode(['success' => false, 'message' => '应用不存在']);
        exit;
    }
    
    // 计算价格
    if ($is_agent && isset($_SESSION['agent_price']) && $_SESSION['agent_app_id'] == $app_id) {
        $price = $_SESSION['agent_price'];
        $agent_id = $_SESSION['agent_id'];
        
        // 获取代理商产品的折扣设置
        $agent_product = $db->fetchOne("SELECT discount_enabled, discount_type, discount_value, stack_discount 
                                         FROM agent_products WHERE agent_id = $agent_id AND id = $app_id");
        if ($agent_product && $agent_product['discount_enabled']) {
            if ($agent_product['discount_type'] == 'percent') {
                $price = $price * (100 - $agent_product['discount_value']) / 100;
            } else {
                $price = max(0, $price - $agent_product['discount_value']);
            }
            $price = round($price, 2);
        }
    } else {
        $price = getDiscountedPrice($app['price'], $user_id);
        $agent_id = 0;
    }
    
    if ($user['balance'] < $price) {
        echo json_encode(['success' => false, 'message' => '余额不足，请先充值']);
        exit;
    }
    
    // ========== 使用事务确保数据一致性 ==========
    $db->query("START TRANSACTION");
    
    try {
        // 再次检查余额（防止并发）
        $check_balance = $db->fetchOne("SELECT balance FROM users WHERE id = $user_id FOR UPDATE");
        if ($check_balance['balance'] < $price) {
            throw new Exception('余额不足');
        }
        
        // 扣款并记录日志（只调用一次，不要重复扣款！）
        updateUserBalance($user_id, -$price, "购买应用：{$app['name']}");
        
        // 生成授权码
        $license_code = generateLicenseCode();
        $expire_date = $app['duration_days'] > 0 ? date('Y-m-d', strtotime("+{$app['duration_days']} days")) : null;
        $app_key = $app['app_key'];
        $db->query("INSERT INTO licenses (license_code, app_key, app_id, user_id, expire_date, used) VALUES ('$license_code', '$app_key', $app_id, $user_id, " . ($expire_date ? "'$expire_date'" : "NULL") . ", 0)");
        
        // 如果有代理商，更新代理商订单状态和佣金
        if ($agent_id > 0) {
            // 获取佣金比例
            $agent_app = $db->fetchOne("SELECT commission_rate FROM agent_apps WHERE agent_id = $agent_id AND app_id = $app_id");
            $commission_rate = $agent_app['commission_rate'] ?? 0;
            $agent_commission = $price * $commission_rate / 100;
            
            // 创建代理商订单
            $order_no = generateOrderNo();
            $db->query("INSERT INTO agent_orders (order_no, agent_id, customer_id, app_id, amount, agent_commission, status, paid_at) 
                        VALUES ('$order_no', $agent_id, $user_id, $app_id, $price, $agent_commission, 'paid', NOW())");
            
            // 更新代理商累计佣金
            $db->query("UPDATE users SET agent_total_commission = agent_total_commission + $agent_commission WHERE id = $agent_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, $app['name'], $price, '余额支付');
}

// ========== 邀请返利（余额支付购买应用） ==========
$invite_record = $db->fetchOne("SELECT * FROM invite_records WHERE invitee_id = $user_id AND status = 0");
if ($invite_record) {
    // 更新邀请记录状态
    $db->query("UPDATE invite_records SET status = 1 WHERE id = {$invite_record['id']}");
    
    // 计算返利（10%）
    $rebate_rate = 10;
    $rebate_amount = $price * $rebate_rate / 100;
    
    if ($rebate_amount > 0) {
        // 添加返利记录
        $db->query("INSERT INTO rebate_records (user_id, from_user_id, order_id, amount, rate) 
                    VALUES ({$invite_record['inviter_id']}, $user_id, 0, $rebate_amount, $rebate_rate)");
        
        // 增加用户返利余额
        $db->query("UPDATE users SET rebate_balance = rebate_balance + $rebate_amount WHERE id = {$invite_record['inviter_id']}");
    }
}
// ========== 邀请返利结束 ==========

echo json_encode(['success' => true, 'message' => '购买成功']);
        
    } catch (Exception $e) {
        $db->query("ROLLBACK");
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

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

// 检查是否有代理价格
$has_agent_price = isset($_SESSION['agent_price']) && isset($_SESSION['agent_app_id']);
$agent_app_id = $has_agent_price ? $_SESSION['agent_app_id'] : 0;
?>

<div class="buy-app-container">
    <div class="page-header">
        <h2>购买应用授权</h2>
        <p>选择您需要授权的应用</p>
    </div>
    
    <!-- 代理提示 -->
    <?php if ($has_agent_price): ?>
        <?php
        $agent_app = $db->fetchOne("SELECT name FROM apps WHERE id = $agent_app_id");
        ?>
        <div class="agent-tip">
            <div class="tip-icon">🤝</div>
            <div class="tip-text">
                您正在通过代理商 <strong><?php echo htmlspecialchars($agent_app['name'] ?? ''); ?></strong> 的推广链接购买，
                享受专属优惠价格！<br>
                <small>购买后佣金将自动结算给代理商</small>
            </div>
            <button class="btn-clear" onclick="clearAgentSession()">清除代理信息</button>
        </div>
    <?php endif; ?>
    
    <div class="apps-grid">
        <?php foreach ($apps as $app): ?>
            <?php 
            // 判断是否有代理价格
            $is_agent_app = ($has_agent_price && $agent_app_id == $app['id']);
            $display_price = $is_agent_app ? $_SESSION['agent_price'] : getDiscountedPrice($app['price'], $user_id);
            $has_discount = $display_price < $app['price'];
            ?>
            <div class="app-card <?php echo $is_agent_app ? 'agent-card' : ''; ?>">
                <div class="app-header">
                    <h3><?php echo htmlspecialchars($app['name']); ?></h3>
                    <div class="price">
                        <?php if ($is_agent_app): ?>
                            <span class="original-price">¥<?php echo number_format($app['price'], 2); ?></span>
                            <span class="agent-price">¥<?php echo number_format($display_price, 2); ?></span>
                            <span class="agent-badge">代理价</span>
                        <?php elseif ($has_discount): ?>
                            <span class="original-price">¥<?php echo number_format($app['price'], 2); ?></span>
                            <span class="discount-price">¥<?php echo number_format($display_price, 2); ?></span>
                        <?php else: ?>
                            <span class="price-amount">¥<?php echo number_format($display_price, 2); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <p class="app-desc"><?php echo htmlspecialchars($app['description'] ?: '暂无描述'); ?></p>
                <div class="app-meta">
                    <span>📅 授权期限：<?php echo $app['duration_days'] ? $app['duration_days'] . '天' : '永久'; ?></span>
                </div>
                <div class="app-footer">
                    <button class="btn btn-primary buy-btn" 
                            data-id="<?php echo $app['id']; ?>" 
                            data-name="<?php echo htmlspecialchars($app['name']); ?>" 
                            data-price="<?php echo $display_price; ?>"
                            data-is-agent="<?php echo $is_agent_app ? 1 : 0; ?>">
                        立即购买
                    </button>
                </div>
            </div>
        <?php endforeach; ?>
    </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_app_name"></strong></p>
            <p>购买金额：<strong id="modal_price" style="color: var(--primary-color); font-size: 20px;"></strong></p>
            <?php if ($has_agent_price): ?>
                <div class="agent-note" style="background: #fef3c7; padding: 8px 12px; border-radius: 8px; margin: 10px 0; font-size: 12px; color: #92400e;">
                    🤝 此订单将通过代理商购买，佣金将自动结算给代理商
                </div>
            <?php endif; ?>
            <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>

<!-- 公告弹窗 -->
<div id="announcementModal" class="announcement-modal" style="display: none;">
    <div class="announcement-modal-content">
        <div class="modal-body">
            <div id="announcementContent"></div>
        </div>
        <div class="announcement-modal-footer">
            <button class="btn btn-primary" id="closeAnnouncementBtn">关闭</button>
            <button class="btn btn-secondary" id="dontShowAgainBtn">不再提示</button>
        </div>
    </div>
</div>

<style>
.announcement-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10001;
}
.announcement-modal-content {
    background: var(--bg-primary);
    border-radius: 20px;
    width: 90%;
    max-width: 500px;
    max-height: 80vh;
    overflow-y: auto;
    box-shadow: var(--shadow-lg);
}
.announcement-modal-footer {
    padding: 16px 24px;
    border-top: 1px solid var(--border-color);
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}
</style>

<script>
function loadAnnouncements(type) {
    fetch(`/api/get_announcements.php?type=${type}`)
        .then(res => res.json())
        .then(data => {
            if (data.success && data.data.length > 0) {
                showAnnouncementModal(data.data[0]);
            }
        });
}

function showAnnouncementModal(announcement) {
    const modal = document.getElementById('announcementModal');
    const content = document.getElementById('announcementContent');
    content.innerHTML = announcement.content;
    modal.style.display = 'flex';
    
    // 记录已读
    fetch('/api/mark_announcement_read.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `id=${announcement.id}`
    });
}

document.getElementById('closeAnnouncementBtn')?.addEventListener('click', () => {
    document.getElementById('announcementModal').style.display = 'none';
});

document.getElementById('dontShowAgainBtn')?.addEventListener('click', () => {
    document.getElementById('announcementModal').style.display = 'none';
});

// 页面加载时获取公告
<?php
$page_type = 'admin';
if ($user['role'] == 'user') {
    $page_type = 'user_dashboard';
}
?>
loadAnnouncements('<?php echo $page_type; ?>');
</script>
<style>
.buy-app-container .page-header {
    margin-bottom: 24px;
}
.buy-app-container .page-header h2 {
    margin-bottom: 8px;
}
.buy-app-container .page-header p {
    color: var(--text-secondary);
}
.apps-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
}
.app-card {
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-md);
    padding: 20px;
    transition: box-shadow 0.2s;
}
.app-card:hover {
    box-shadow: var(--shadow-md);
}
.app-card.agent-card {
    border: 2px solid #f59e0b;
    background: linear-gradient(135deg, var(--bg-primary) 0%, rgba(245, 158, 11, 0.05) 100%);
}
.app-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
}
.app-header h3 {
    font-size: 18px;
    font-weight: 600;
}
.price {
    text-align: right;
}
.original-price {
    text-decoration: line-through;
    font-size: 12px;
    color: var(--text-muted);
    display: block;
}
.discount-price, .price-amount {
    font-size: 20px;
    font-weight: bold;
    color: var(--primary-color);
}
.agent-price {
    font-size: 20px;
    font-weight: bold;
    color: #f59e0b;
}
.agent-badge {
    background: #f59e0b;
    color: white;
    font-size: 10px;
    padding: 2px 6px;
    border-radius: 12px;
    margin-left: 5px;
    display: inline-block;
}
.app-desc {
    color: var(--text-secondary);
    margin-bottom: 12px;
    line-height: 1.5;
}
.app-meta {
    font-size: 13px;
    color: var(--text-muted);
    margin-bottom: 16px;
}
.app-footer {
    padding-top: 12px;
    border-top: 1px solid var(--border-color);
}
.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);
}
.agent-tip {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border-left: 4px solid #f59e0b;
    padding: 12px 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}
.agent-tip .tip-icon {
    font-size: 24px;
}
.agent-tip .tip-text {
    flex: 1;
    color: #92400e;
}
.agent-tip .tip-text strong {
    color: #d97706;
}
.agent-tip .btn-clear {
    background: rgba(245, 158, 11, 0.2);
    border: none;
    padding: 6px 16px;
    border-radius: 20px;
    cursor: pointer;
    color: #92400e;
    font-size: 12px;
    transition: all 0.2s;
}
.agent-tip .btn-clear:hover {
    background: rgba(245, 158, 11, 0.4);
}
</style>
<script>
// 清除代理会话
function clearAgentSession() {
    fetch('/api/clear_agent_session.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.reload();
        }
    })
    .catch(() => {
        window.location.reload();
    });
}

// 防重复提交标志
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(() => 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() {
    console.log('buy_app.js 加载完成');
    
    const modal = document.getElementById('buyModal');
    const buyBtns = document.querySelectorAll('.buy-btn');
    let currentApp = null;
    
    console.log('找到按钮数量:', buyBtns.length);
    
    function closeModal() {
        modal.style.display = 'none';
    }
    
    function showModal(appId, appName, price, isAgent) {
        currentApp = { id: appId, name: appName, price: price, is_agent: isAgent };
        document.getElementById('modal_app_name').innerText = appName;
        document.getElementById('modal_price').innerText = '¥' + parseFloat(price).toFixed(2);
        modal.style.display = 'flex';
        console.log('显示弹窗:', appName, price, isAgent);
    }
    
    buyBtns.forEach((btn, index) => {
        console.log('绑定按钮:', index, btn.dataset.id, btn.dataset.name);
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            // 防止重复点击
            if (isProcessing) {
                window.showToast('正在处理中，请稍后...', 'warning');
                return;
            }
            console.log('点击购买按钮:', this.dataset.id, this.dataset.name, this.dataset.isAgent);
            showModal(this.dataset.id, this.dataset.name, this.dataset.price, this.dataset.isAgent);
        });
    });
    
    document.querySelectorAll('.close, .cancel-btn').forEach(el => {
        el.addEventListener('click', closeModal);
    });
    
    document.querySelector('.confirm-btn').addEventListener('click', function() {
        // 防止重复提交
        if (isProcessing) {
            window.showToast('正在处理中，请稍后...', 'warning');
            return;
        }
        
        const paymentMethod = document.querySelector('input[name="payment_method"]:checked').value;
        if (!currentApp) return;
        
        console.log('确认购买:', currentApp.id, paymentMethod, currentApp.is_agent);
        
        isProcessing = true;
        const confirmBtn = this;
        const originalText = confirmBtn.innerHTML;
        confirmBtn.innerHTML = '<span class="loading-spinner"></span> 处理中...';
        confirmBtn.disabled = true;
        
        if (paymentMethod === 'balance') {
            // 余额支付
            fetch('/modules/user/buy_app.php?action=purchase', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `app_id=${currentApp.id}&is_agent=${currentApp.is_agent || 0}`
            })
            .then(response => response.json())
            .then(data => {
                console.log('余额支付响应:', data);
                if (data.success) {
                    window.showToast('购买成功', 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    window.showToast(data.message || '购买失败', 'error');
                    confirmBtn.innerHTML = originalText;
                    confirmBtn.disabled = false;
                    isProcessing = false;
                }
                closeModal();
            })
            .catch(error => {
                console.error('错误:', error);
                window.showToast('网络错误', 'error');
                confirmBtn.innerHTML = originalText;
                confirmBtn.disabled = false;
                isProcessing = false;
                closeModal();
            });
        } else {
            // 在线支付 - 创建订单
            fetch('/modules/user/buy_app.php?action=create_order', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `app_id=${currentApp.id}&payment_method=${paymentMethod}&is_agent=${currentApp.is_agent || 0}`
            })
            .then(response => response.json())
            .then(data => {
                console.log('创建订单响应:', data);
                if (data.success) {
                    // 保存订单信息和支付方式
                    localStorage.setItem('pending_order', data.order_no);
                    localStorage.setItem('pending_method', paymentMethod);
                    
                    const payUrl = '/modules/payment/api.php?order_no=' + encodeURIComponent(data.order_no) + 
                                   '&amount=' + encodeURIComponent(data.amount) + 
                                   '&type=' + encodeURIComponent(paymentMethod) + 
                                   '&name=' + encodeURIComponent(data.name);
                    
                    fetch(payUrl)
                        .then(res => res.json())
                        .then(payData => {
                            if (payData.code == 1 && payData.qrcode) {
                                showPaymentModal(paymentMethod, data.amount, payData.qrcode, data.order_no);
                            } else {
                                window.showToast(payData.msg || '支付失败', 'error');
                            }
                            confirmBtn.innerHTML = originalText;
                            confirmBtn.disabled = false;
                            isProcessing = false;
                        })
                        .catch(error => {
                            console.error('支付请求错误:', error);
                            window.showToast('网络错误', 'error');
                            confirmBtn.innerHTML = originalText;
                            confirmBtn.disabled = false;
                            isProcessing = false;
                        });
                } else {
                    window.showToast(data.message || '创建订单失败', 'error');
                    confirmBtn.innerHTML = originalText;
                    confirmBtn.disabled = false;
                    isProcessing = false;
                }
                closeModal();
            })
            .catch(error => {
                console.error('错误:', error);
                window.showToast('网络错误', 'error');
                confirmBtn.innerHTML = originalText;
                confirmBtn.disabled = false;
                isProcessing = false;
                closeModal();
            });
        }
    });
    
    modal.addEventListener('click', function(e) {
        if (e.target === modal) closeModal();
    });
});
</script>