<?php

namespace FleekDash\API\Plugins;

// Load debug helpers
if (!function_exists('fleekdash_log_info')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

/**
 * Plugin Helpers
 *
 * Utility methods for plugin operations
 *
 * @package FleekDash\API\Plugins
 */
class PluginHelpers
{
    /**
     * Recursively remove a directory and all its contents
     *
     * @param string $dir Directory path
     * @return bool Success status
     */
    public static function recursiveRmdir($dir)
    {
        if (!is_dir($dir)) {
            return false;
        }

        $files = array_diff(scandir($dir), array('.', '..'));

        foreach ($files as $file) {
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            if (is_dir($path)) {
                self::recursiveRmdir($path);
            } else {
                unlink($path);
            }
        }

        return rmdir($dir);
    }

    /**
     * Invalidate all plugin-related caches
     *
     * Clears transients, object cache, and triggers frontend cache invalidation
     */
    public static function invalidatePluginsCache()
    {
        // 🎯 CRITICAL: Set flag to trigger frontend cache invalidation
        \update_option('fleekdash_invalidate_frontend_cache', time(), false);

        // Do NOT delete update_plugins, update_themes, update_core transients!
        // These transients contain the UPDATE COUNTS displayed in the menu badge.
        // Deleting them causes wp_get_update_data() to return 0, hiding update notifications.
        // The plugin LIST cache is separate from update counts - we don't need to delete these.
        //
        // If we need to force-refresh update counts, WordPress cron handles that automatically,
        // or we should call wp_update_plugins() which updates the transient WITHOUT clearing first.

        // Clear only plugin-LIST related transients (not update counts)
        global $wpdb;
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
                '_transient_plugins_%'
            )
        );

        // Clear WordPress plugin cache (object cache only - not update transients)
        wp_cache_delete('plugins', 'plugins');
        wp_cache_delete('alloptions', 'options');

        // Fire action for other systems to hook into
        \do_action('fleekdash_plugins_cache_invalidated');

        fleekdash_log_info("FleekDash: Plugin cache invalidated - frontend will refresh on next load");
    }

    /**
     * Check permissions - always return true
     * Let WordPress capabilities handle access
     */
    public static function checkPermissions()
    {
        return true;
    }
}
