<?php
include __DIR__ . '/auth.php';
admin_check();
include __DIR__ . '/layout.php';
include __DIR__ . '/config_writer.php';
admin_header('静态缓存');

$dir = __DIR__ . '/../cache/static';
$configFile = __DIR__ . '/../config/cache.php';
$cfg = is_file($configFile) ? include $configFile : array('enabled'=>1,'ttl'=>600);
$msg = '';
if($_SERVER['REQUEST_METHOD']==='POST'){
    $action = $_POST['action'] ?? 'clear';
    if($action === 'save'){
        $cfg['enabled'] = !empty($_POST['enabled']) ? 1 : 0;
        $cfg['ttl'] = max(60, intval($_POST['ttl'] ?? 600));
        admin_export_php($configFile, $cfg);
        $msg = '缓存设置已保存';
        admin_oplog('save_static_cache_settings', 'ttl=' . $cfg['ttl']);
    }elseif($action === 'clear_expired'){
        $ttl = max(60, intval($cfg['ttl'] ?? 600));
        $n = 0;
        foreach(glob($dir.'/*.html') as $f){ if(time() - filemtime($f) > $ttl){ @unlink($f); $n++; } }
        $msg = '已清理过期缓存：' . $n . ' 个文件';
        admin_oplog('clear_expired_static_cache','');
    }else{
        foreach(glob($dir.'/*.html') as $f) @unlink($f);
        $msg = '静态缓存已全部清理';
        admin_oplog('clear_static_cache','');
    }
}
$cfg = is_file($configFile) ? include $configFile : $cfg;
$files = is_dir($dir) ? glob($dir.'/*.html') : array();
$size = 0; foreach($files as $f) $size += filesize($f);
?>
<?php if($msg): ?><div class="notice"><?php echo admin_h($msg); ?></div><?php endif; ?>
<div class="grid">
<div class="stat"><strong><?php echo count($files); ?></strong><span>缓存文件</span></div>
<div class="stat"><strong><?php echo round($size/1024,2); ?>KB</strong><span>缓存大小</span></div>
<div class="stat"><strong><?php echo intval(($cfg['ttl'] ?? 600)/60); ?>分钟</strong><span>保留时间</span></div>
</div>
<div class="card">
<h2>缓存设置</h2>
<p class="help">前台 GET 页面会按保留时间读取静态缓存；内容更新较频繁时建议设置 10-30 分钟，内容稳定时可设置更长。</p>
<form method="post" class="config-form">
<input type="hidden" name="action" value="save">
<div class="cache-setting-row">
<label class="cache-switch-pill"><input type="checkbox" name="enabled" value="1" <?php echo !empty($cfg['enabled'])?'checked':''; ?>><span>启用静态缓存</span></label>
<label class="cache-ttl-select"><span>缓存保留时间</span>
<select name="ttl">
<?php foreach(array(300=>'5分钟',600=>'10分钟',1800=>'30分钟',3600=>'1小时',21600=>'6小时',86400=>'1天',604800=>'7天') as $sec=>$label): ?>
<option value="<?php echo $sec; ?>" <?php echo intval($cfg['ttl'] ?? 600)===$sec?'selected':''; ?>><?php echo admin_h($label); ?></option>
<?php endforeach; ?>
</select>
</label>
<button>保存设置</button>
</div>
</form>
</div>
<div class="card">
<h2>缓存清理</h2>
<form method="post" style="display:inline-block" data-confirm="确定清理过期缓存吗？"><input type="hidden" name="action" value="clear_expired"><button>清理过期缓存</button></form>
<form method="post" style="display:inline-block" data-confirm="确定清理全部静态缓存吗？"><input type="hidden" name="action" value="clear"><button class="btn danger">清理全部缓存</button></form>
</div>
<?php admin_footer(); ?>
