<?php

namespace FleekDash\Core;

defined('ABSPATH') || exit;

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

/**
 * Old Plugin Remover
 *
 * Automatically detects and removes the old "fleekdash-v2" plugin
 * when the new "fleekdash" plugin is activated to prevent confusion.
 *
 * @package FleekDash
 * @since 2.1.3
 */
class OldPluginRemover
{
    private const OLD_PLUGIN_TRANSIENT = 'fleekdash_remove_old_plugin';

    /**
     * Force deactivate plugin by directly modifying active_plugins option
     * This bypasses WordPress hooks and works even when the plugin is interfering
     *
     * @param string $pluginPath Plugin path (e.g., 'fleekdash-v2/fleekdash.php')
     */
    private static function forceDeactivatePlugin(string $pluginPath): bool
    {
        $activePlugins = \get_option('active_plugins', []);
        if (!\is_array($activePlugins)) {
            $activePlugins = [];
        }

        $pluginIndex = \array_search($pluginPath, $activePlugins, true);
        if ($pluginIndex === false) {
            return false;
        }

        unset($activePlugins[$pluginIndex]);
        $activePlugins = \array_values($activePlugins);
        \update_option('active_plugins', $activePlugins, false);

        if (\is_multisite()) {
            $networkPlugins = \get_site_option('active_sitewide_plugins', []);
            if (isset($networkPlugins[$pluginPath])) {
                unset($networkPlugins[$pluginPath]);
                \update_site_option('active_sitewide_plugins', $networkPlugins);
            }
        }

        \wp_cache_delete('plugins', 'plugins');

        return true;
    }

    /**
     * Only deactivate old plugin (fast, synchronous operation)
     * Used during activation hook to ensure old plugin doesn't interfere
     * Full removal happens async in ActivationRunner
     *
     * @return bool True if old plugin was found and deactivated
     */
    public static function deactivateOldPluginOnly(): bool
    {
        $deactivated = false;
        if (!\function_exists('get_plugins')) {
            PluginHelper::ensurePluginApiLoaded();
        }

        if (\function_exists('get_plugins')) {
            $oldPluginPath = self::detectOldPlugin();
            if ($oldPluginPath !== null && $oldPluginPath !== '' && \is_plugin_active($oldPluginPath)) {
                self::forceDeactivatePlugin($oldPluginPath);
                fleekdash_log_debug("FleekDash OldPluginRemover: Deactivated old plugin '{$oldPluginPath}' during activation.");
                \set_transient(self::OLD_PLUGIN_TRANSIENT, $oldPluginPath, 300);
                $deactivated = true;
            }
        }

        return $deactivated;
    }

    /**
     * Detect old plugin path
     *
     * @return string|null Old plugin path or null if not found
     */
    private static function detectOldPlugin(): ?string
    {
        if (!\function_exists('get_plugins')) {
            PluginHelper::ensurePluginApiLoaded();
        }

        if (!\function_exists('get_plugins')) {
            return null;
        }

        $allPlugins = \get_plugins();
        foreach ($allPlugins as $pluginPath => $pluginData) {
            $pluginDir = \dirname($pluginPath);
            $matchesV2Dir = $pluginDir === 'fleekdash-v2';
            $matchesV2Name = isset($pluginData['Name'])
                && \stripos($pluginData['Name'], 'FleekDash V2') !== false
                && $pluginDir !== 'fleekdash';

            if ($matchesV2Dir || $matchesV2Name) {
                return $pluginPath;
            }
        }

        return null;
    }

    /**
     * Detect and remove old fleekdash-v2 plugin automatically
     *
     * This function runs during activation to prevent confusion
     * when both plugins are installed simultaneously.
     */
    public static function removeOldPlugin(): void
    {
        $oldPluginPath = self::detectOldPlugin();
        if ($oldPluginPath === null || $oldPluginPath === '') {
            return;
        }

        if (\is_plugin_active($oldPluginPath)) {
            self::forceDeactivatePlugin($oldPluginPath);
            if (\function_exists('deactivate_plugins')) {
                @\deactivate_plugins($oldPluginPath, false, false);
            }
        }

        \set_transient(self::OLD_PLUGIN_TRANSIENT, $oldPluginPath, \HOUR_IN_SECONDS);
        fleekdash_log_debug("FleekDash OldPluginRemover: Legacy plugin flagged for removal ({$oldPluginPath}).");
    }

    private static function ensurePluginRemovalFunctionsLoaded(): void
    {
        PluginHelper::ensurePluginApiLoaded();
    }

    private static function deactivateLegacyPluginIfNeeded(string $oldPluginPath): void
    {
        if (!\is_plugin_active($oldPluginPath)) {
            return;
        }

        self::forceDeactivatePlugin($oldPluginPath);

        if (\function_exists('deactivate_plugins') && \is_plugin_active($oldPluginPath)) {
            @\deactivate_plugins($oldPluginPath, false, false);
        }
    }

    private static function flushPluginListCaches(): void
    {
        \wp_cache_delete('plugins', 'plugins');
        if (\function_exists('wp_cache_flush_group')) {
            \wp_cache_flush_group('plugins');
        }
    }

    private static function deleteLegacyDirectoryViaFilesystem(string $oldPluginPath): void
    {
        global $wp_filesystem;

        $pluginDirName = \dirname($oldPluginPath);
        if ($pluginDirName === 'fleekdash') {
            return;
        }

        $oldPluginDir = \WP_PLUGIN_DIR . '/' . $pluginDirName;
        if (!$wp_filesystem->exists($oldPluginDir)) {
            return;
        }

        $deleted = $wp_filesystem->delete($oldPluginDir, true);
        if ($deleted) {
            self::flushPluginListCaches();
            fleekdash_log_debug("FleekDash OldPluginRemover: Legacy plugin directory removed ({$oldPluginDir}).");

            return;
        }

        fleekdash_log_warn("FleekDash OldPluginRemover: Failed to delete legacy plugin directory: {$oldPluginDir}");
    }

    private static function deleteLegacyViaWordPressApi(string $oldPluginPath): void
    {
        if (!\function_exists('delete_plugins')) {
            return;
        }

        $result = \delete_plugins([$oldPluginPath]);
        if ($result === true) {
            \wp_cache_delete('plugins', 'plugins');
            fleekdash_log_debug('FleekDash OldPluginRemover: Legacy plugin removed via delete_plugins().');
        }
    }

    private static function removeLegacyPluginFiles(string $oldPluginPath): void
    {
        if (FilesystemHelper::safe_init()) {
            self::deleteLegacyDirectoryViaFilesystem($oldPluginPath);

            return;
        }

        self::deleteLegacyViaWordPressApi($oldPluginPath);
    }

    /**
     * Process scheduled plugin removal (fallback if activation removal fails)
     */
    public static function processScheduledRemoval(): void
    {
        $oldPluginPath = \get_transient(self::OLD_PLUGIN_TRANSIENT);
        if (!\is_string($oldPluginPath) || $oldPluginPath === '') {
            return;
        }

        \delete_transient(self::OLD_PLUGIN_TRANSIENT);
        self::ensurePluginRemovalFunctionsLoaded();

        try {
            self::deactivateLegacyPluginIfNeeded($oldPluginPath);
            self::removeLegacyPluginFiles($oldPluginPath);
        } catch (\Throwable $e) {
            fleekdash_log_error('FleekDash OldPluginRemover: Scheduled removal failed - ' . $e->getMessage());
        }
    }
}
