<?php

/**
 * System REST API Controller
 *
 * Handles system information endpoints
 *
 * @package ProRank\SEO\Core\RestApi
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\RestApi;

use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


/**
 * System controller class
 */


class SystemController extends BaseController {
    
    /**
     * Rest base
     *
     * @var string
     */
    protected $rest_base = 'system';
    
    /**
     * Register routes
     *
     * @return void
     */
    public function register_routes(): void {
        // System compatibility check
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/compatibility',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'get_compatibility'],
                    'permission_callback' => [$this, 'check_permission'],
                ],
            ]
        );

        // SEO plugins check
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/seo-plugins',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'get_seo_plugins'],
                    'permission_callback' => [$this, 'check_permission'],
                ],
            ]
        );

        // System info for wizard
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/info',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'get_system_info'],
                    'permission_callback' => [$this, 'check_permission'],
                ],
            ]
        );

        // Competitors check for wizard
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/competitors',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'get_competitors'],
                    'permission_callback' => [$this, 'check_permission'],
                ],
            ]
        );

        // Get active plugins
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/plugins',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'get_active_plugins'],
                    'permission_callback' => [$this, 'check_permission'],
                ],
            ]
        );
        
        // Check specific plugin
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/check-plugin/(?P<plugin>[a-zA-Z0-9_-]+)',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'check_plugin'],
                    'permission_callback' => [$this, 'check_permission'],
                    'args'                => [
                        'plugin' => [
                            'required'          => true,
                            'type'              => 'string',
                            'sanitize_callback' => 'sanitize_key',
                        ],
                    ],
                ],
            ]
        );
        
        // Flush rewrite rules
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/flush-rules',
            [
                [
                    'methods'             => WP_REST_Server::CREATABLE,
                    'callback'            => [$this, 'flush_rewrite_rules'],
                    'permission_callback' => [$this, 'check_permission'],
                ],
            ]
        );

        // Extract site basics from deactivated competitor plugins
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/competitor-site-data',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'get_competitor_site_data'],
                    'permission_callback' => [$this, 'check_permission'],
                ],
            ]
        );
    }
    
    /**
     * Get active plugins
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error
     */
    public function get_active_plugins(WP_REST_Request $request) {
        // Get active plugins
        $active_plugins = get_option('active_plugins', []);
        
        // For multisite, also check network active plugins
        if (is_multisite()) {
            $network_plugins = get_site_option('active_sitewide_plugins', []);
            if (is_array($network_plugins)) {
                $active_plugins = array_merge($active_plugins, array_keys($network_plugins));
            }
        }
        
        return new WP_REST_Response([
            'success' => true,
            'data'    => array_values(array_unique($active_plugins)),
        ]);
    }

    /**
     * Check if a plugin is currently active (including network-active on multisite).
     *
     * @param string $plugin_file Plugin main file path.
     * @return bool
     */
    private function is_plugin_currently_active(string $plugin_file): bool {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        if (is_plugin_active($plugin_file)) {
            return true;
        }

        if (is_multisite() && function_exists('is_plugin_active_for_network')) {
            return is_plugin_active_for_network($plugin_file);
        }

        return false;
    }
    
    /**
     * Check if a specific plugin is active
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error
     */
    public function check_plugin(WP_REST_Request $request) {
        // Ensure plugin functions are available
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $plugin_slug = $request->get_param('plugin');

        // Map common plugin slugs to their main files
        $plugin_map = [
            'woocommerce'      => 'woocommerce/woocommerce.php',
            'elementor'        => 'elementor/elementor.php',
            'wpml'            => 'sitepress-multilingual-cms/sitepress.php',
            'polylang'        => 'polylang/polylang.php',
            'acf'             => 'advanced-custom-fields/acf.php',
            'acf-pro'         => 'advanced-custom-fields-pro/acf.php',
            'yoast'           => 'wordpress-seo/wp-seo.php',
            'rankmath'        => 'seo-by-rank-math/rank-math.php',
            'aioseo'          => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
        ];
        
        // Get the plugin file
        $plugin_file = $plugin_map[$plugin_slug] ?? $plugin_slug;
        
        // Check if plugin is active
        $is_active = is_plugin_active($plugin_file);
        
        // For multisite, also check network activation
        if (!$is_active && is_multisite()) {
            $is_active = is_plugin_active_for_network($plugin_file);
        }
        
        // Additional checks for specific plugins
        $additional_checks = [
            'woocommerce' => class_exists('WooCommerce'),
            'elementor' => defined('ELEMENTOR_VERSION'),
            'wpml' => defined('ICL_SITEPRESS_VERSION'),
            'polylang' => defined('POLYLANG_VERSION'),
            'acf' => class_exists('ACF'),
            'yoast' => defined('WPSEO_VERSION'),
            'rankmath' => defined('RANK_MATH_VERSION'),
            'aioseo' => defined('AIOSEO_VERSION'),
        ];
        
        // If primary check failed, try additional check
        if (!$is_active && isset($additional_checks[$plugin_slug])) {
            $is_active = $additional_checks[$plugin_slug];
        }
        
        return new WP_REST_Response([
            'success' => true,
            'data'    => [
                'plugin'    => $plugin_slug,
                'is_active' => $is_active,
                'file'      => $plugin_file,
            ],
        ]);
    }
    
    /**
     * Flush rewrite rules
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error
     */
    public function flush_rewrite_rules(WP_REST_Request $request) {
        // Flush the rewrite rules
        flush_rewrite_rules();

        // Also clear any ProRank SEO specific flush flags
        delete_option('prorank_seo_flush_rules');

        return new WP_REST_Response([
            'success' => true,
            'message' => __('Rewrite rules have been flushed successfully.', 'prorank-seo'),
        ]);
    }

    /**
     * Get system compatibility information
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error
     */
    public function get_compatibility(WP_REST_Request $request) {
        global $wpdb;

        // WordPress version check
        $wp_version = get_bloginfo('version');
        $wp_required = '5.8';
        $wp_compatible = version_compare($wp_version, $wp_required, '>=');

        // PHP version check
        $php_version = phpversion();
        $php_required = '7.4';
        $php_compatible = version_compare($php_version, $php_required, '>=');

        // PHP extensions check
        $required_extensions = ['json', 'mbstring', 'curl'];
        $missing_extensions = [];
        foreach ($required_extensions as $ext) {
            if (!extension_loaded($ext)) {
                $missing_extensions[] = $ext;
            }
        }
        $extensions_compatible = empty($missing_extensions);

        // Memory limit check
        $memory_limit = ini_get('memory_limit');
        $memory_bytes = $this->convert_to_bytes($memory_limit);
        $memory_required = 64 * 1024 * 1024; // 64MB minimum
        $memory_compatible = $memory_bytes >= $memory_required || $memory_bytes === -1; // -1 means no limit

        // Overall compatibility
        $is_compatible = $wp_compatible && $php_compatible && $extensions_compatible && $memory_compatible;

        return new WP_REST_Response([
            'success' => true,
            'data' => [
                'compatible' => $is_compatible,
                'wordpress' => [
                    'version' => $wp_version,
                    'required' => $wp_required,
                    'compatible' => $wp_compatible,
                ],
                'php' => [
                    'version' => $php_version,
                    'required' => $php_required,
                    'compatible' => $php_compatible,
                ],
                'extensions' => [
                    'required' => $required_extensions,
                    'missing' => $missing_extensions,
                    'compatible' => $extensions_compatible,
                ],
                'memory' => [
                    'limit' => $memory_limit,
                    'required' => '64M',
                    'compatible' => $memory_compatible,
                ],
            ],
        ]);
    }

    /**
     * Get active SEO plugins that might conflict
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error
     */
    public function get_seo_plugins(WP_REST_Request $request) {
        // Ensure plugin functions are available
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        // List of known SEO and optimization plugins
        $seo_plugins = [
            [
                'slug' => 'yoast',
                'name' => 'Yoast SEO',
                'file' => 'wordpress-seo/wp-seo.php',
                'constant' => 'WPSEO_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'yoast-premium',
                'name' => 'Yoast SEO Premium',
                'file' => 'wordpress-seo-premium/wp-seo-premium.php',
                'constant' => 'WPSEO_PREMIUM_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'yoast-local',
                'name' => 'Yoast Local SEO',
                'file' => 'wpseo-local/wpseo-local.php',
                'constant' => 'WPSEO_LOCAL_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'yoast-video',
                'name' => 'Yoast Video SEO',
                'file' => 'wpseo-video/wpseo-video.php',
                'constant' => 'WPSEO_VIDEO_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'yoast-news',
                'name' => 'Yoast News SEO',
                'file' => 'wpseo-news/wpseo-news.php',
                'constant' => 'WPSEO_NEWS_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'yoast-woocommerce',
                'name' => 'Yoast WooCommerce SEO',
                'file' => 'woocommerce-seo/woocommerce-seo.php',
                'type' => 'seo',
            ],
            [
                'slug' => 'yoast-woocommerce-alt',
                'name' => 'Yoast WooCommerce SEO',
                'file' => 'wpseo-woocommerce/wpseo-woocommerce.php',
                'type' => 'seo',
            ],
            [
                'slug' => 'rankmath',
                'name' => 'Rank Math SEO',
                'file' => 'seo-by-rank-math/rank-math.php',
                'constant' => 'RANK_MATH_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'rankmath-pro',
                'name' => 'Rank Math SEO Pro',
                'file' => 'seo-by-rank-math-pro/rank-math-pro.php',
                'constant' => 'RANK_MATH_PRO_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'aioseo',
                'name' => 'All in One SEO',
                'file' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
                'constant' => 'AIOSEO_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'aioseo-pro',
                'name' => 'All in One SEO Pro',
                'file' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
                'constant' => 'AIOSEO_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'seopress',
                'name' => 'SEOPress',
                'file' => 'wp-seopress/seopress.php',
                'constant' => 'SEOPRESS_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'seopress-pro',
                'name' => 'SEOPress Pro',
                'file' => 'wp-seopress-pro/seopress-pro.php',
                'constant' => 'SEOPRESS_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'squirrly',
                'name' => 'Squirrly SEO',
                'file' => 'squirrly-seo/squirrly.php',
                'class' => 'SQ_Classes_Helpers_Tools',
                'type' => 'seo',
            ],
            [
                'slug' => 'smartcrawl',
                'name' => 'SmartCrawl SEO',
                'file' => 'smartcrawl-seo/wpmu-dev-seo.php',
                'constant' => 'SMARTCRAWL_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'slim-seo',
                'name' => 'Slim SEO',
                'file' => 'slim-seo/slim-seo.php',
                'constant' => 'SLIM_SEO_VER',
                'type' => 'seo',
            ],
            [
                'slug' => 'the-seo-framework',
                'name' => 'The SEO Framework',
                'file' => 'autodescription/autodescription.php',
                'constant' => 'THE_SEO_FRAMEWORK_VERSION',
                'type' => 'seo',
            ],
            [
                'slug' => 'seokey',
                'name' => 'SEOKEY',
                'file' => 'seokey/seokey.php',
                'type' => 'seo',
            ],
            [
                'slug' => 'seo-ultimate',
                'name' => 'SEO Ultimate',
                'file' => 'seo-ultimate/seo-ultimate.php',
                'type' => 'seo',
            ],
            [
                'slug' => 'wp-meta-seo',
                'name' => 'WP Meta SEO',
                'file' => 'wp-meta-seo/wp-meta-seo.php',
                'type' => 'seo',
            ],
            [
                'slug' => 'premium-seo-pack',
                'name' => 'Premium SEO Pack',
                'file' => 'premium-seo-pack/index.php',
                'type' => 'seo',
            ],
            [
                'slug' => 'seo-booster',
                'name' => 'SEO Booster',
                'file' => 'seo-booster/seo-booster.php',
                'type' => 'seo',
            ],
            [
                'slug' => 'surerank',
                'name' => 'SureRank SEO',
                'file' => 'surerank/surerank.php',
                'type' => 'seo',
            ],
            [
                'slug' => 'wp-rocket',
                'name' => 'WP Rocket',
                'file' => 'wp-rocket/wp-rocket.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'litespeed-cache',
                'name' => 'LiteSpeed Cache',
                'file' => 'litespeed-cache/litespeed-cache.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'wp-super-cache',
                'name' => 'WP Super Cache',
                'file' => 'wp-super-cache/wp-cache.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'wp-fastest-cache',
                'name' => 'WP Fastest Cache',
                'file' => 'wp-fastest-cache/wpFastestCache.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'cache-enabler',
                'name' => 'Cache Enabler',
                'file' => 'cache-enabler/cache-enabler.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'autoptimize',
                'name' => 'Autoptimize',
                'file' => 'autoptimize/autoptimize.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'hummingbird',
                'name' => 'Hummingbird',
                'file' => 'hummingbird-performance/wp-hummingbird.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'siteground-optimizer',
                'name' => 'SiteGround Optimizer',
                'file' => 'sg-cachepress/sg-cachepress.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'nitropack',
                'name' => 'NitroPack',
                'file' => 'nitropack/nitropack.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'perfmatters',
                'name' => 'Perfmatters',
                'file' => 'perfmatters/perfmatters.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'flying-press',
                'name' => 'FlyingPress',
                'file' => 'flying-press/flying-press.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'asset-cleanup',
                'name' => 'Asset CleanUp',
                'file' => 'asset-cleanup/asset-cleanup.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'async-javascript',
                'name' => 'Async JavaScript',
                'file' => 'async-javascript/async-javascript.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'wp-optimize',
                'name' => 'WP-Optimize',
                'file' => 'wp-optimize/wp-optimize.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'breeze',
                'name' => 'Breeze',
                'file' => 'breeze/breeze.php',
                'type' => 'performance',
            ],
            [
                'slug' => 'shortpixel',
                'name' => 'ShortPixel Image Optimizer',
                'file' => 'shortpixel-image-optimiser/wp-shortpixel.php',
                'type' => 'image',
            ],
            [
                'slug' => 'imagify',
                'name' => 'Imagify',
                'file' => 'imagify/imagify.php',
                'type' => 'image',
            ],
            [
                'slug' => 'smush',
                'name' => 'Smush',
                'file' => 'wp-smushit/wp-smush.php',
                'type' => 'image',
            ],
            [
                'slug' => 'ewww',
                'name' => 'EWWW Image Optimizer',
                'file' => 'ewww-image-optimizer/ewww-image-optimizer.php',
                'type' => 'image',
            ],
            [
                'slug' => 'optimole',
                'name' => 'Optimole',
                'file' => 'optimole-wp/optimole-wp.php',
                'type' => 'image',
            ],
            [
                'slug' => 'tinypng',
                'name' => 'TinyPNG',
                'file' => 'tiny-compress-images/tiny-compress-images.php',
                'type' => 'image',
            ],
            [
                'slug' => 'webp-express',
                'name' => 'WebP Express',
                'file' => 'webp-express/webp-express.php',
                'type' => 'image',
            ],
            [
                'slug' => 'converter-for-media',
                'name' => 'Converter for Media',
                'file' => 'converter-for-media/converter-for-media.php',
                'type' => 'image',
            ],
            [
                'slug' => 'seo-optimized-images',
                'name' => 'SEO Optimized Images',
                'file' => 'seo-optimized-images/seo-optimized-images.php',
                'type' => 'image',
            ],
        ];

        $detected = [];
        $conflicts = [];

        foreach ($seo_plugins as $plugin) {
            $is_active = $this->is_plugin_currently_active($plugin['file']);

            if ($is_active) {
                $detected[] = [
                    'slug' => $plugin['slug'],
                    'name' => $plugin['name'],
                    'type' => $plugin['type'] ?? 'seo',
                    'active' => true,
                ];
                $conflicts[] = $plugin['name'];
            }
        }

        return new WP_REST_Response([
            'success' => true,
            'data' => [
                'detected' => $detected,
                'has_conflicts' => !empty($conflicts),
                'conflict_message' => !empty($conflicts)
                    ? sprintf(
/* translators: %1$: value */
                        __('The following SEO or performance optimization plugins are active and may conflict with ProRank SEO: %1$s. Consider deactivating them to avoid duplicate optimizations and other issues.', 'prorank-seo'),
                        implode(', ', $conflicts)
                    )
                    : null,
            ],
        ]);
    }

    /**
     * Convert memory string to bytes
     *
     * @param string $value Memory limit string (e.g., '128M')
     * @return int Memory in bytes
     */
    private function convert_to_bytes(string $value): int {
        $value = trim($value);
        $last = strtolower($value[strlen($value) - 1]);
        $value = (int) $value;

        switch ($last) {
            case 'g':
                $value *= 1024;
                // fall through
            case 'm':
                $value *= 1024;
                // fall through
            case 'k':
                $value *= 1024;
        }

        return $value;
    }

    /**
     * Get system info for wizard
     *
     * Returns system compatibility info in the format expected by frontend:
     * - wordpress: { version, compatible }
     * - php: { version, compatible }
     * - extensions: { status, missing }
     * - memory: { limit, available }
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error
     */
    public function get_system_info(WP_REST_Request $request) {
        // WordPress version check
        $wp_version = get_bloginfo('version');
        $wp_required = '5.8';
        $wp_compatible = version_compare($wp_version, $wp_required, '>=');

        // PHP version check
        $php_version = phpversion();
        $php_required = '7.4';
        $php_compatible = version_compare($php_version, $php_required, '>=');

        // PHP extensions check
        $required_extensions = ['json', 'mbstring', 'curl'];
        $missing_extensions = [];
        foreach ($required_extensions as $ext) {
            if (!extension_loaded($ext)) {
                $missing_extensions[] = $ext;
            }
        }
        $extensions_ok = empty($missing_extensions);

        // Memory limit check
        $memory_limit = ini_get('memory_limit');
        $memory_bytes = $this->convert_to_bytes($memory_limit);
        $memory_required = 64 * 1024 * 1024; // 64MB minimum
        $memory_available = $memory_bytes >= $memory_required || $memory_bytes === -1;

        // Return in the format expected by frontend
        return new WP_REST_Response([
            'wordpress' => [
                'version' => $wp_version,
                'compatible' => $wp_compatible,
            ],
            'php' => [
                'version' => $php_version,
                'compatible' => $php_compatible,
            ],
            'extensions' => [
                'status' => $extensions_ok,
                'missing' => $missing_extensions,
            ],
            'memory' => [
                'limit' => $memory_limit === '-1' ? __('Unlimited', 'prorank-seo') : $memory_limit,
                'available' => $memory_available,
            ],
        ]);
    }

    /**
     * Get competitor SEO plugins for wizard
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error
     */
    public function get_competitors(WP_REST_Request $request) {
        // Ensure plugin functions are available
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        // List of known SEO plugins (competitors)
        $competitors = [
            [
                'slug' => 'yoast',
                'name' => 'Yoast SEO',
                'file' => 'wordpress-seo/wp-seo.php',
                'constant' => 'WPSEO_VERSION',
                'can_import' => true,
                'meta_prefix' => '_yoast_wpseo_',
            ],
            [
                'slug' => 'yoast-premium',
                'name' => 'Yoast SEO Premium',
                'file' => 'wordpress-seo-premium/wp-seo-premium.php',
                'constant' => 'WPSEO_PREMIUM_VERSION',
                'can_import' => true,
                'meta_prefix' => '_yoast_wpseo_',
            ],
            [
                'slug' => 'rankmath',
                'name' => 'Rank Math SEO',
                'file' => 'seo-by-rank-math/rank-math.php',
                'constant' => 'RANK_MATH_VERSION',
                'can_import' => true,
                'meta_prefix' => 'rank_math_',
            ],
            [
                'slug' => 'aioseo',
                'name' => 'All in One SEO',
                'file' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
                'constant' => 'AIOSEO_VERSION',
                'can_import' => true,
                'meta_prefix' => '_aioseo_',
            ],
            [
                'slug' => 'seopress',
                'name' => 'SEOPress',
                'file' => 'wp-seopress/seopress.php',
                'constant' => 'SEOPRESS_VERSION',
                'can_import' => true,
                'meta_prefix' => '_seopress_',
            ],
            [
                'slug' => 'squirrly',
                'name' => 'Squirrly SEO',
                'file' => 'squirrly-seo/squirrly.php',
                'class' => 'SQ_Classes_Helpers_Tools',
                'can_import' => false,
            ],
            [
                'slug' => 'smartcrawl',
                'name' => 'SmartCrawl SEO',
                'file' => 'smartcrawl-seo/wpmu-dev-seo.php',
                'constant' => 'SMARTCRAWL_VERSION',
                'can_import' => false,
            ],
            [
                'slug' => 'slim-seo',
                'name' => 'Slim SEO',
                'file' => 'slim-seo/slim-seo.php',
                'constant' => 'SLIM_SEO_VER',
                'can_import' => false,
            ],
            [
                'slug' => 'the-seo-framework',
                'name' => 'The SEO Framework',
                'file' => 'autodescription/autodescription.php',
                'constant' => 'THE_SEO_FRAMEWORK_VERSION',
                'can_import' => false,
            ],
            [
                'slug' => 'seokey',
                'name' => 'SEOKEY',
                'file' => 'seokey/seokey.php',
                'can_import' => false,
            ],
            [
                'slug' => 'seo-ultimate',
                'name' => 'SEO Ultimate',
                'file' => 'seo-ultimate/seo-ultimate.php',
                'can_import' => false,
            ],
            [
                'slug' => 'wp-meta-seo',
                'name' => 'WP Meta SEO',
                'file' => 'wp-meta-seo/wp-meta-seo.php',
                'can_import' => false,
            ],
            [
                'slug' => 'premium-seo-pack',
                'name' => 'Premium SEO Pack',
                'file' => 'premium-seo-pack/index.php',
                'can_import' => false,
            ],
            [
                'slug' => 'seo-booster',
                'name' => 'SEO Booster',
                'file' => 'seo-booster/seo-booster.php',
                'can_import' => false,
            ],
            [
                'slug' => 'seo-optimized-images',
                'name' => 'SEO Optimized Images',
                'file' => 'seo-optimized-images/seo-optimized-images.php',
                'can_import' => false,
            ],
            [
                'slug' => 'surerank',
                'name' => 'SureRank SEO',
                'file' => 'surerank/surerank.php',
                'can_import' => false,
            ],
        ];

        $detected = [];

        foreach ($competitors as $plugin) {
            // Wizard conflicts should only consider truly active plugins.
            // Do not infer active state from constants/classes to avoid false positives
            // after deactivation when plugin data remains in DB.
            $is_active = $this->is_plugin_currently_active($plugin['file']);

            if ($is_active) {
                $detected[] = [
                    'slug' => $plugin['slug'],
                    'name' => $plugin['name'],
                    'file' => $plugin['file'],
                    'active' => true,
                    'can_import' => $plugin['can_import'],
                ];
            }
        }

        // Second pass: detect deactivated plugins with residual SEO data in the database.
        // This catches cases where users deactivated the old plugin before running our import.
        global $wpdb;
        $detected_slugs = array_column($detected, 'slug');

        foreach ($competitors as $plugin) {
            // Only check importable plugins that weren't already detected as active
            if (empty($plugin['can_import']) || empty($plugin['meta_prefix'])) {
                continue;
            }
            if (in_array($plugin['slug'], $detected_slugs, true)) {
                continue;
            }
            // Yoast free and premium share the same meta_prefix — skip premium if free already detected
            if ($plugin['slug'] === 'yoast-premium' && in_array('yoast', $detected_slugs, true)) {
                continue;
            }
            if ($plugin['slug'] === 'yoast' && in_array('yoast-premium', $detected_slugs, true)) {
                continue;
            }

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            $has_data = (int) $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT 1 FROM {$wpdb->postmeta} WHERE meta_key LIKE %s LIMIT 1",
                    $wpdb->esc_like($plugin['meta_prefix']) . '%'
                )
            );

            if ($has_data) {
                $detected[] = [
                    'slug'       => $plugin['slug'],
                    'name'       => $plugin['name'],
                    'file'       => $plugin['file'],
                    'active'     => false,
                    'has_data'   => true,
                    'can_import' => true,
                ];
                $detected_slugs[] = $plugin['slug'];
            }
        }

        $active_competitors = array_values(array_filter($detected, static function ($plugin) {
            return !empty($plugin['active']);
        }));

        $inactive_importable = array_values(array_filter($detected, static function ($plugin) {
            return empty($plugin['active']) && !empty($plugin['has_data']) && !empty($plugin['can_import']);
        }));

        // Return in the format expected by frontend
        return new WP_REST_Response([
            'competitors' => $detected,
            'has_competitors' => !empty($detected),
            'has_active_conflicts' => !empty($active_competitors),
            'active_competitors' => $active_competitors,
            'inactive_importable' => $inactive_importable,
            'importable' => array_values(array_filter($detected, fn($p) => $p['can_import'])),
        ]);
    }

    /**
     * Extract site basics (site name, social profiles, verification codes, etc.)
     * from deactivated competitor SEO plugins' saved options.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response
     */
    public function get_competitor_site_data(WP_REST_Request $request): WP_REST_Response {
        $data   = [];
        $source = null;

        // Try Rank Math options first (most common migration path)
        $rm_titles  = get_option('rank-math-options-titles', []);
        $rm_general = get_option('rank-math-options-general', []);
        $rankmath_sources = [];
        if (is_array($rm_titles) && !empty($rm_titles)) {
            $rankmath_sources[] = $rm_titles;
        }
        if (is_array($rm_general) && !empty($rm_general)) {
            $rankmath_sources[] = $rm_general;
        }
        $rankmath_candidates = [
            get_option('rank_math_options_titles', []),
            get_option('rank_math_options_general', []),
            get_option('rank-math-options-social', []),
            get_option('rank_math_options_social', []),
            get_option('rank_math_google_analytic_options', []),
        ];
        foreach ($rankmath_candidates as $candidate) {
            if (is_array($candidate) && !empty($candidate)) {
                $rankmath_sources[] = $candidate;
            }
        }

        if (!empty($rm_titles) && is_array($rm_titles)) {
            $source = 'rankmath';

            // Site info
            if (!empty($rm_titles['website_name'])) {
                $data['site_name'] = sanitize_text_field($rm_titles['website_name']);
            }
            if (!empty($rm_titles['website_alternate_name'])) {
                $data['site_alternate_name'] = sanitize_text_field($rm_titles['website_alternate_name']);
            }
            if (!empty($rm_titles['title_separator'])) {
                $data['title_separator'] = sanitize_text_field($rm_titles['title_separator']);
            }

            // Organization / Knowledge Graph
            if (!empty($rm_titles['knowledgegraph_type'])) {
                $representation = $rm_titles['knowledgegraph_type'] === 'company' ? 'organization' : 'person';
                $data['org_or_person'] = $representation;
                $data['site_representation'] = $representation; // Backward compatibility.
            }
            if (!empty($rm_titles['knowledgegraph_name'])) {
                $org_name = sanitize_text_field($rm_titles['knowledgegraph_name']);
                $data['org_name'] = $org_name;
                $data['organization_name'] = $org_name; // Backward compatibility.
            }
            if (!empty($rm_titles['knowledgegraph_logo'])) {
                $org_logo = esc_url_raw($rm_titles['knowledgegraph_logo']);
                $data['org_logo'] = $org_logo;
                $data['organization_logo'] = $org_logo; // Backward compatibility.
            }

            // Social profiles
            if (!empty($rm_titles['social_url_facebook'])) {
                $data['facebook_page_url'] = esc_url_raw($rm_titles['social_url_facebook']);
            }
            if (!empty($rm_titles['social_url_twitter'])) {
                $data['twitter_username'] = sanitize_text_field(ltrim($rm_titles['social_url_twitter'], '@'));
            } elseif (!empty($rm_titles['twitter_author_names'])) {
                $data['twitter_username'] = sanitize_text_field(ltrim($rm_titles['twitter_author_names'], '@'));
            }
            if (!empty($rm_titles['social_url_linkedin'])) {
                $data['linkedin_url'] = esc_url_raw($rm_titles['social_url_linkedin']);
            }
            if (!empty($rm_titles['social_url_instagram'])) {
                $data['instagram_url'] = esc_url_raw($rm_titles['social_url_instagram']);
            }
            if (!empty($rm_titles['social_url_youtube'])) {
                $data['youtube_url'] = esc_url_raw($rm_titles['social_url_youtube']);
            }

            $data = array_merge($data, $this->extract_rankmath_verification_codes($rankmath_sources));
        }

        // Try Yoast options if Rank Math didn't yield site name
        if (empty($data['site_name'])) {
            $wpseo = get_option('wpseo', []);
            $wpseo_titles = get_option('wpseo_titles', []);
            $wpseo_social = get_option('wpseo_social', []);

            if (!empty($wpseo_titles) && is_array($wpseo_titles)) {
                if (empty($source)) {
                    $source = 'yoast';
                }
                if (!empty($wpseo_titles['website_name'])) {
                    $data['site_name'] = sanitize_text_field($wpseo_titles['website_name']);
                }
                if (!empty($wpseo_titles['alternate_website_name'])) {
                    $data['site_alternate_name'] = sanitize_text_field($wpseo_titles['alternate_website_name']);
                }
                if (!empty($wpseo_titles['separator'])) {
                    $data['title_separator'] = sanitize_text_field($wpseo_titles['separator']);
                }
                if (!empty($wpseo_titles['company_or_person'])) {
                    $representation = $wpseo_titles['company_or_person'] === 'company' ? 'organization' : 'person';
                    $data['org_or_person'] = $representation;
                    $data['site_representation'] = $representation; // Backward compatibility.
                }
                if (!empty($wpseo_titles['company_name'])) {
                    $org_name = sanitize_text_field($wpseo_titles['company_name']);
                    $data['org_name'] = $org_name;
                    $data['organization_name'] = $org_name; // Backward compatibility.
                }
                if (!empty($wpseo_titles['company_logo'])) {
                    $org_logo = esc_url_raw($wpseo_titles['company_logo']);
                    $data['org_logo'] = $org_logo;
                    $data['organization_logo'] = $org_logo; // Backward compatibility.
                }
            }

            if (!empty($wpseo_social) && is_array($wpseo_social)) {
                if (!empty($wpseo_social['facebook_site'])) {
                    $data['facebook_page_url'] = esc_url_raw($wpseo_social['facebook_site']);
                }
                if (!empty($wpseo_social['twitter_site'])) {
                    $data['twitter_username'] = sanitize_text_field(ltrim($wpseo_social['twitter_site'], '@'));
                }
                if (!empty($wpseo_social['linkedin_url'])) {
                    $data['linkedin_url'] = esc_url_raw($wpseo_social['linkedin_url']);
                }
                if (!empty($wpseo_social['instagram_url'])) {
                    $data['instagram_url'] = esc_url_raw($wpseo_social['instagram_url']);
                }
                if (!empty($wpseo_social['youtube_url'])) {
                    $data['youtube_url'] = esc_url_raw($wpseo_social['youtube_url']);
                }
            }

            // Yoast verification codes are stored in wpseo option
            if (!empty($wpseo) && is_array($wpseo)) {
                if (!empty($wpseo['googleverify'])) {
                    $data['google_verification'] = sanitize_text_field($wpseo['googleverify']);
                }
                if (!empty($wpseo['msverify'])) {
                    $data['bing_verification'] = sanitize_text_field($wpseo['msverify']);
                }
                if (!empty($wpseo['yandexverify'])) {
                    $data['yandex_verification'] = sanitize_text_field($wpseo['yandexverify']);
                }
            }
        }

        // Try AIOSEO options
        if (empty($data['site_name'])) {
            $aioseo = get_option('aioseo_options', '');
            if (!empty($aioseo)) {
                $aioseo = is_string($aioseo) ? json_decode($aioseo, true) : $aioseo;
                if (is_array($aioseo)) {
                    $source = $source ?: 'aioseo';
                    if (!empty($aioseo['searchAppearance']['global']['separator'])) {
                        $data['title_separator'] = sanitize_text_field($aioseo['searchAppearance']['global']['separator']);
                    }
                    if (!empty($aioseo['social']['facebook']['general']['facebookPageUrl'])) {
                        $data['facebook_page_url'] = esc_url_raw($aioseo['social']['facebook']['general']['facebookPageUrl']);
                    }
                    if (!empty($aioseo['social']['twitter']['general']['twitterCard'])) {
                        $data['twitter_username'] = sanitize_text_field($aioseo['social']['twitter']['general']['twitterCard']);
                    }
                }
            }
        }

        // Try SEOPress options
        if (empty($data['site_name'])) {
            $sp_titles = get_option('seopress_titles_option_name', []);
            $sp_social = get_option('seopress_social_option_name', []);

            if (!empty($sp_titles) && is_array($sp_titles)) {
                $source = $source ?: 'seopress';
                if (!empty($sp_titles['seopress_titles_sep'])) {
                    $data['title_separator'] = sanitize_text_field($sp_titles['seopress_titles_sep']);
                }
            }
            if (!empty($sp_social) && is_array($sp_social)) {
                if (!empty($sp_social['seopress_social_accounts_facebook'])) {
                    $data['facebook_page_url'] = esc_url_raw($sp_social['seopress_social_accounts_facebook']);
                }
                if (!empty($sp_social['seopress_social_accounts_twitter'])) {
                    $data['twitter_username'] = sanitize_text_field(ltrim($sp_social['seopress_social_accounts_twitter'], '@'));
                }
                if (!empty($sp_social['seopress_social_accounts_instagram'])) {
                    $data['instagram_url'] = esc_url_raw($sp_social['seopress_social_accounts_instagram']);
                }
                if (!empty($sp_social['seopress_social_accounts_linkedin'])) {
                    $data['linkedin_url'] = esc_url_raw($sp_social['seopress_social_accounts_linkedin']);
                }
                if (!empty($sp_social['seopress_social_accounts_youtube'])) {
                    $data['youtube_url'] = esc_url_raw($sp_social['seopress_social_accounts_youtube']);
                }
            }
        }

        // Fall back to WordPress core settings for site name
        if (empty($data['site_name'])) {
            $data['site_name'] = get_bloginfo('name');
        }
        if (empty($data['site_tagline'])) {
            $data['site_tagline'] = get_bloginfo('description');
        }

        // Try to get site logo from WordPress customizer
        $custom_logo_id = get_theme_mod('custom_logo');
        if (!empty($custom_logo_id) && empty($data['site_logo'])) {
            $logo_url = wp_get_attachment_image_url($custom_logo_id, 'full');
            if ($logo_url) {
                $data['site_logo'] = $logo_url;
            }
        }

        return new WP_REST_Response([
            'success' => true,
            'source'  => $source,
            'data'    => $data,
        ]);
    }

    /**
     * Extract Rank Math verification codes from known and nested key variants.
     *
     * @param array<int,array> $sources Candidate option arrays.
     * @return array<string,string>
     */
    private function extract_rankmath_verification_codes(array $sources): array {
        $result = [];

        $field_map = [
            'google_verification' => ['google_verify', 'google_verification', 'google_site_verification', 'google-site-verification'],
            'bing_verification' => ['bing_verify', 'bing_verification', 'msverify', 'ms_validate', 'msvalidate.01'],
            'baidu_verification' => ['baidu_verify', 'baidu_verification', 'baidu-site-verification'],
            'yandex_verification' => ['yandex_verify', 'yandex_verification', 'yandexverify', 'yandex-verification'],
            'pinterest_verification' => ['pinterest_verify', 'pinterest_verification', 'p:domain_verify', 'domain_verify'],
            'norton_verification' => ['norton_verify', 'norton_verification', 'norton-safeweb-site-verification'],
        ];

        foreach ($field_map as $target_key => $candidates) {
            foreach ($sources as $source) {
                $raw = $this->find_nested_setting_value($source, $candidates);
                if ($raw === null) {
                    continue;
                }
                $clean = $this->extract_verification_code($raw);
                if ($clean !== '') {
                    $result[$target_key] = $clean;
                    break;
                }
            }
        }

        return $result;
    }

    /**
     * Recursively search for candidate keys in nested arrays.
     *
     * @param mixed $payload Candidate payload.
     * @param array<int,string> $keys Candidate key names.
     * @return string|null
     */
    private function find_nested_setting_value($payload, array $keys): ?string {
        if (!is_array($payload)) {
            return null;
        }

        $normalized_candidates = array_map(
            fn(string $key): string => $this->normalize_competitor_key($key),
            $keys
        );

        foreach ($payload as $key => $value) {
            $normalized_key = $this->normalize_competitor_key((string) $key);
            if (in_array($normalized_key, $normalized_candidates, true) && is_scalar($value)) {
                $value = trim((string) $value);
                if ($value !== '') {
                    return $value;
                }
            }

            if (is_array($value)) {
                $nested = $this->find_nested_setting_value($value, $keys);
                if ($nested !== null && trim($nested) !== '') {
                    return $nested;
                }
            }
        }

        return null;
    }

    /**
     * Normalize keys for robust matching across plugins/versions.
     *
     * @param string $key Raw key.
     * @return string
     */
    private function normalize_competitor_key(string $key): string {
        $key = strtolower(trim($key));
        return str_replace(['-', '.', ':', ' '], '_', $key);
    }

    /**
     * Extract verification content from raw value or meta tag.
     *
     * @param string $raw Raw value.
     * @return string
     */
    private function extract_verification_code(string $raw): string {
        $raw = trim($raw);
        if ($raw === '') {
            return '';
        }

        if (stripos($raw, '<meta') !== false) {
            if (preg_match('/content\\s*=\\s*["\\\']([^"\\\']+)["\\\']/i', $raw, $m)) {
                $raw = $m[1];
            }
        }

        return sanitize_text_field($raw);
    }
}
