<?php declare(strict_types=1);

/**
 * Universal & Composable Server Requirements Checker for Kirby CMS & rehaPro
 *
 * Validated against official Kirby documentation:
 * https://getkirby.com/docs/reference/system/requirements
 *
 * Usage:
 *   CLI: php requirements.php
 *   Web: https://example.com/requirements.php
 */

// =============================================================================
// 1. PROJECT CONFIGURATION & COMPOSABLES (Customize Here)
// =============================================================================

$config = [
    'project_name' => 'Kirby 5',

    // Compose requirements from pre-built modular presets
    'presets' => [
        // 1. Web Server, OS POSIX Compatibility & URL Rewriting
        Presets::webServer(
            requirePosix: true,
            checkRewrite: true
        ),

        // 2. Core Kirby 5 & PHP Runtime Requirements
        Presets::phpRuntime(
            minVersion: '8.5.0',
            memoryLimit: '256M',
            maxExecutionTime: 60,
            uploadMaxFilesize: '32M',
            requiredExtensions: [
                'ctype', 'curl', 'dom', 'filter', 'hash', 'iconv',
                'json', 'libxml', 'mbstring', 'openssl', 'simplexml'
            ],
            recommendedExtensions: [
                'fileinfo', 'intl', 'exif', 'sodium', 'opcache'
            ],
            optionalExtensions: [
                'zlib'
            ]
        ),

        // 3. Graphics & Image Manipulation (GD or ImageMagick)
        Presets::graphics(
            driver: 'im', // 'im' (ImageMagick CLI), 'gd' (PHP GD extension), or 'any'
            requireExif: true
        ),

        // 4. SQLite & Loupe Search Engine (Comment out if project uses MySQL or flat search)
        Presets::sqliteSearch(
            minSqliteVersion: '3.35.0'
        ),

        // 5. Document, PDF & Excel Processing (PhpSpreadsheet / TC-PDF)
        Presets::documentProcessing(
            excel: true,
            pdf: true
        ),

        // 6. CLI, Task Runners & Deployer Capabilities
        Presets::cliCapabilities(
            requireExec: true,
            requireProcOpen: true
        ),

        // 7. Filesystem Permissions & Shared Storage
        Presets::permissions(
            paths: [
                'public/media' => 'Generated thumbnails and Panel media assets',
                'content'      => 'Content flat-files and metadata',
                'var/cache'   => 'Page and query cache directory (optional)',
            ]
        ),
    ],

    // Optional project-specific custom checks
    'custom_checks' => [],
];

// =============================================================================
// 2. CHECK REGISTRY & MODEL
// =============================================================================

final class Check
{
    public function __construct(
        public string $title,
        public Closure $test,
        public string $failureMessage,
        public bool $fatal = true,
        public string|null $category = null
    ) {}

    public static function make(
        string $title,
        callable $test,
        string $failureMessage,
        bool $fatal = true,
        string|null $category = null
    ): self {
        return new self($title, Closure::fromCallable($test), $failureMessage, $fatal, $category);
    }
}

// =============================================================================
// 3. COMPOSABLE PRESETS
// =============================================================================

final class Presets
{
    /**
     * Web server, OS POSIX compatibility, and URL rewriting checks
     */
    public static function webServer(
        bool $requirePosix = true,
        bool $checkRewrite = true
    ): array {
        $checks = [];

        // 1. POSIX Operating System Compatibility
        if ($requirePosix) {
            $checks[] = Check::make(
                'Operating System: POSIX Compatible',
                function () {
                    // Kirby requires POSIX compatibility (Linux, macOS, BSD, Unix)
                    if (PHP_OS_FAMILY === 'Windows') {
                        return false;
                    }
                    return DIRECTORY_SEPARATOR === '/';
                },
                'Kirby requires a POSIX-compatible operating system (Linux, macOS, Unix). Current OS: ' . PHP_OS,
                category: 'Web Server & OS'
            );
        }

        // 2. Web Server Detection & Compatibility
        $checks[] = Check::make(
            'Web Server Compatibility',
            function () {
                if (PHP_SAPI === 'cli') {
                    return true;
                }

                $server = (string)($_SERVER['SERVER_SOFTWARE'] ?? '');
                if ($server === '') {
                    return true;
                }

                $supported = ['apache', 'nginx', 'caddy', 'litespeed', 'openlitespeed', 'ddev', 'development server'];
                $serverLower = strtolower($server);

                foreach ($supported as $s) {
                    if (str_contains($serverLower, $s)) {
                        return true;
                    }
                }

                return false;
            },
            'Web server detected: ' . ($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown') . '. Supported web servers include Apache, Nginx, Caddy, LiteSpeed, or PHP built-in server.',
            fatal: false,
            category: 'Web Server & OS'
        );

        // 3. URL Rewriting Support
        if ($checkRewrite) {
            $checks[] = Check::make(
                'URL Rewriting Support',
                function () {
                    if (PHP_SAPI === 'cli') {
                        return true;
                    }

                    // Check Apache mod_rewrite if apache_get_modules is available
                    if (function_exists('apache_get_modules')) {
                        return in_array('mod_rewrite', apache_get_modules(), true);
                    }

                    // Check if server set HTTP_MOD_REWRITE or REDIRECT_HTTP_MOD_REWRITE
                    if (
                        isset($_SERVER['HTTP_MOD_REWRITE']) ||
                        isset($_SERVER['REDIRECT_HTTP_MOD_REWRITE']) ||
                        isset($_SERVER['KIRBY_REWRITE'])
                    ) {
                        return true;
                    }

                    // Nginx/Caddy route via try_files / php-fpm (assumed functional if reaching PHP)
                    $serverLower = strtolower((string)($_SERVER['SERVER_SOFTWARE'] ?? ''));
                    if (str_contains($serverLower, 'nginx') || str_contains($serverLower, 'caddy') || str_contains($serverLower, 'development server')) {
                        return true;
                    }

                    // For Apache without apache_get_modules, verify .htaccess existence
                    if (str_contains($serverLower, 'apache')) {
                        return file_exists(__DIR__ . '/public/.htaccess') || file_exists(__DIR__ . '/public/.htaccess');
                    }

                    return true;
                },
                'URL rewriting must be enabled on the web server (e.g. Apache mod_rewrite, Nginx try_files, or Caddy router).',
                fatal: false,
                category: 'Web Server & OS'
            );
        }

        return $checks;
    }

    /**
     * Core PHP runtime, version, limits and extensions
     */
    public static function phpRuntime(
        string $minVersion = '8.3.0',
        string $memoryLimit = '256M',
        int $maxExecutionTime = 30,
        string $uploadMaxFilesize = '32M',
        array $requiredExtensions = [],
        array $recommendedExtensions = [],
        array $optionalExtensions = []
    ): array {
        $checks = [];

        // PHP Version Check
        $checks[] = Check::make(
            "PHP Version (>= {$minVersion})",
            fn() => version_compare(PHP_VERSION, $minVersion, '>='),
            "Current PHP version is " . PHP_VERSION . " ({$minVersion}+ required).",
            category: 'PHP Runtime'
        );

        $descriptions = [
            'ctype'     => 'Character type checking (Kirby core)',
            'curl'      => 'HTTP client and remote requests (Kirby core)',
            'dom'       => 'DOM/XML manipulation and HTML parsing (Kirby core)',
            'filter'    => 'Data filtering and sanitization (Kirby core)',
            'hash'      => 'Cryptographic hashing (Kirby core)',
            'iconv'     => 'Character set conversion (Kirby core)',
            'json'      => 'JSON serialization and API processing (Kirby core)',
            'libxml'    => 'Core XML handling (Kirby core)',
            'mbstring'  => 'Multibyte string handling (Kirby core)',
            'openssl'   => 'Secure communication and token generation (Kirby core)',
            'simplexml' => 'SimpleXML structure parsing (Kirby core)',
            'fileinfo'  => 'MIME type detection for file uploads',
            'intl'      => 'Internationalization, date formatting, and search tokenization',
            'exif'      => 'EXIF metadata and image orientation',
            'sodium'    => 'Modern cryptographic security',
            'opcache'   => 'PHP bytecode caching for production performance',
            'zlib'      => 'Stream compression and SVGZ sanitization',
            'apcu'      => 'APCu in-memory cache driver',
            'memcached' => 'Memcached distributed cache driver',
            'zip'       => 'ZIP archive creation and export extraction',
        ];

        // Required Extensions (Kirby 5 core requirements)
        foreach ($requiredExtensions as $ext) {
            $desc = $descriptions[$ext] ?? 'Kirby core requirement';
            $checks[] = Check::make(
                "PHP Extension: ext-{$ext}",
                fn() => extension_loaded($ext),
                "Required extension '{$ext}' is not installed or enabled ({$desc}).",
                category: 'Required Extensions'
            );
        }

        // Recommended Extensions
        foreach ($recommendedExtensions as $ext) {
            $desc = $descriptions[$ext] ?? 'Recommended enhancement';
            $checks[] = Check::make(
                "PHP Extension: ext-{$ext} (recommended)",
                fn() => extension_loaded($ext),
                "Recommended extension '{$ext}' is missing ({$desc}).",
                fatal: false,
                category: 'Recommended Extensions'
            );
        }

        // Optional Extensions
        foreach ($optionalExtensions as $ext) {
            $desc = $descriptions[$ext] ?? 'Optional feature';
            $checks[] = Check::make(
                "PHP Extension: ext-{$ext} (optional)",
                fn() => extension_loaded($ext),
                "Optional extension '{$ext}' is not loaded ({$desc}).",
                fatal: false,
                category: 'Optional Extensions'
            );
        }

        // Memory Limit
        $checks[] = Check::make(
            "memory_limit (>= {$memoryLimit})",
            fn() => Util::parseBytes((string)ini_get('memory_limit')) >= Util::parseBytes($memoryLimit),
            "Current memory_limit is " . ini_get('memory_limit') . " (recommended: {$memoryLimit}).",
            fatal: false,
            category: 'PHP Runtime'
        );

        // Max Execution Time
        if ($maxExecutionTime > 0) {
            $checks[] = Check::make(
                "max_execution_time (>= {$maxExecutionTime}s)",
                function () use ($maxExecutionTime) {
                    $val = (int)ini_get('max_execution_time');
                    return $val === 0 || $val >= $maxExecutionTime;
                },
                "Current max_execution_time is " . ini_get('max_execution_time') . "s (recommended: {$maxExecutionTime}s).",
                fatal: false,
                category: 'PHP Runtime'
            );
        }

        // Upload Max Filesize
        if ($uploadMaxFilesize !== '') {
            $checks[] = Check::make(
                "upload_max_filesize (>= {$uploadMaxFilesize})",
                fn() => Util::parseBytes((string)ini_get('upload_max_filesize')) >= Util::parseBytes($uploadMaxFilesize),
                "Current upload_max_filesize is " . ini_get('upload_max_filesize') . " (recommended: {$uploadMaxFilesize}).",
                fatal: false,
                category: 'PHP Runtime'
            );
        }

        return $checks;
    }

    /**
     * Image manipulation (GD / ImageMagick)
     */
    public static function graphics(string $driver = 'im', bool $requireExif = true): array
    {
        $checks = [];

        if ($driver === 'gd') {
            $checks[] = Check::make(
                'Graphics: ext-gd',
                fn() => extension_loaded('gd'),
                'PHP GD extension is required for thumbnail and image processing.',
                category: 'Graphics & Media'
            );
        } elseif ($driver === 'im') {
            $checks[] = Check::make(
                'Graphics: ImageMagick CLI Binary (convert / magick)',
                function () {
                    $disabled = array_map('trim', explode(',', (string)ini_get('disable_functions')));
                    if (in_array('exec', $disabled, true) || in_array('shell_exec', $disabled, true)) {
                        return false;
                    }
                    $bin = trim((string)@shell_exec('command -v convert || command -v magick'));
                    return $bin !== '';
                },
                'ImageMagick binary ("convert" or "magick") was not found in $PATH or exec() is blocked in disable_functions.',
                fatal: true,
                category: 'Graphics & Media'
            );
        } else {
            // 'any' driver (Kirby docs: either GD or ImageMagick)
            $checks[] = Check::make(
                'Graphics: GD or ImageMagick available',
                function () {
                    if (extension_loaded('gd')) {
                        return true;
                    }
                    $disabled = array_map('trim', explode(',', (string)ini_get('disable_functions')));
                    if (!in_array('exec', $disabled, true) && !in_array('shell_exec', $disabled, true)) {
                        $bin = trim((string)@shell_exec('command -v convert || command -v magick'));
                        return $bin !== '';
                    }
                    return false;
                },
                'Either the GD PHP extension or ImageMagick CLI binary is required for image resizing.',
                category: 'Graphics & Media'
            );
        }

        if ($requireExif) {
            $checks[] = Check::make(
                'Graphics: ext-exif (photo orientation)',
                fn() => extension_loaded('exif'),
                'exif extension is recommended for automatic photo rotation and metadata extraction.',
                fatal: false,
                category: 'Graphics & Media'
            );
        }

        return $checks;
    }

    /**
     * SQLite PDO and library version checks (e.g. for Loupe Search)
     */
    public static function sqliteSearch(string $minSqliteVersion = '3.35.0'): array
    {
        return [
            Check::make(
                'Search Engine: ext-pdo_sqlite',
                fn() => extension_loaded('pdo_sqlite'),
                'pdo_sqlite extension is required for SQLite-based full-text indexing (Loupe).',
                category: 'Search Engine (Loupe)'
            ),
            Check::make(
                "Search Engine: SQLite C-Library (>= {$minSqliteVersion})",
                function () use ($minSqliteVersion) {
                    if (!extension_loaded('pdo_sqlite')) {
                        return false;
                    }
                    try {
                        $pdo = new PDO('sqlite::memory:');
                        $version = (string)$pdo->query('SELECT sqlite_version()')->fetchColumn();
                        return version_compare($version, $minSqliteVersion, '>=');
                    } catch (Throwable) {
                        return false;
                    }
                },
                "SQLite library >= {$minSqliteVersion} is required by full-text search engine (Loupe).",
                category: 'Search Engine (Loupe)'
            ),
        ];
    }

    /**
     * Document, PDF and Spreadsheet export extensions
     */
    public static function documentProcessing(bool $excel = true, bool $pdf = true): array
    {
        $checks = [];

        if ($excel) {
            $excelExts = ['zip', 'xml', 'xmlreader', 'xmlwriter', 'simplexml', 'dom'];
            foreach ($excelExts as $ext) {
                $checks[] = Check::make(
                    "Spreadsheet Processing: ext-{$ext}",
                    fn() => extension_loaded($ext),
                    "Extension '{$ext}' is required for Excel/CSV import and export (PhpSpreadsheet).",
                    category: 'Document & Export Processing'
                );
            }
        }

        if ($pdf) {
            $checks[] = Check::make(
                'PDF Processing: ext-zlib',
                fn() => extension_loaded('zlib'),
                'zlib extension is required for PDF stream compression and TC-PDF output.',
                category: 'Document & Export Processing'
            );
        }

        return $checks;
    }

    /**
     * CLI and Process execution functions
     */
    public static function cliCapabilities(bool $requireExec = true, bool $requireProcOpen = true): array
    {
        $checks = [];
        $disabled = array_map('trim', explode(',', (string)ini_get('disable_functions')));

        if ($requireExec) {
            $checks[] = Check::make(
                'Process Execution: exec() enabled',
                fn() => !in_array('exec', $disabled, true) && function_exists('exec'),
                "'exec' function is disabled in php.ini (required for CLI utilities and ImageMagick).",
                category: 'CLI & Process Execution'
            );
        }

        if ($requireProcOpen) {
            $checks[] = Check::make(
                'Process Execution: proc_open() enabled',
                fn() => !in_array('proc_open', $disabled, true) && function_exists('proc_open'),
                "'proc_open' function is disabled in php.ini (required for Kirby CLI and Deployer).",
                category: 'CLI & Process Execution'
            );
        }

        return $checks;
    }

    /**
     * Filesystem and Directory Write Permissions (Non-intrusive: checks target or existing parent)
     */
    public static function permissions(array $paths): array
    {
        $checks = [];

        foreach ($paths as $path => $desc) {
            $checks[] = Check::make(
                "Writable Directory: {$path}",
                function () use ($path) {
                    $fullPath = __DIR__ . '/' . ltrim($path, '/');
                    if (!file_exists($fullPath)) {
                        $parent = dirname($fullPath);
                        while (!file_exists($parent) && $parent !== dirname($parent)) {
                            $parent = dirname($parent);
                        }
                        return is_dir($parent) && is_writable($parent);
                    }
                    return is_dir($fullPath) && is_writable($fullPath);
                },
                "Directory '{$path}' ({$desc}) does not exist or its parent directory is not writable by the web server user.",
                fatal: false,
                category: 'Filesystem Permissions'
            );
        }

        return $checks;
    }
}

// =============================================================================
// 4. UTILITY HELPERS
// =============================================================================

final class Util
{
    public static function parseBytes(string $val): int
    {
        $val = trim($val);
        if ($val === '' || $val === '-1') {
            return PHP_INT_MAX;
        }
        $last = strtolower($val[strlen($val) - 1]);
        $num = (int)$val;
        return match ($last) {
            'g' => $num * 1024 * 1024 * 1024,
            'm' => $num * 1024 * 1024,
            'k' => $num * 1024,
            default => (int)$val,
        };
    }
}

// =============================================================================
// 5. RUNNER & OUTPUT RENDERER
// =============================================================================

$allChecks = [];
foreach ($config['presets'] as $presetChecks) {
    foreach ($presetChecks as $c) {
        $allChecks[] = $c;
    }
}
foreach ($config['custom_checks'] as $c) {
    $allChecks[] = $c;
}

$results = [
    'passed' => [],
    'warnings' => [],
    'errors' => [],
];

foreach ($allChecks as $check) {
    try {
        $passed = ($check->test)();
    } catch (Throwable $e) {
        $passed = false;
    }

    if ($passed) {
        $results['passed'][] = [
            'title' => $check->title,
            'category' => $check->category,
        ];
    } elseif ($check->fatal) {
        $results['errors'][] = [
            'title' => $check->title,
            'message' => $check->failureMessage,
            'category' => $check->category,
        ];
    } else {
        $results['warnings'][] = [
            'title' => $check->title,
            'message' => $check->failureMessage,
            'category' => $check->category,
        ];
    }
}

$isCli = PHP_SAPI === 'cli';

if ($isCli) {
    echo "\n========================================================\n";
    echo "  " . $config['project_name'] . " - Requirements Check\n";
    echo "========================================================\n\n";

    echo "Environment:\n";
    echo "  - PHP: " . PHP_VERSION . " (" . PHP_SAPI . ")\n";
    echo "  - OS:  " . PHP_OS . " (" . PHP_OS_FAMILY . ")\n";
    if (isset($_SERVER['SERVER_SOFTWARE'])) {
        echo "  - Web: " . $_SERVER['SERVER_SOFTWARE'] . "\n";
    }
    echo "\nChecks:\n";

    foreach ($results['passed'] as $item) {
        echo "\033[32m [OK]   \033[0m {$item['title']}\n";
    }
    foreach ($results['warnings'] as $item) {
        echo "\033[33m [WARN] \033[0m {$item['title']}: {$item['message']}\n";
    }
    foreach ($results['errors'] as $item) {
        echo "\033[31m [FAIL] \033[0m {$item['title']}: {$item['message']}\n";
    }

    echo "\n--------------------------------------------------------\n";
    echo "Summary: " . count($results['passed']) . " passed, "
        . count($results['warnings']) . " warnings, "
        . count($results['errors']) . " errors.\n";
    echo "--------------------------------------------------------\n\n";

    exit(count($results['errors']) > 0 ? 1 : 0);
} else {
    header('Content-Type: text/html; charset=utf-8');
    $serverSoftware = $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown SAPI (' . PHP_SAPI . ')';
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title><?= htmlspecialchars($config['project_name']) ?> Requirements</title>
        <style>
            :root {
                --bg: #f8fafc;
                --card-bg: #ffffff;
                --text: #0f172a;
                --muted: #64748b;
                --border: #e2e8f0;
                --ok-bg: #f0fdf4;
                --ok-text: #166534;
                --ok-border: #22c55e;
                --warn-bg: #fefce8;
                --warn-text: #854d0e;
                --warn-border: #eab308;
                --fail-bg: #fef2f2;
                --fail-text: #991b1b;
                --fail-border: #ef4444;
            }
            body {
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
                padding: 2.5rem 1rem;
                background: var(--bg);
                color: var(--text);
                line-height: 1.5;
                margin: 0;
            }
            .container {
                max-width: 860px;
                margin: 0 auto;
                background: var(--card-bg);
                padding: 2.5rem;
                border-radius: 12px;
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
                border: 1px solid var(--border);
            }
            .header {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                margin-bottom: 2rem;
                border-bottom: 1px solid var(--border);
                padding-bottom: 1.5rem;
            }
            h1 {
                margin: 0 0 0.5rem 0;
                font-size: 1.6rem;
                font-weight: 700;
                letter-spacing: -0.02em;
            }
            .env-meta {
                display: flex;
                flex-wrap: wrap;
                gap: 0.75rem;
                font-size: 0.85rem;
                color: var(--muted);
            }
            .badge {
                display: inline-block;
                padding: 0.25rem 0.6rem;
                border-radius: 9999px;
                background: #f1f5f9;
                border: 1px solid var(--border);
                font-weight: 500;
            }
            .badge-status-ok { background: #dcfce7; color: #15803d; border-color: #bbf7d0; }
            .badge-status-fail { background: #fee2e2; color: #b91c1c; border-color: #fecaca; }
            .badge-status-warn { background: #fef9c3; color: #a16207; border-color: #fef08a; }

            .item {
                display: flex;
                align-items: flex-start;
                justify-content: space-between;
                padding: 0.75rem 1rem;
                margin-bottom: 0.5rem;
                border-radius: 8px;
                font-size: 0.9rem;
                border-left: 4px solid;
            }
            .item-content { flex: 1; }
            .item-title { font-weight: 600; }
            .item-msg { margin-top: 0.25rem; font-size: 0.85rem; color: var(--muted); }
            .ok { background: var(--ok-bg); color: var(--ok-text); border-color: var(--ok-border); }
            .warn { background: var(--warn-bg); color: var(--warn-text); border-color: var(--warn-border); }
            .fail { background: var(--fail-bg); color: var(--fail-text); border-color: var(--fail-border); }

            .summary {
                margin-top: 2rem;
                padding-top: 1.25rem;
                border-top: 1px solid var(--border);
                display: flex;
                gap: 1.5rem;
                font-weight: 600;
                font-size: 0.95rem;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <div>
                    <h1><?= htmlspecialchars($config['project_name']) ?></h1>
                    <div class="env-meta">
                        <span class="badge">PHP <?= htmlspecialchars(PHP_VERSION) ?></span>
                        <span class="badge">OS: <?= htmlspecialchars(PHP_OS_FAMILY) ?></span>
                        <span class="badge">Server: <?= htmlspecialchars($serverSoftware) ?></span>
                    </div>
                </div>
                <div>
                    <?php if (count($results['errors']) === 0 && count($results['warnings']) === 0): ?>
                        <span class="badge badge-status-ok" style="font-size: 1rem; padding: 0.5rem 1rem;">Ready for Production</span>
                    <?php elseif (count($results['errors']) === 0): ?>
                        <span class="badge badge-status-warn" style="font-size: 1rem; padding: 0.5rem 1rem;">Passed with Warnings</span>
                    <?php else: ?>
                        <span class="badge badge-status-fail" style="font-size: 1rem; padding: 0.5rem 1rem;">Requirements Missing</span>
                    <?php endif; ?>
                </div>
            </div>

            <?php if (!empty($results['errors'])): ?>
                <h3 style="color: var(--fail-text); margin: 1.5rem 0 0.75rem;">Failed Requirements (<?= count($results['errors']) ?>)</h3>
                <?php foreach ($results['errors'] as $item): ?>
                    <div class="item fail">
                        <div class="item-content">
                            <div class="item-title">[FAIL] <?= htmlspecialchars($item['title']) ?></div>
                            <div class="item-msg"><?= htmlspecialchars($item['message']) ?></div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>

            <?php if (!empty($results['warnings'])): ?>
                <h3 style="color: var(--warn-text); margin: 1.5rem 0 0.75rem;">Warnings & Recommendations (<?= count($results['warnings']) ?>)</h3>
                <?php foreach ($results['warnings'] as $item): ?>
                    <div class="item warn">
                        <div class="item-content">
                            <div class="item-title">[WARN] <?= htmlspecialchars($item['title']) ?></div>
                            <div class="item-msg"><?= htmlspecialchars($item['message']) ?></div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>

            <h3 style="color: var(--ok-text); margin: 1.5rem 0 0.75rem;">Passed Checks (<?= count($results['passed']) ?>)</h3>
            <?php foreach ($results['passed'] as $item): ?>
                <div class="item ok">
                    <div class="item-content">
                        <div class="item-title">[OK] <?= htmlspecialchars($item['title']) ?></div>
                    </div>
                </div>
            <?php endforeach; ?>

            <div class="summary">
                <span style="color: #15803d;"><?= count($results['passed']) ?> Passed</span>
                <span style="color: #a16207;"><?= count($results['warnings']) ?> Warnings</span>
                <span style="color: #b91c1c;"><?= count($results['errors']) ?> Errors</span>
            </div>
        </div>
    </body>
    </html>
    <?php
}
