<?php

require_once dirname(__DIR__, 2) . '/core/lib/system_health.php';
require_once dirname(__DIR__, 2) . '/core/lib/task_center.php';

$checks = cmsCollectSystemHealth($db, dirname(__DIR__, 2));
$summary = cmsSystemHealthSummary($checks);
$scheduler = cmsReadSchedulerStatus();
$pendingArticles = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('article')} WHERE deleted_at=0 AND status=0 AND review_status='approved' AND scheduled_publish_at>0")['cnt'] ?? 0);
$dueArticles = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('article')} WHERE deleted_at=0 AND status=0 AND review_status='approved' AND scheduled_publish_at>0 AND scheduled_publish_at<=?", [time()])['cnt'] ?? 0);
$cachePath = dirname(__DIR__, 2) . '/data/cache';
$cacheFiles = is_dir($cachePath) ? glob($cachePath . '/*') : [];
$cacheSize = 0;
foreach ((array) $cacheFiles as $file) { if (is_file($file)) { $cacheSize += filesize($file); } }
$backupConfig = [];
foreach ($db->fetchAll("SELECT config_key, config_value FROM {$db->table('config')} WHERE config_key IN ('auto_backup_enabled','auto_backup_interval')") as $row) {
    $backupConfig[$row['config_key']] = $row['config_value'];
}
$backupEnabled = intval($backupConfig['auto_backup_enabled'] ?? 0) === 1;
$backupIntervals = ['hourly' => 3600, 'daily' => 86400, 'weekly' => 604800, 'monthly' => 2592000];
$backupIntervalLabels = ['hourly' => '每小时', 'daily' => '每天', 'weekly' => '每周', 'monthly' => '每月'];
$backupIntervalKey = (string) ($backupConfig['auto_backup_interval'] ?? 'daily');
$backupInterval = $backupIntervals[$backupIntervalKey] ?? $backupIntervals['daily'];
$backupIntervalLabel = $backupIntervalLabels[$backupIntervalKey] ?? $backupIntervalLabels['daily'];
$latestBackup = cmsTaskRecentRuns($db, 1, 'database_backup')[0] ?? [];
$latestBackupSuccess = cmsTaskRecentRuns($db, 1, 'database_backup', 'success')[0] ?? [];
$lastBackupAt = intval($latestBackupSuccess['started_at'] ?? 0);
$nextBackupAt = $lastBackupAt > 0 ? $lastBackupAt + $backupInterval : 0;
$backupStatus = 'warning';
$backupState = '自动备份已关闭';
$backupNote = '可在数据库管理中启用自动备份并设置执行周期。';
if ($backupEnabled) {
    $backupState = '等待首次自动备份';
    $backupNote = '自动备份已启用，请确认系统调度任务正在运行。';
    if (($latestBackup['status'] ?? '') === 'running') {
        $backupState = '备份正在执行';
        $backupNote = '任务已启动，完成后会更新最近成功时间。';
    } elseif (($latestBackup['status'] ?? '') === 'error' && intval($latestBackup['started_at'] ?? 0) >= $lastBackupAt) {
        $backupStatus = 'error';
        $backupState = '最近备份失败';
        $backupNote = trim((string) ($latestBackup['error_message'] ?? '')) ?: '请到后台任务查看失败详情。';
    } elseif ($lastBackupAt > 0 && $nextBackupAt <= time()) {
        $backupState = '备份任务已逾期';
        $backupNote = '下次备份时间已经到期，请检查 cli/scheduler.php 调度。';
    } elseif ($lastBackupAt > 0) {
        $backupStatus = 'ok';
        $backupState = '自动备份正常';
        $backupNote = '备份任务按配置周期运行。';
    }
}
$overall = ($summary['error'] > 0 || $backupStatus === 'error') ? 'error' : (($summary['warning'] > 0 || $scheduler['status'] !== 'ok' || $backupStatus !== 'ok') ? 'warning' : 'ok');
$labels = ['ok' => '运行正常', 'warning' => '需要关注', 'error' => '存在异常'];
?>
<div class="page-container fade-in health-page">
    <div class="page-header">
        <div class="page-title"><div class="page-icon"><i class="fa fa-heartbeat"></i></div><div><h1>系统状态</h1><p>检查运行环境、目录权限、定时发布和自动备份任务</p></div></div>
        <div class="page-actions"><button type="button" class="btn btn-primary" onclick="CMSAdminUI.reload(this,'检测中')"><i class="fa fa-refresh"></i> 重新检测</button></div>
    </div>

    <section class="health-overview health-<?php echo $overall; ?>">
        <div><span class="health-signal"></span><strong><?php echo $labels[$overall]; ?></strong><p>本次检测 <?php echo count($checks); ?> 项，不会修改系统配置。</p></div>
        <div class="health-totals"><span><b><?php echo $summary['ok']; ?></b> 正常</span><span><b><?php echo $summary['warning']; ?></b> 提醒</span><span><b><?php echo $summary['error']; ?></b> 异常</span></div>
    </section>

    <div class="health-grid">
        <section class="health-card health-scheduler-card">
            <div class="health-card-head"><div><span class="health-eyebrow">AUTOMATION</span><h2>定时发布任务</h2></div><span class="health-pill is-<?php echo htmlspecialchars($scheduler['status']); ?>"><?php echo $labels[$scheduler['status']]; ?></span></div>
            <div class="health-metrics"><div><small>最近运行</small><strong><?php echo !empty($scheduler['run_at']) ? date('Y-m-d H:i:s', intval($scheduler['run_at'])) : '暂无记录'; ?></strong></div><div><small>待发布</small><strong><?php echo $pendingArticles; ?> 篇</strong></div><div><small>已到期</small><strong><?php echo $dueArticles; ?> 篇</strong></div></div>
            <p class="health-note"><?php echo htmlspecialchars($scheduler['message'] ?? ''); ?><?php if (($scheduler['status'] ?? '') === 'warning'): ?>。建议确认 Windows 计划任务已按说明安装。<?php endif; ?></p>
            <div class="health-actions"><a class="btn btn-secondary" href="?act=article&state=scheduled">查看待发布</a><span>调度入口：cli/scheduler.php · 说明：cli/README.md</span></div>
        </section>

        <section class="health-card health-backup-card">
            <div class="health-card-head"><div><span class="health-eyebrow">BACKUP</span><h2>自动备份</h2></div><span class="health-pill is-<?php echo $backupStatus; ?>"><?php echo htmlspecialchars($backupState); ?></span></div>
            <div class="health-metrics"><div><small>执行周期</small><strong><?php echo $backupEnabled ? $backupIntervalLabel : '未启用'; ?></strong></div><div><small>最近成功</small><strong><?php echo $lastBackupAt ? date('Y-m-d H:i:s', $lastBackupAt) : '暂无记录'; ?></strong></div><div><small>下次到期</small><strong><?php echo $backupEnabled && $nextBackupAt ? date('Y-m-d H:i:s', $nextBackupAt) : '—'; ?></strong></div></div>
            <p class="health-note"><?php echo htmlspecialchars($backupNote); ?></p>
            <div class="health-actions"><a class="btn btn-secondary" href="?act=database">备份设置</a><a href="?act=task_center&task=database_backup">查看运行记录</a></div>
        </section>

        <section class="health-card">
            <div class="health-card-head"><div><span class="health-eyebrow">CACHE</span><h2>缓存概况</h2></div><span class="health-pill is-ok">可用</span></div>
            <div class="health-cache-value"><?php echo count((array) $cacheFiles); ?><small> 个缓存项</small></div>
            <p class="health-note">当前缓存占用 <?php echo cmsFormatBytes($cacheSize); ?>。这里只显示状态，不自动清理业务缓存。</p>
        </section>
    </div>

    <section class="health-card health-checks-card">
        <div class="health-card-head"><div><span class="health-eyebrow">ENVIRONMENT</span><h2>环境与目录检查</h2></div><span class="health-muted">检测时间 <?php echo date('Y-m-d H:i:s'); ?></span></div>
        <div class="health-check-list">
            <?php foreach ($checks as $check): ?>
            <div class="health-check-row"><span class="health-dot is-<?php echo htmlspecialchars($check['status']); ?>"></span><div><strong><?php echo htmlspecialchars($check['name']); ?></strong><small><?php echo htmlspecialchars($check['detail']); ?></small></div><span class="health-value"><?php echo htmlspecialchars($check['value']); ?></span></div>
            <?php endforeach; ?>
        </div>
    </section>
</div>
<style>
.health-page{max-width:1440px}.health-overview{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:22px 24px;margin-bottom:18px;border:1px solid #dbe3ee;border-radius:16px;background:#fff;box-shadow:0 8px 24px rgba(15,23,42,.04)}.health-overview>div:first-child{display:grid;grid-template-columns:14px auto;column-gap:12px;align-items:center}.health-overview strong{font-size:20px;color:#172033}.health-overview p{grid-column:2;margin:3px 0 0;color:#64748b;font-size:12px}.health-signal{width:12px;height:12px;border-radius:50%;background:#10b981;box-shadow:0 0 0 5px #d1fae5}.health-warning .health-signal{background:#f59e0b;box-shadow:0 0 0 5px #fef3c7}.health-error .health-signal{background:#ef4444;box-shadow:0 0 0 5px #fee2e2}.health-totals{display:flex;gap:22px;color:#64748b;font-size:12px}.health-totals b{display:block;color:#1e293b;font-size:19px}.health-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px;margin-bottom:18px}.health-card{padding:22px;border:1px solid #dfe6ef;border-radius:16px;background:#fff;box-shadow:0 8px 24px rgba(15,23,42,.04)}.health-card-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px;margin-bottom:20px}.health-card h2{margin:2px 0 0;font-size:17px;color:#1e293b}.health-eyebrow{font-size:10px;letter-spacing:.14em;font-weight:800;color:#94a3b8}.health-pill{padding:5px 9px;border-radius:999px;font-size:11px;font-weight:800}.health-pill.is-ok{color:#047857;background:#ecfdf5}.health-pill.is-warning{color:#b45309;background:#fffbeb}.health-pill.is-error{color:#b91c1c;background:#fef2f2}.health-metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.health-metrics div{padding:14px;border-radius:12px;background:#f8fafc}.health-metrics small{display:block;color:#94a3b8;font-size:11px}.health-metrics strong{display:block;margin-top:5px;color:#25324a;font-size:15px;overflow-wrap:anywhere}.health-note{margin:16px 0 0;color:#64748b;font-size:12px;line-height:1.8}.health-actions{display:flex;align-items:center;gap:14px;margin-top:16px;color:#94a3b8;font-size:11px}.health-actions a:not(.btn){color:#64748b;text-decoration:none}.health-cache-value{font-size:36px;font-weight:800;color:#2563eb}.health-cache-value small{font-size:13px;color:#64748b}.health-checks-card{padding-bottom:8px}.health-muted{color:#94a3b8;font-size:11px}.health-check-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));column-gap:28px}.health-check-row{display:grid;grid-template-columns:10px minmax(0,1fr) auto;gap:12px;align-items:center;padding:14px 2px;border-top:1px solid #edf1f6}.health-dot{width:8px;height:8px;border-radius:50%;background:#10b981}.health-dot.is-warning{background:#f59e0b}.health-dot.is-error{background:#ef4444}.health-check-row strong{display:block;color:#334155;font-size:13px}.health-check-row small{display:block;margin-top:2px;color:#94a3b8;font-size:10px}.health-value{color:#475569;font-size:12px;font-weight:700;text-align:right}@media(max-width:1100px){.health-grid{grid-template-columns:1fr 1fr}.health-scheduler-card{grid-column:1/-1}}@media(max-width:900px){.health-grid,.health-check-list{grid-template-columns:1fr}.health-scheduler-card{grid-column:auto}.health-overview{align-items:flex-start;flex-direction:column}.health-metrics{grid-template-columns:1fr}.health-totals{width:100%;justify-content:space-between}}
</style>
