<?php

declare(strict_types=1);

namespace ShieldX\Support;

defined('ABSPATH') || exit;

/**
 * Clears only runtime cache entries for code SHIELD-X has just installed.
 *
 * A whole OPcache reset or a global object-cache flush can affect unrelated
 * applications on shared hosting. Directory-scoped invalidation keeps a
 * successful SHIELD-X installation visible on hosts that disable timestamp
 * validation without broad cache side effects.
 */
final class RuntimeCacheInvalidator
{
    public static function invalidateDirectory(string $directory): int
    {
        if (!function_exists('opcache_invalidate') || !is_dir($directory) || is_link($directory)) {
            return 0;
        }

        clearstatcache(true, $directory);
        $invalidated = 0;
        try {
            $iterator = new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS),
                \RecursiveIteratorIterator::LEAVES_ONLY
            );

            foreach ($iterator as $file) {
                if (!$file instanceof \SplFileInfo || !$file->isFile() || $file->isLink() || strtolower((string) $file->getExtension()) !== 'php') {
                    continue;
                }

                $path = $file->getPathname();
                if (!is_readable($path)) {
                    continue;
                }

                clearstatcache(true, $path);
                opcache_invalidate($path, true);
                $invalidated++;
            }
        } catch (\Throwable $error) {
            // OPcache is an optional performance layer. It must never make a
            // verified package install fail or cause a rollback by itself.
        }

        return $invalidated;
    }

    public static function clearPluginUpdateCache(): void
    {
        if (function_exists('delete_site_transient')) {
            delete_site_transient('update_plugins');

            return;
        }

        if (function_exists('delete_transient')) {
            delete_transient('update_plugins');
        }
    }
}
