<?php
include_once __DIR__ . '/admin_path.php';
function static_cache_key(){
    $host = strtolower($_SERVER['HTTP_HOST'] ?? 'localhost');
    $uri = $_SERVER['REQUEST_URI'] ?? '/';
    return md5($host . '|' . $uri);
}

function static_cache_path(){
    return __DIR__ . '/../cache/static/' . static_cache_key() . '.html';
}

function static_cache_clear($maxAge = null){
    $dir = __DIR__ . '/../cache/static';
    if(!is_dir($dir)) return 0;
    $count = 0;
    foreach(glob($dir . '/*.html') as $file){
        if($maxAge !== null && time() - filemtime($file) <= (int)$maxAge) continue;
        if(@unlink($file)) $count++;
    }
    return $count;
}

function static_cache_start($ttl=600){
    $cfgFile = __DIR__ . '/../config/cache.php';
    if(is_file($cfgFile)){
        $cfg = include $cfgFile;
        if(empty($cfg['enabled'])) return;
        $ttl = max(60, intval($cfg['ttl'] ?? $ttl));
    }
    if(($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET') return;
    if(function_exists('cms_is_admin_request') && cms_is_admin_request()) return;
    $path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
    if(in_array($path, array('/sitemap.xml', '/sitemap.php'), true)) return;
    $file = static_cache_path();
    if(is_file($file) && time() - filemtime($file) < $ttl){
        readfile($file);
        exit;
    }
    ob_start(function($html) use ($file){
        if(!is_dir(dirname($file))) @mkdir(dirname($file), 0777, true);
        if(strlen($html) > 200) @file_put_contents($file, $html, LOCK_EX);
        return $html;
    });
}
