<?php
/**
 * 管理员仪表盘 - 统计概览（优化版）
 */
if (!defined('IN_ADMIN')) {
    define('IN_ADMIN', true);
}
require_once __DIR__ . '/../../config.php';

if (!isAdmin()) {
    redirect(SITE_URL . 'admin.php');
}

$user = currentUser();

// 精简统计：只保留核心数据
$users_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM users")['cnt'] ?? 0;
$apps_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM apps WHERE status = 1")['cnt'] ?? 0;
$licenses_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM licenses")['cnt'] ?? 0;
$today_income = $db->fetchOne("SELECT SUM(amount) as total FROM orders WHERE status = 'paid' AND DATE(paid_at) = CURDATE()")['total'] ?? 0;

// 获取版本信息
require_once __DIR__ . '/../../includes/LicenseClient.php';

// SVG 图标
$svg_icons = [
    'users'     => 'https://api.iconify.design/mdi:account-group.svg?color=%23667eea',
    'apps'      => 'https://api.iconify.design/mdi:application.svg?color=%2310b981',
    'licenses'  => 'https://api.iconify.design/mdi:key.svg?color=%23f59e0b',
    'income'    => 'https://api.iconify.design/mdi:cash.svg?color=%23ef4444',
    'announce'  => 'https://api.iconify.design/mdi:bullhorn.svg?color=%238b5cf6',
    'version'   => 'https://api.iconify.design/mdi:package-up.svg?color=%2306b6d4',
    'success'   => 'https://api.iconify.design/mdi:check-circle.svg?color=%2310b981',
    'warning'   => 'https://api.iconify.design/mdi:alert-circle.svg?color=%23f59e0b',
    'update'    => 'https://api.iconify.design/mdi:cloud-download.svg?color=%232563eb',
    'site'      => 'https://api.iconify.design/mdi:web.svg?color=%236b7280',
    'time'      => 'https://api.iconify.design/mdi:clock-outline.svg?color=%236b7280',
    'pin'       => 'https://api.iconify.design/mdi:pin.svg?color=white',
    'chevron'   => 'https://api.iconify.design/mdi:chevron-right.svg?color=white',
];

$current_version = '';
$has_update = false;
$update_info = null;
$license_error = '';
$announcements = [];

try {
    $client = new LicenseClient();
    $current_version = $client->getCurrentVersion();
    $update_info = $client->checkUpdate();
    $has_update = $update_info['has_update'] ?? false;
    $announcements = $client->getAnnouncements($current_version);
} catch (Exception $e) {
    $license_error = $e->getMessage();
    $current_version = defined('SYS_VERSION') ? SYS_VERSION : '1.0.0';
}
?>

<div class="admin-dashboard">
    <h2 class="page-subtitle">
        欢迎回来，<?php echo htmlspecialchars($user['username']); ?>！
    </h2>
    
    <!-- 统计卡片 - 精简为 4 个 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">
                <img src="<?php echo $svg_icons['users']; ?>" alt="">
            </div>
            <div class="stat-content">
                <div class="stat-value"><?php echo number_format($users_count); ?></div>
                <div class="stat-label">总用户数</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="<?php echo $svg_icons['apps']; ?>" alt="">
            </div>
            <div class="stat-content">
                <div class="stat-value"><?php echo number_format($apps_count); ?></div>
                <div class="stat-label">应用数量</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="<?php echo $svg_icons['licenses']; ?>" alt="">
            </div>
            <div class="stat-content">
                <div class="stat-value"><?php echo number_format($licenses_count); ?></div>
                <div class="stat-label">授权码总数</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="<?php echo $svg_icons['income']; ?>" alt="">
            </div>
            <div class="stat-content">
                <div class="stat-value">¥<?php echo number_format($today_income, 2); ?></div>
                <div class="stat-label">今日收入</div>
            </div>
        </div>
    </div>
    
    <!-- 左右列布局：公告 + 版本状态 -->
    <div class="dashboard-row">
        <!-- 左侧：系统公告 -->
        <div class="dashboard-col">
            <div class="section-box">
                <div class="section-header">
                    <h3>
                        <img src="<?php echo $svg_icons['announce']; ?>" alt="" style="width:22px;height:22px;">
                        系统公告
                    </h3>
                </div>
                
                <?php if (empty($announcements)): ?>
                    <div class="empty-state-small">
                        <img src="https://api.iconify.design/mdi:inbox.svg?color=%239ca3af" alt="" style="width:48px;">
                        <p>暂无公告</p>
                    </div>
                <?php else: ?>
                    <div class="announcements-list">
                        <?php foreach (array_slice($announcements, 0, 5) as $ann): ?>
                        <div class="announcement-item announcement-<?php echo htmlspecialchars($ann['type'] ?? 'info'); ?>">
                            <?php if (!empty($ann['is_top'])): ?>
                                <span class="top-tag">
                                    <img src="<?php echo $svg_icons['pin']; ?>" alt="" style="width:12px;">
                                    置顶
                                </span>
                            <?php endif; ?>
                            <div class="announcement-title">
                                <?php echo htmlspecialchars($ann['title']); ?>
                            </div>
                            <div class="announcement-content">
                                <?php echo nl2br(htmlspecialchars(mb_substr($ann['content'], 0, 80) . (mb_strlen($ann['content']) > 80 ? '...' : ''))); ?>
                            </div>
                            <?php if (!empty($ann['created_at'])): ?>
                                <div class="announcement-time">
                                    <img src="<?php echo $svg_icons['time']; ?>" alt="" style="width:12px;">
                                    <?php echo date('m-d H:i', strtotime($ann['created_at'])); ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- 右侧：版本状态 -->
        <div class="dashboard-col">
            <div class="section-box">
                <div class="section-header">
                    <h3>
                        <img src="<?php echo $svg_icons['version']; ?>" alt="" style="width:22px;height:22px;">
                        系统状态
                    </h3>
                    <a href="?page=update" class="btn-small">
                        检查更新
                        <img src="<?php echo $svg_icons['chevron']; ?>" alt="" style="width:14px;">
                    </a>
                </div>
                
                <div class="version-info-container">
                    <?php if (!empty($license_error)): ?>
                        <div class="version-alert version-alert-warning">
                            <img src="<?php echo $svg_icons['warning']; ?>" alt="" style="width:36px;height:36px;">
                            <div class="alert-content">
                                <strong>授权异常</strong>
                                <p><?php echo htmlspecialchars($license_error); ?></p>
                            </div>
                        </div>
                    <?php elseif ($has_update): ?>
                        <div class="version-alert version-alert-info">
                            <img src="<?php echo $svg_icons['update']; ?>" alt="" style="width:36px;height:36px;">
                            <div class="alert-content">
                                <strong>发现新版本 v<?php echo htmlspecialchars($update_info['version']); ?></strong>
                                <p><?php echo htmlspecialchars($update_info['title'] ?? '有新版本可更新'); ?></p>
                                <?php if (!empty($update_info['is_force'])): ?>
                                    <span class="force-badge">强制更新</span>
                                <?php endif; ?>
                            </div>
                            <a href="?page=update" class="btn-update-now">立即更新</a>
                        </div>
                    <?php else: ?>
                        <div class="version-alert version-alert-success">
                            <img src="<?php echo $svg_icons['success']; ?>" alt="" style="width:36px;height:36px;">
                            <div class="alert-content">
                                <strong>系统已是最新版本</strong>
                                <p>当前版本 v<?php echo htmlspecialchars($current_version); ?></p>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
                <!-- 更新提示横幅 -->
<?php if ($has_update): ?>
<div class="update-banner <?php echo !empty($update_info['is_force']) ? 'force' : ''; ?>">
    <div class="banner-content">
        <img src="<?php echo $svg_icons['update']; ?>" alt="" style="width:24px;height:24px;">
        <div class="banner-text">
            <strong>发现新版本 v<?php echo htmlspecialchars($update_info['version']); ?></strong>
            <span><?php echo htmlspecialchars($update_info['title'] ?? '有新版本可更新'); ?></span>
        </div>
    </div>
    <a href="?page=update" class="banner-btn">
        立即更新
        <img src="<?php echo $svg_icons['chevron']; ?>" alt="" style="width:14px;">
    </a>
    <?php if (empty($update_info['is_force'])): ?>
    <button class="banner-close" onclick="dismissBanner()">
        <img src="https://api.iconify.design/mdi:close.svg?color=%239ca3af" alt="">
    </button>
    <?php endif; ?>
</div>
<?php endif; ?>
                <!-- 站点信息 -->
                <div class="site-info">
                    <div class="info-row">
                        <img src="<?php echo $svg_icons['site']; ?>" alt="" style="width:16px;">
                        <span class="info-label">站点ID</span>
                        <code><?php echo defined('SITE_ID') ? substr(SITE_ID, 0, 32)  : '—'; ?></code>
                    </div>
                    <div class="info-row">
                        <img src="<?php echo $svg_icons['time']; ?>" alt="" style="width:16px;">
                        <span class="info-label">最后检查</span>
                        <span><?php echo date('Y-m-d H:i'); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="status-dot success"></span>
                        <span class="info-label">授权状态</span>
                        <span class="text-success">已激活</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* 更新横幅 */
.update-banner {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16px;
    padding: 16px 22px;
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 20px;
    color: white;
    position: relative;
}

.update-banner.force {
    background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
}

.banner-content {
    display: flex;
    align-items: center;
    gap: 16px;
    flex: 1;
}

.banner-content img {
    filter: brightness(0) invert(1);
}

.banner-text {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.banner-text strong {
    font-size: 18px;
}

.banner-text span {
    font-size: 14px;
    opacity: 0.9;
}

.banner-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 22px;
    background: rgba(255,255,255,0.2);
    border-radius: 40px;
    color: white;
    text-decoration: none;
    font-weight: 500;
    font-size: 15px;
    transition: all 0.2s;
    border: 1px solid rgba(255,255,255,0.2);
}

.banner-btn:hover {
    background: rgba(255,255,255,0.3);
}

.banner-btn img {
    filter: brightness(0) invert(1);
}

.banner-close {
    background: none;
    border: none;
    cursor: pointer;
    padding: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0.7;
    transition: opacity 0.2s;
}

.banner-close:hover {
    opacity: 1;
}

/* 响应式 */
@media (max-width: 640px) {
    .update-banner {
        flex-wrap: wrap;
    }
    
    .banner-btn {
        width: 100%;
        justify-content: center;
    }
    
    .banner-close {
        position: absolute;
        top: 12px;
        right: 12px;
    }
}
.admin-dashboard {
    padding: 4px 0;
}

.page-subtitle {
    font-size: 22px;
    font-weight: 600;
    margin-bottom: 24px;
    color: var(--text-primary);
}

/* 统计卡片 */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 18px;
    margin-bottom: 28px;
}

.stat-card {
    background: var(--bg-primary);
    border-radius: 18px;
    padding: 22px 20px;
    border: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.2s;
}

.stat-card:hover {
    box-shadow: var(--shadow-md);
    border-color: transparent;
}

.stat-icon {
    width: 52px;
    height: 52px;
    background: var(--bg-secondary);
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.stat-icon img {
    width: 28px;
    height: 28px;
}

.stat-content {
    flex: 1;
}

.stat-value {
    font-size: 30px;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1.2;
}

.stat-label {
    font-size: 14px;
    color: var(--text-secondary);
}

/* 左右列布局 */
.dashboard-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
}

.dashboard-col {
    min-width: 0;
}

.section-box {
    background: var(--bg-primary);
    border-radius: 18px;
    padding: 22px;
    border: 1px solid var(--border-color);
    height: 100%;
    display: flex;
    flex-direction: column;
}

.section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 18px;
    padding-bottom: 14px;
    border-bottom: 1px solid var(--border-color);
}

.section-header h3 {
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 8px;
}

.btn-small {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 14px;
    background: var(--primary-color);
    color: white;
    border-radius: 30px;
    text-decoration: none;
    font-size: 13px;
    font-weight: 500;
    transition: all 0.2s;
}

.btn-small:hover {
    background: var(--primary-hover);
}

.btn-small img {
    width: 14px;
    height: 14px;
    filter: brightness(0) invert(1);
}

/* 公告列表 */
.announcements-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    flex: 1;
}

.announcement-item {
    padding: 14px 16px;
    border-radius: 14px;
    position: relative;
    transition: all 0.2s;
}

.announcement-item:hover {
    background: var(--bg-secondary);
}

.announcement-info {
    border-left: 3px solid #3b82f6;
}

.announcement-warning {
    border-left: 3px solid #f59e0b;
}

.announcement-success {
    border-left: 3px solid #10b981;
}

.announcement-danger {
    border-left: 3px solid #ef4444;
}

.top-tag {
    position: absolute;
    top: 12px;
    right: 14px;
    background: #f59e0b;
    color: white;
    padding: 2px 8px;
    border-radius: 30px;
    font-size: 10px;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 3px;
}

.announcement-title {
    font-weight: 600;
    font-size: 15px;
    color: var(--text-primary);
    margin-bottom: 8px;
    padding-right: 50px;
}

.announcement-content {
    color: var(--text-secondary);
    font-size: 13px;
    line-height: 1.5;
    margin-bottom: 8px;
}

.announcement-time {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 11px;
    color: var(--text-muted);
}

/* 版本状态 */
.version-info-container {
    margin-bottom: 18px;
}

.version-alert {
    display: flex;
    align-items: flex-start;
    gap: 14px;
    padding: 18px;
    border-radius: 16px;
}

.version-alert-info {
    background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
}

.version-alert-success {
    background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
}

.version-alert-warning {
    background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
}

.alert-content {
    flex: 1;
}

.alert-content strong {
    font-size: 15px;
    display: block;
    margin-bottom: 4px;
    color: var(--text-primary);
}

.alert-content p {
    font-size: 13px;
    color: var(--text-secondary);
    margin-bottom: 6px;
}

.force-badge {
    display: inline-block;
    background: #dc2626;
    color: white;
    padding: 2px 10px;
    border-radius: 30px;
    font-size: 11px;
    font-weight: 500;
}

.btn-update-now {
    padding: 10px 18px;
    background: #2563eb;
    color: white;
    border-radius: 30px;
    text-decoration: none;
    font-size: 13px;
    font-weight: 500;
    white-space: nowrap;
    transition: all 0.2s;
}

.btn-update-now:hover {
    background: #1d4ed8;
}

/* 站点信息 */
.site-info {
    margin-top: auto;
    padding-top: 18px;
    border-top: 1px dashed var(--border-color);
}

.info-row {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 0;
    font-size: 13px;
}

.info-label {
    color: var(--text-secondary);
    min-width: 70px;
}

.info-row code {
    background: var(--bg-secondary);
    padding: 3px 8px;
    border-radius: 8px;
    font-family: monospace;
    font-size: 12px;
}

.status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
}

.status-dot.success {
    background: #10b981;
}

.text-success {
    color: #10b981;
}

.empty-state-small {
    text-align: center;
    padding: 30px 20px;
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.empty-state-small img {
    opacity: 0.4;
    margin-bottom: 12px;
}

.empty-state-small p {
    color: var(--text-muted);
    font-size: 14px;
}

/* 响应式 */
@media (max-width: 900px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .dashboard-row {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 480px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    
    .version-alert {
        flex-wrap: wrap;
    }
    
    .btn-update-now {
        width: 100%;
        text-align: center;
    }
}
</style>
<script>
function dismissBanner() {
    const banner = document.querySelector('.update-banner');
    if (banner) {
        banner.style.display = 'none';
        // 记录关闭状态，当天不再显示
        localStorage.setItem('update_banner_dismissed_' + '<?php echo $update_info['version'] ?? ""; ?>', new Date().toDateString());
    }
}

// 检查是否已关闭
document.addEventListener('DOMContentLoaded', function() {
    const version = '<?php echo $update_info['version'] ?? ""; ?>';
    if (version) {
        const dismissed = localStorage.getItem('update_banner_dismissed_' + version);
        const today = new Date().toDateString();
        if (dismissed === today) {
            const banner = document.querySelector('.update-banner');
            if (banner && !banner.classList.contains('force')) {
                banner.style.display = 'none';
            }
        }
    }
});
</script>