<?php
// 用户仪表盘 - 显示统计概览
$user_id = $_SESSION['user_id'];
$user = currentUser();

// 统计数据
$apps_count = getUserAppsCount($user_id);
$licenses_count = getUserLicensesCount($user_id);
$open_tickets = getUserOpenTicketsCount($user_id);
$balance = $user['balance'];

// 获取用户当前用户组
$current_group = getUserCurrentGroup($user_id);

// 最近授权码
$recent_licenses = $db->fetchAll("
    SELECT l.*, a.name as app_name 
    FROM licenses l 
    JOIN apps a ON l.app_id = a.id 
    WHERE l.user_id = $user_id 
    ORDER BY l.id DESC LIMIT 5
");

// 最近工单
$recent_tickets = $db->fetchAll("
    SELECT * FROM tickets 
    WHERE user_id = $user_id 
    ORDER BY id DESC LIMIT 5
");
?>

<div class="dashboard-container">
    <h2 class="page-subtitle">欢迎回来，<?php echo htmlspecialchars($user['username']); ?>！</h2>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <h3>授权应用</h3>
            <div class="stat-value"><?php echo $apps_count; ?></div>
            <p>已授权的应用数量</p>
        </div>
        <div class="stat-card">
            <h3>授权码</h3>
            <div class="stat-value"><?php echo $licenses_count; ?></div>
            <p>已生成的授权码</p>
        </div>
        <div class="stat-card">
            <h3>待处理工单</h3>
            <div class="stat-value"><?php echo $open_tickets; ?></div>
            <p>等待回复的工单</p>
        </div>
        <div class="stat-card">
            <h3>账户余额</h3>
            <div class="stat-value">¥<?php echo number_format($balance, 2); ?></div>
            <p><a href="?page=recharge" class="btn-small">立即充值</a></p>
        </div>
    </div>
    
    <!-- 会员信息卡片 -->
    <div class="info-card" style="margin-bottom: 30px; background: var(--primary-light); padding: 20px; border-radius: var(--radius-md);">
        <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap;">
            <div>
                <strong>当前会员等级：</strong> <?php echo htmlspecialchars($current_group['name']); ?>
                <?php if ($current_group['discount'] < 100): ?>
                    <span class="badge" style="background: var(--primary-color); color: white; margin-left: 10px;"><?php echo $current_group['discount']; ?>折优惠</span>
                <?php endif; ?>
                <?php if (!empty($current_group['expire_date'])): ?>
                    <span class="badge" style="margin-left: 10px;">有效期至：<?php echo $current_group['expire_date']; ?></span>
                <?php endif; ?>
            </div>
            <a href="?page=buy_group" class="btn-small">升级会员</a>
        </div>
    </div>
    
    <!-- 最近授权码 -->
    <div class="section-box">
        <div class="section-header">
            <h3>最近授权码</h3>
            <a href="?page=licenses" class="btn-small">查看全部</a>
        </div>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>授权码</th>
                        <th>应用名称</th>
                        <th>绑定域名</th>
                        <th>到期时间</th>
                        <th>状态</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($recent_licenses)): ?>
                        <tr><td colspan="5" style="text-align: center;">暂无授权码</td></tr>
                    <?php else: ?>
                        <?php foreach ($recent_licenses as $lic): ?>
                            <tr>
                                <td><code><?php echo htmlspecialchars($lic['license_code']); ?></code></td>
                                <td><?php echo htmlspecialchars($lic['app_name']); ?></td>
                                <td><?php echo htmlspecialchars($lic['domain'] ?: '未绑定'); ?></td>
                                <td><?php echo $lic['expire_date'] ?: '永久'; ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $lic['status'] ? 'active' : 'inactive'; ?>">
                                        <?php echo $lic['status'] ? '有效' : '已禁用'; ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- 最近工单 -->
    <div class="section-box">
        <div class="section-header">
            <h3>最近工单</h3>
            <a href="?page=tickets" class="btn-small">查看全部</a>
        </div>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>标题</th>
                        <th>状态</th>
                        <th>优先级</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($recent_tickets)): ?>
                        <tr><td colspan="5" style="text-align: center;">暂无工单</td></tr>
                    <?php else: ?>
                        <?php foreach ($recent_tickets as $ticket): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($ticket['title']); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $ticket['status']; ?>">
                                        <?php 
                                        $status_map = ['open' => '待处理', 'processing' => '处理中', 'closed' => '已关闭'];
                                        echo $status_map[$ticket['status']] ?? $ticket['status'];
                                        ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="priority-<?php echo $ticket['priority']; ?>">
                                        <?php 
                                        $priority_map = ['low' => '低', 'medium' => '中', 'high' => '高'];
                                        echo $priority_map[$ticket['priority']] ?? $ticket['priority'];
                                        ?>
                                    </span>
                                </td>
                                <td><?php echo $ticket['created_at']; ?></td>
                                <td><a href="?page=ticket_view&id=<?php echo $ticket['id']; ?>" class="btn-small">查看</a></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </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>
.dashboard-container {
    max-width: 100%;
}
.section-box {
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid var(--border-color);
}
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--border-color);
}
.section-header h3 {
    font-size: 16px;
    font-weight: 600;
}
.btn-small {
    padding: 5px 12px;
    background: var(--primary-color);
    color: white;
    border-radius: 5px;
    text-decoration: none;
    font-size: 12px;
}
.btn-small:hover {
    background: var(--primary-hover);
}
.status-badge {
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 12px;
}
.status-active, .status-open, .status-processing {
    background: #d1fae5;
    color: #065f46;
}
.status-inactive, .status-closed {
    background: #fee2e2;
    color: #991b1b;
}
.priority-low {
    color: #6b7280;
}
.priority-medium {
    color: #f59e0b;
}
.priority-high {
    color: #ef4444;
}
.info-card .badge {
    padding: 3px 10px;
    border-radius: 20px;
    font-size: 12px;
}
</style>