<?php
declare(strict_types=1);

class Performance
{
    private static float $start = 0.0;
    private static bool $cacheHandled = false;
    private static ?string $cacheFile = null;

    public static function boot(): void
    {
        self::$start = microtime(true);
        if (!headers_sent()) {
            header('X-Content-Type-Options: nosniff');
            header('Referrer-Policy: strict-origin-when-cross-origin');
        }
    }

    public static function startPublicCache(
        bool $enabled,
        int $ttlSeconds,
        bool $isGetRequest,
        bool $isAuthenticated,
        bool $isSensitivePage,
        string $requestUri
    ): void {
        if (!$enabled || !$isGetRequest || $isAuthenticated || $isSensitivePage) {
            return;
        }

        $ttlSeconds = max(5, $ttlSeconds);
        $cacheDir = __DIR__ . '/../../storage/cache/pages';
        if (!is_dir($cacheDir)) {
            @mkdir($cacheDir, 0777, true);
        }

        self::$cacheFile = $cacheDir . DIRECTORY_SEPARATOR . sha1($requestUri) . '.html';
        if (is_file(self::$cacheFile) && (time() - (int)@filemtime(self::$cacheFile)) < $ttlSeconds) {
            self::$cacheHandled = true;
            readfile(self::$cacheFile);
            exit;
        }
    }

    public static function storePublicCache(bool $enabled): void
    {
        if (!$enabled || self::$cacheHandled || self::$cacheFile === null || headers_sent()) {
            return;
        }

        $content = (string)ob_get_contents();
        if ($content === '') {
            return;
        }

        @file_put_contents(self::$cacheFile, $content);
    }

    public static function isSensitiveScript(string $scriptName): bool
    {
        $name = strtolower(basename($scriptName));
        $sensitive = [
            'cart.php',
            'checkout.php',
            'payment-callback.php',
            'profile.php',
            'login.php',
            'logout.php',
            'register.php',
            'order-tracking.php',
        ];

        return in_array($name, $sensitive, true);
    }

    public static function finish(string $routeTag = 'unknown'): void
    {
        self::storePublicCache(true);
        $elapsedMs = (microtime(true) - self::$start) * 1000;
        if (!headers_sent()) {
            header('X-Response-Time-Ms: ' . number_format($elapsedMs, 2, '.', ''));
        }

        if ($elapsedMs >= 800) {
            $logDir = __DIR__ . '/../../storage/logs';
            if (!is_dir($logDir)) {
                @mkdir($logDir, 0777, true);
            }
            $line = sprintf("[%s] route=%s response_ms=%.2f\n", date('c'), $routeTag, $elapsedMs);
            @file_put_contents($logDir . '/slow-requests.log', $line, FILE_APPEND);
        }
    }
}
