<?php
// ========== 代理商链接识别 ==========
// 识别通过代理链接进来的用户
if (isset($_GET['app']) && isset($_SESSION['agent_id'])) {
    $agent_id = $_SESSION['agent_id'];
    $app_id = intval($_GET['app']);
    
    // 验证代理商和应用是否有效
    $agent_app = $db->fetchOne("
        SELECT * FROM agent_apps 
        WHERE agent_id = $agent_id AND app_id = $app_id AND status = 1
    ");
    
    if ($agent_app) {
        // 设置代理价格到SESSION
        $_SESSION['agent_price'] = $agent_app['agent_price'];
        $_SESSION['agent_app_id'] = $app_id;
    }
}
// ========== 代理商链接识别结束 ==========

require_once '../../config.php';

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

$site_name = getSiteConfig('site_name') ?? '万能授权系统';

// 获取当前是否有代理价格
$has_agent_price = isset($_SESSION['agent_price']) && isset($_SESSION['agent_app_id']);
?>
        <?php include 'header.php'; ?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购买授权 - <?php echo htmlspecialchars($site_name); ?></title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <link rel="stylesheet" href="/assets/css/dark.css" id="dark-theme" disabled>
    <script src="/assets/js/main.js" defer></script>
    <style>
        /* 代理提示样式 */
        .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);
        }
        .agent-price-badge {
            background: #f59e0b;
            color: white;
            font-size: 12px;
            padding: 2px 8px;
            border-radius: 20px;
            margin-left: 8px;
        }
    </style>
</head>
<body>
    <div class="front-container">
        
        <main class="front-main">
            <div class="buy-container">
                <div class="buy-header">
                    <h2>购买授权</h2>
                    <p>选择您需要的应用授权</p>
                </div>
                
                <!-- 代理提示 -->
                <?php if ($has_agent_price): ?>
                    <?php
                    $agent_app = $db->fetchOne("SELECT name FROM apps WHERE id = {$_SESSION['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; ?>
                
                <?php if (empty($apps)): ?>
                    <div class="empty-state">
                        <p>暂无可购买的应用</p>
                    </div>
                <?php else: ?>
                    <div class="apps-grid">
                        <?php foreach ($apps as $app): ?>
                            <?php 
                            // 判断是否有代理价格
                            $is_agent_app = ($has_agent_price && $_SESSION['agent_app_id'] == $app['id']);
                            $display_price = $is_agent_app ? $_SESSION['agent_price'] : $app['price'];
                            $price_class = $is_agent_app ? 'agent-price' : '';
                            ?>
                            <div class="app-card">
                                <div class="app-card-header">
                                    <h3><?php echo htmlspecialchars($app['name']); ?></h3>
                                    <div class="price <?php echo $price_class; ?>">
                                        ¥<?php echo number_format($display_price, 2); ?>
                                        <?php if ($is_agent_app && $app['price'] > $display_price): ?>
                                            <span class="agent-price-badge">代理价</span>
                                            <span class="original-price" style="text-decoration: line-through; font-size: 14px; color: var(--text-muted); margin-left: 5px;">¥<?php echo number_format($app['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-card-footer">
                                    <?php if (isLoggedIn()): ?>
                                        <a href="/admin.php?page=buy_app&app_id=<?php echo $app['id']; ?><?php echo $is_agent_app ? '&agent=1' : ''; ?>" class="btn btn-primary btn-block">立即购买</a>
                                    <?php else: ?>
                                        <a href="/modules/home/login.php?redirect=buy&app_id=<?php echo $app['id']; ?><?php echo $is_agent_app ? '&agent=1' : ''; ?>" class="btn btn-primary btn-block">登录后购买</a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </main>
        
        <?php include 'footer.php'; ?>
    </div>
    
    <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();
            });
        }
    </script>
    <!-- 公告弹窗 -->
<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>
</body>
</html>

<style>
.buy-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 40px 20px;
}
.buy-header {
    text-align: center;
    margin-bottom: 40px;
}
.buy-header h2 {
    font-size: 32px;
    margin-bottom: 10px;
}
.buy-header p {
    color: var(--text-secondary);
}
.apps-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 30px;
}
.app-card {
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-lg);
    padding: 24px;
    transition: transform 0.2s, box-shadow 0.2s;
}
.app-card:hover {
    transform: translateY(-5px);
    box-shadow: var(--shadow-lg);
}
.app-card-header {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    margin-bottom: 16px;
}
.app-card-header h3 {
    font-size: 20px;
}
.price {
    font-size: 24px;
    font-weight: bold;
    color: var(--primary-color);
}
.price.agent-price {
    color: #f59e0b;
}
.app-desc {
    color: var(--text-secondary);
    margin-bottom: 16px;
    line-height: 1.6;
}
.app-meta {
    margin-bottom: 20px;
    padding-top: 16px;
    border-top: 1px solid var(--border-color);
    color: var(--text-muted);
    font-size: 14px;
}
.btn-block {
    width: 100%;
    text-align: center;
}
</style>