<?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 WHERE role = 'user'")['cnt'] ?? 0;
$employees_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM users WHERE role = 'employee'")['cnt'] ?? 0;
$apps_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM apps")['cnt'] ?? 0;
$licenses_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM licenses")['cnt'] ?? 0;
$orders_pend = $db->fetchOne("SELECT COUNT(*) as cnt FROM orders WHERE status = 'paid'")['cnt'] ?? 0;
$orders_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM orders WHERE status = 'pending'")['cnt'] ?? 0;
$tickets_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM tickets WHERE status IN ('open','processing')")['cnt'] ?? 0;
$today_income = $db->fetchOne("SELECT SUM(amount) as total FROM orders WHERE status = 'paid' AND DATE(paid_at) = CURDATE()")['total'] ?? 0;
$month_income = $db->fetchOne("SELECT SUM(amount) as total FROM orders WHERE status = 'paid' AND MONTH(paid_at) = MONTH(CURDATE())")['total'] ?? 0;

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

// SVG 图标链接（可自行替换）

$icon_success = '/assets/icons/scc.svg';  // 成功图标
$icon_warning = '/assets/icons/wr.svg';  // 警告图标
$icon_update  = '/assets/icons/up.svg';     // 更新图标

$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>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <h3>普通用户</h3>
            <div class="stat-value"><?php echo $users_count; ?></div>
        </div>
        <div class="stat-card">
            <h3>员工/管理员</h3>
            <div class="stat-value"><?php echo $employees_count + 1; ?></div>
        </div>
        <div class="stat-card">
            <h3>应用数量</h3>
            <div class="stat-value"><?php echo $apps_count; ?></div>
        </div>
        <div class="stat-card">
            <h3>授权码总数</h3>
            <div class="stat-value"><?php echo $licenses_count; ?></div>
        </div>
        <div class="stat-card">
            <h3>已支付订单</h3>
            <div class="stat-value"><?php echo $orders_pend; ?></div>
        </div>
        <div class="stat-card">
            <h3>待处理订单</h3>
            <div class="stat-value"><?php echo $orders_count; ?></div>
        </div>
        <div class="stat-card">
            <h3>待处理工单</h3>
            <div class="stat-value"><?php echo $tickets_count; ?></div>
        </div>
        <div class="stat-card">
            <h3>今日收入</h3>
            <div class="stat-value">¥<?php echo number_format($today_income, 2); ?></div>
        </div>
        <div class="stat-card">
            <h3>本月收入</h3>
            <div class="stat-value">¥<?php echo number_format($month_income, 2); ?></div>
        </div>
    </div>
    
    <!-- 系统公告区域 -->
    <?php if (!empty($announcements)): ?>
    <div class="section-box announcements-box">
        <div class="section-header">
            <h3>📢 系统公告</h3>
        </div>
        <div class="announcements-list">
            <?php foreach ($announcements as $ann): ?>
            <div class="announcement-item announcement-<?php echo htmlspecialchars($ann['type'] ?? 'info'); ?>">
                <?php if (!empty($ann['is_top'])): ?>
                    <span class="top-tag">置顶</span>
                <?php endif; ?>
                <div class="announcement-title">
                    <?php echo htmlspecialchars($ann['title']); ?>
                    <?php if (!empty($ann['created_at'])): ?>
                        <span class="announcement-time"><?php echo date('m-d H:i', strtotime($ann['created_at'])); ?></span>
                    <?php endif; ?>
                </div>
                <div class="announcement-content"><?php echo nl2br(htmlspecialchars($ann['content'])); ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- 版本更新状态卡片 -->
    <div class="section-box version-status-box">
        <div class="section-header">
            <h3>📦 系统版本状态</h3>
            <a href="?page=update" class="btn-small">检查更新</a>
        </div>
        
        <div class="version-info-container">
            <?php if (!empty($license_error)): ?>
                <div class="version-alert version-alert-warning">
                    <span class="alert-icon">
                        <img src="<?php echo $icon_warning; ?>" alt="警告" style="width: 40px; height: 40px;">
                    </span>
                    <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">
                    <span class="alert-icon">
                        <img src="<?php echo $icon_update; ?>" alt="更新" style="width: 40px; height: 40px;">
                    </span>
                    <div class="alert-content">
                        <strong>发现新版本！</strong>
                        <p>当前版本：<code><?php echo htmlspecialchars($current_version); ?></code> → 最新版本：<code><?php echo htmlspecialchars($update_info['version']); ?></code></p>
                        <?php if (!empty($update_info['title'])): ?>
                            <p class="update-title"><?php echo htmlspecialchars($update_info['title']); ?></p>
                        <?php endif; ?>
                        <?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">
                    <span class="alert-icon">
                        <img src="<?php echo $icon_success; ?>" alt="成功" style="width: 40px; height: 40px;">
                    </span>
                    <div class="alert-content">
                        <strong>系统已是最新版本</strong>
                        <p>当前版本：<code><?php echo htmlspecialchars($current_version); ?></code></p>
                    </div>
                    <span class="status-ok">运行正常</span>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- 快速信息 -->
        <div class="version-meta">
            <div class="meta-item">
                <span class="meta-label">授权状态</span>
                <span class="meta-value text-success">● 已激活</span>
            </div>
            <div class="meta-item">
                <span class="meta-label">站点ID</span>
                <span class="meta-value"><code><?php echo defined('SITE_ID') ? SITE_ID : '—'; ?></code></span>
            </div>
            <div class="meta-item">
                <span class="meta-label">最后检查</span>
                <span class="meta-value"><?php echo date('Y-m-d H:i'); ?></span>
            </div>
        </div>
    </div>
</div>

<style>
.admin-dashboard .stats-grid {
    margin-bottom: 30px;
}
.section-box {
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 20px;
    border: 1px solid var(--border-color);
}
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--border-color);
}
.section-header h3 {
    font-size: 18px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 8px;
}
.btn-small {
    padding: 6px 14px;
    background: var(--primary-color);
    color: white;
    border-radius: 20px;
    text-decoration: none;
    font-size: 13px;
    transition: all 0.2s;
}
.btn-small:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
}

/* 公告样式 */
.announcements-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}
.announcement-item {
    padding: 16px;
    border-radius: 12px;
    border-left: 4px solid;
    position: relative;
}
.announcement-info {
    background: #e3f2fd;
    border-left-color: #1565c0;
}
.announcement-warning {
    background: #fff3e0;
    border-left-color: #e65100;
}
.announcement-success {
    background: #e6f7e6;
    border-left-color: #2e7d32;
}
.announcement-danger {
    background: #fee9e7;
    border-left-color: #d32f2f;
}
.top-tag {
    position: absolute;
    top: 8px;
    right: 12px;
    background: #f59e0b;
    color: white;
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 11px;
}
.announcement-title {
    font-weight: 600;
    margin-bottom: 8px;
    padding-right: 60px;
}
.announcement-time {
    font-weight: 400;
    font-size: 12px;
    color: #888;
    margin-left: 12px;
}
.announcement-content {
    color: #444;
    line-height: 1.6;
    font-size: 14px;
}

/* 版本提示卡片 */
.version-alert {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 20px;
    border-radius: 14px;
    margin-bottom: 20px;
}
.version-alert-info {
    background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
    border-left: 4px solid #0284c7;
}
.version-alert-success {
    background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
    border-left: 4px solid #059669;
}
.version-alert-warning {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border-left: 4px solid #d97706;
}
.alert-icon {
    font-size: 40px;
}
.alert-content {
    flex: 1;
}
.alert-content strong {
    font-size: 16px;
    display: block;
    margin-bottom: 6px;
}
.alert-content p {
    margin: 4px 0;
    color: #374151;
}
.alert-content code {
    background: rgba(0,0,0,0.08);
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 13px;
}
.update-title {
    font-weight: 500;
    color: #1e293b;
}
.force-badge {
    display: inline-block;
    background: #dc2626;
    color: white;
    padding: 3px 10px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-top: 8px;
}
.btn-update-now {
    padding: 10px 20px;
    background: #0284c7;
    color: white;
    border-radius: 30px;
    text-decoration: none;
    font-weight: 500;
    font-size: 14px;
    transition: all 0.2s;
    white-space: nowrap;
}
.btn-update-now:hover {
    background: #0369a1;
    transform: translateX(3px);
}
.status-ok {
    color: #059669;
    font-weight: 500;
    font-size: 14px;
}

/* 元信息行 */
.version-meta {
    display: flex;
    gap: 30px;
    padding-top: 12px;
    border-top: 1px dashed var(--border-color);
}
.meta-item {
    display: flex;
    align-items: center;
    gap: 8px;
}
.meta-label {
    color: #6b7280;
    font-size: 13px;
}
.meta-value {
    font-size: 13px;
}
.meta-value code {
    background: var(--bg-secondary);
    padding: 2px 6px;
    border-radius: 10px;
}
.text-success {
    color: #059669;
}

/* 统计卡片 */
.stat-card {
    background: var(--bg-primary);
    border-radius: 12px;
    padding: 20px;
    border: 1px solid var(--border-color);
}
.stat-card h3 {
    font-size: 14px;
    color: var(--text-secondary);
    margin-bottom: 8px;
    font-weight: 400;
}
.stat-value {
    font-size: 32px;
    font-weight: 700;
    color: var(--text-primary);
}
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 16px;
}
</style>