<?php
/**
 * Legacy MU Plugin Cleaner
 *
 * Automatically detects and removes legacy MU plugins generated by the old
 * integration system. This ensures a clean migration from MU-based to
 * standard plugin-based integrations.
 *
 * @package FleekDash
 * @since 2.2.0
 */

namespace FleekDash\Core;

defined('ABSPATH') || exit;

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

class LegacyMUPluginCleaner
{
    /**
     * Option key to track if cleanup has been completed
     */
    const CLEANUP_COMPLETED_OPTION = 'fleekdash_mu_cleanup_completed';

    /**
     * Cleanup version - increment when cleanup logic changes
     */
    const CLEANUP_VERSION = '2.2.0';

    /**
     * Initialize the cleaner
     * Runs automatically on plugin load
     */
    public static function init(): void
    {
        // Run cleanup once per version
        \add_action('plugins_loaded', [self::class, 'maybe_cleanup'], 5);
    }

    /**
     * Check if cleanup is needed and run it
     */
    public static function maybe_cleanup(): void
    {
        $last_cleanup_version = \get_option(self::CLEANUP_COMPLETED_OPTION, '0.0.0');

        // Only run if cleanup hasn't been done for this version
        if (version_compare($last_cleanup_version, self::CLEANUP_VERSION, '>=')) {
            return;
        }

        self::cleanup();
    }

    /**
     * Clean up legacy MU plugins
     *
     * @return array Result with cleaned files count
     */
    public static function cleanup(): array
    {
        $mu_plugins_dir = WPMU_PLUGIN_DIR;

        if (!is_dir($mu_plugins_dir)) {
            // No mu-plugins directory, nothing to clean
            \update_option(self::CLEANUP_COMPLETED_OPTION, self::CLEANUP_VERSION);
            return ['cleaned' => 0, 'files' => []];
        }

        $cleaned_files = [];
        $cleaned_dirs = [];

        // 1. Remove legacy loader file
        $loader_file = $mu_plugins_dir . '/fleekdash-integrations-loader.php';
        if (file_exists($loader_file)) {
            if (self::is_fleekdash_mu_file($loader_file)) {
                if (@unlink($loader_file)) {
                    $cleaned_files[] = $loader_file;
                    fleekdash_log_info('[FleekDash] Removed legacy MU loader: ' . basename($loader_file));
                }
            }
        }

        // 2. Remove legacy integration directories (fleekdash-*)
        $mu_dirs = glob($mu_plugins_dir . '/fleekdash-*', GLOB_ONLYDIR);
        if ($mu_dirs) {
            foreach ($mu_dirs as $mu_dir) {
                $dir_name = basename($mu_dir);

                // Skip if it's not a legacy integration directory
                if (!self::is_legacy_integration_dir($dir_name)) {
                    continue;
                }

                // Remove directory recursively
                if (self::remove_directory($mu_dir)) {
                    $cleaned_dirs[] = $mu_dir;
                    fleekdash_log_info('[FleekDash] Removed legacy MU integration directory: ' . $dir_name);
                }
            }
        }

        // 3. Remove legacy single-file MU plugins (fleekdash-*.php)
        $mu_files = glob($mu_plugins_dir . '/fleekdash-*.php');
        if ($mu_files) {
            foreach ($mu_files as $mu_file) {
                $file_name = basename($mu_file);

                // Skip the loader (already handled)
                if ($file_name === 'fleekdash-integrations-loader.php') {
                    continue;
                }

                // Check if it's a legacy integration file
                if (self::is_fleekdash_mu_file($mu_file)) {
                    if (@unlink($mu_file)) {
                        $cleaned_files[] = $mu_file;
                        fleekdash_log_info('[FleekDash] Removed legacy MU plugin file: ' . $file_name);
                    }
                }
            }
        }

        $total_cleaned = count($cleaned_files) + count($cleaned_dirs);

        // Mark cleanup as completed
        \update_option(self::CLEANUP_COMPLETED_OPTION, self::CLEANUP_VERSION);

        if ($total_cleaned > 0) {
            fleekdash_log_info(sprintf(
                '[FleekDash] Legacy MU plugin cleanup completed: %d file(s) and %d directory(ies) removed',
                count($cleaned_files),
                count($cleaned_dirs)
            ));
        }

        return [
            'cleaned' => $total_cleaned,
            'files' => $cleaned_files,
            'directories' => $cleaned_dirs,
        ];
    }

    /**
     * Check if a file is a FleekDash legacy MU plugin
     *
     * @param string $file_path File path
     * @return bool True if it's a legacy FleekDash MU file
     */
    private static function is_fleekdash_mu_file(string $file_path): bool
    {
        if (!file_exists($file_path)) {
            return false;
        }

        $content = @file_get_contents($file_path);
        if ($content === false) {
            return false;
        }

        // Check for legacy markers
        $legacy_markers = [
            'FLEEKDASH_MU_LOADER',
            'fleekdash_is_integration_enabled',
            'fleekdash_register_mu_integration',
            'FleekDash Integrations MU Plugin Loader',
            'Auto-generated MU plugin',
        ];

        foreach ($legacy_markers as $marker) {
            if (strpos($content, $marker) !== false) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if a directory is a legacy integration directory
     *
     * @param string $dir_name Directory name
     * @return bool True if it's a legacy integration directory
     */
    private static function is_legacy_integration_dir(string $dir_name): bool
    {
        // Legacy pattern: fleekdash-{integration_id}
        if (strpos($dir_name, 'fleekdash-') !== 0) {
            return false;
        }

        // Check if it contains Integration.php (legacy structure)
        $integration_file = WPMU_PLUGIN_DIR . '/' . $dir_name . '/Integration.php';
        if (file_exists($integration_file)) {
            // Check if it's a legacy integration (has old markers)
            $content = @file_get_contents($integration_file);
            if ($content && (
                strpos($content, 'FleekDashV2\\Integrations') !== false ||
                strpos($content, 'fleekdash/integrations') !== false ||
                strpos($content, 'require_once \'/Integration.php\'') !== false
            )) {
                return true;
            }
        }

        // Also check for the main plugin file pattern
        $plugin_file = WPMU_PLUGIN_DIR . '/' . $dir_name . '/fleekdash-' . str_replace('fleekdash-', '', $dir_name) . '.php';
        if (file_exists($plugin_file) && self::is_fleekdash_mu_file($plugin_file)) {
            return true;
        }

        return false;
    }

    /**
     * Remove directory recursively
     *
     * @param string $dir Directory path
     * @return bool True if removed successfully
     */
    private static function remove_directory(string $dir): bool
    {
        if (!is_dir($dir)) {
            return false;
        }

        // Use WordPress filesystem API if available
        if (function_exists('WP_Filesystem')) {
            global $wp_filesystem;
            if (WP_Filesystem()) {
                return $wp_filesystem->rmdir($dir, true);
            }
        }

        // Fallback: manual recursive deletion
        $files = array_diff(scandir($dir), ['.', '..']);

        foreach ($files as $file) {
            $path = $dir . '/' . $file;
            if (is_dir($path)) {
                self::remove_directory($path);
            } else {
                @unlink($path);
            }
        }

        return @rmdir($dir);
    }

    /**
     * Force cleanup (for manual execution)
     * Useful for troubleshooting or immediate cleanup
     *
     * @return array Cleanup result
     */
    public static function force_cleanup(): array
    {
        // Reset cleanup flag to force re-execution
        \delete_option(self::CLEANUP_COMPLETED_OPTION);
        return self::cleanup();
    }

    /**
     * Get cleanup status
     *
     * @return array Status information
     */
    public static function get_status(): array
    {
        $mu_plugins_dir = WPMU_PLUGIN_DIR;
        $legacy_files = [];
        $legacy_dirs = [];

        if (is_dir($mu_plugins_dir)) {
            // Check for loader
            $loader_file = $mu_plugins_dir . '/fleekdash-integrations-loader.php';
            if (file_exists($loader_file) && self::is_fleekdash_mu_file($loader_file)) {
                $legacy_files[] = basename($loader_file);
            }

            // Check for integration directories
            $mu_dirs = glob($mu_plugins_dir . '/fleekdash-*', GLOB_ONLYDIR);
            if ($mu_dirs) {
                foreach ($mu_dirs as $mu_dir) {
                    if (self::is_legacy_integration_dir(basename($mu_dir))) {
                        $legacy_dirs[] = basename($mu_dir);
                    }
                }
            }

            // Check for single-file plugins
            $mu_files = glob($mu_plugins_dir . '/fleekdash-*.php');
            if ($mu_files) {
                foreach ($mu_files as $mu_file) {
                    if (basename($mu_file) !== 'fleekdash-integrations-loader.php' &&
                        self::is_fleekdash_mu_file($mu_file)) {
                        $legacy_files[] = basename($mu_file);
                    }
                }
            }
        }

        return [
            'cleanup_completed' => \get_option(self::CLEANUP_COMPLETED_OPTION, '0.0.0'),
            'cleanup_version' => self::CLEANUP_VERSION,
            'legacy_files_found' => count($legacy_files),
            'legacy_dirs_found' => count($legacy_dirs),
            'legacy_files' => $legacy_files,
            'legacy_dirs' => $legacy_dirs,
            'needs_cleanup' => count($legacy_files) > 0 || count($legacy_dirs) > 0,
        ];
    }
}
