<?php

namespace Core\System;

class PageCache
{
    protected static string $cacheDir;
    protected static bool $enabled = true;

    public static function init(): void
    {
        self::$cacheDir = ROOT_PATH . '/storage/cache/pages';

        if (
            php_sapi_name() === 'cli' ||
            ($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET' ||
            !empty($_POST) ||
            !empty($_SESSION['admin_logged_in']) ||
            self::hasAuthCookie() ||
            self::isExcludedUri()
        ) {
            self::$enabled = false;
            return;
        }

        if (!is_dir(self::$cacheDir)) {
            @mkdir(self::$cacheDir, 0755, true);
        }

        $cacheFile = self::cacheFile();
        if (file_exists($cacheFile)) {
            header('X-Page-Cache: HIT');
            readfile($cacheFile);
            exit;
        }

        ob_start(function ($html) use ($cacheFile) {
            if (self::$enabled && is_string($html) && $html !== '') {
                @file_put_contents($cacheFile, $html, LOCK_EX);
            }
            return $html;
        });

        header('X-Page-Cache: MISS');
    }

    protected static function cacheFile(): string
    {
        $uri = (string)($_SERVER['REQUEST_URI'] ?? '/');
        $parts = parse_url($uri);
        $path = $parts['path'] ?? '/';
        $query = '';
        if (!empty($parts['query'])) {
            parse_str($parts['query'], $queryParams);
            ksort($queryParams);
            $query = http_build_query($queryParams);
        }

        $path = preg_replace('#/+#', '/', $path ?: '/');
        if ($path !== '/') {
            $path = rtrim($path, '/');
        }
        if ($path === '') {
            $path = '/';
        }

        $key = md5($path . '?' . $query);
        return self::$cacheDir . '/' . $key . '.html';
    }

    /**
     * Check if any authentication/session cookie exists that should bypass cache.
     * Analytics cookies (GA, GTM, Facebook Pixel) are intentionally ignored.
     */
    protected static function hasAuthCookie(): bool
    {
        // Session cookie name patterns that indicate an authenticated/stateful user
        $authCookiePatterns = [
            session_name(),          // PHP session cookie (PHPSESSID)
            'PHPSESSID',
            'admin_session',
            'logged_in',
            'auth_token',
            'remember_token',
        ];

        foreach ($_COOKIE as $name => $value) {
            foreach ($authCookiePatterns as $pattern) {
                if (stripos($name, $pattern) !== false) {
                    return true;
                }
            }
        }

        return false;
    }

    protected static function isExcludedUri(): bool
    {
        $uri = (string)($_SERVER['REQUEST_URI'] ?? '/');
        $parts = parse_url($uri);
        $path = $parts['path'] ?? '/';
        parse_str((string)($parts['query'] ?? ''), $query);

        $excludedPrefixes = [
            '/admin', '/api', '/cron', '/login', '/logout', '/order', '/install',
            '/product-review', '/submit-order', '/cart', '/checkout', '/lp',
        ];

        foreach ($excludedPrefixes as $prefix) {
            if ($path === $prefix || str_starts_with($path, $prefix . '/')) {
                return true;
            }
        }

        foreach (['page', 'sort', 'filter', 'search', 'q', 'utm_source', 'utm_medium', 'utm_campaign'] as $sensitiveKey) {
            if (array_key_exists($sensitiveKey, $query)) {
                return true;
            }
        }

        return false;
    }

    public static function clear(): void
    {
        self::$cacheDir = ROOT_PATH . '/storage/cache/pages';
        foreach (glob(self::$cacheDir . '/*.html') ?: [] as $file) {
            @unlink($file);
        }
    }
}
