<?php

declare(strict_types=1);

namespace WPUltimateSecurity\UltimateSecurity\Modules\Compatibility;

use WPUltimateSecurity\UltimateSecurity\Modules\Base\AbstractModule;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\PluginDetection;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;
use WPUltimateSecurity\UltimateSecurity\Modules\Compatibility\WooCommerceIntegration;
use WPUltimateSecurity\UltimateSecurity\Modules\Compatibility\PageBuildersIntegration;
use WPUltimateSecurity\UltimateSecurity\Modules\Compatibility\FormPluginsIntegration;
use WPUltimateSecurity\UltimateSecurity\Modules\Compatibility\CachePluginsIntegration;
use WPUltimateSecurity\UltimateSecurity\Modules\Compatibility\SEOPluginsIntegration;
use WPUltimateSecurity\UltimateSecurity\Modules\Compatibility\FlavorIntegration;

class CompatibilityManager extends AbstractModule
{
    public const MODULE_ID = 'system.compatibility';

    protected const VERSION = '2.0.0';

    /**
     * Get unique module identifier.
     */
    public static function getId(): string
    {
        return self::MODULE_ID;
    }

    /**
     * Get human-readable module name.
     */
    public static function getName(): string
    {
        return __('Compatibility Manager', 'ultimate-security');
    }

    /**
     * Get module domain.
     */
    public static function getDomain(): string
    {
        return 'system';
    }

    private static $instance = null;
    private $active_integrations = [];

    /**
     * Boot the module after registration.
     */
    public static function boot(): void
    {
        if (self::$instance === null) {
            self::$instance = new self();
            self::$instance->init();
        }
    }

    /**
     * Get singleton instance.
     */
    public static function getInstance(): ?self
    {
        return self::$instance;
    }

    public function init()
    {
        // Register compatibility hooks early
        add_action('plugins_loaded', [$this, 'load_integrations'], 20);

        // Add admin notice for conflicting plugins
        add_action('admin_notices', [$this, 'show_compatibility_notices']);

        // Filter for whitelisting AJAX actions
        add_filter('ultimate_security_skip_rate_limit', [$this, 'should_skip_rate_limit']);

        // Filter for whitelisting REST API namespaces
        add_filter('ultimate_security_skip_rest_protection', [$this, 'should_skip_rest_protection'], 10, 2);

        // AJAX handler for dismissing notices
        add_action('wp_ajax_ultimate_security_dismiss_notice', [$this, 'ajax_dismiss_notice']);
    }

    public function ajax_dismiss_notice()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Unauthorized', 'ultimate-security')]);
            return;
        }

        if (!check_ajax_referer('ultimate_security_dismiss_notice', '_wpnonce', false)) {
            wp_send_json_error(['message' => __('Invalid nonce', 'ultimate-security')]);
            return;
        }

        $notice = isset($_POST['notice']) ? sanitize_text_field(wp_unslash($_POST['notice'])) : '';

        if ($notice === 'compatibility') {
            update_user_meta(get_current_user_id(), 'ultimate_security_compatibility_notice_dismissed', time());
            wp_send_json_success(['message' => __('Notice dismissed', 'ultimate-security')]);
        }

        wp_send_json_error(['message' => __('Unknown notice', 'ultimate-security')]);
    }

    public function load_integrations()
    {
        // WooCommerce integration
        if (PluginDetection::is_woocommerce_active()) {
            $this->active_integrations['woocommerce'] = new WooCommerceIntegration();
        }

        // Page builder integrations
        if (PluginDetection::is_elementor_active()) {
            $this->active_integrations['elementor'] = new PageBuildersIntegration('elementor');
        }
        if (PluginDetection::is_divi_active()) {
            $this->active_integrations['divi'] = new PageBuildersIntegration('divi');
        }
        if (PluginDetection::is_avada_active()) {
            $this->active_integrations['avada'] = new PageBuildersIntegration('avada');
        }
        if (PluginDetection::is_wpbakery_active()) {
            $this->active_integrations['wpbakery'] = new PageBuildersIntegration('wpbakery');
        }
        if (PluginDetection::is_beaver_builder_active()) {
            $this->active_integrations['beaver_builder'] = new PageBuildersIntegration('beaver_builder');
        }

        // Form plugins integration
        if (PluginDetection::is_cf7_active() || PluginDetection::is_wpforms_active() || PluginDetection::is_gravity_forms_active()) {
            $this->active_integrations['forms'] = new FormPluginsIntegration();
        }

        // Cache plugins integration
        if (PluginDetection::is_litespeed_active() || PluginDetection::is_wp_super_cache_active() || PluginDetection::is_w3_total_cache_active()) {
            $this->active_integrations['cache'] = new CachePluginsIntegration();
        }

        // SEO plugins integration
        if (PluginDetection::is_yoast_active() || PluginDetection::is_rank_math_active()) {
            $this->active_integrations['seo'] = new SEOPluginsIntegration();
        }

        // Flavor theme integration
        if (PluginDetection::is_flavor_theme_active() || PluginDetection::is_flavor_studio_active()) {
            $this->active_integrations['flavor'] = new FlavorIntegration();
        }
    }

    public function show_compatibility_notices()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        $conflicts = PluginDetection::get_conflicting_security_plugins();
        if (empty($conflicts)) {
            return;
        }

        // Check if user has dismissed this notice
        $dismissed = get_user_meta(get_current_user_id(), 'ultimate_security_compatibility_notice_dismissed', true);
        if ($dismissed) {
            return;
        }

        $plugin_names = array_column($conflicts, 'name');
        $plugin_list = implode(', ', $plugin_names);

        echo '<div class="notice notice-warning is-dismissible" id="ultimate-security-compatibility-notice">';
        echo '<p><strong>' . esc_html__('Ultimate Security:', 'ultimate-security') . '</strong> ';
        echo sprintf(
            /* translators: %s: List of conflicting plugin names */
            esc_html__('We detected other security plugins (%s) that may conflict with Ultimate Security. Running multiple security plugins can cause conflicts and may slow down your site.', 'ultimate-security'),
            esc_html($plugin_list)
        );
        echo '</p>';
        echo '<p>';
        echo '<a href="' . esc_url(admin_url('admin.php?page=ultimate-security#/settings/more/compatibility')) . '" class="button button-primary">';
        echo esc_html__('Configure Compatibility', 'ultimate-security');
        echo '</a> ';
        echo '<a href="#" class="ultimate-security-dismiss-notice" data-notice="compatibility">';
        echo esc_html__('Dismiss', 'ultimate-security');
        echo '</a>';
        echo '</p>';
        echo '</div>';

        // Add JS to handle dismissal
        add_action('admin_footer', [$this, 'add_dismiss_notice_script']);
    }

    public function add_dismiss_notice_script()
    {
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                $('.ultimate-security-dismiss-notice').on('click', function(e) {
                    e.preventDefault();
                    var notice = $(this).data('notice');
                    $.post(ajaxurl, {
                        action: 'ultimate_security_dismiss_notice',
                        notice: notice,
                        _wpnonce: '<?php echo esc_js(wp_create_nonce('ultimate_security_dismiss_notice')); ?>'
                    });
                    $(this).closest('.notice').fadeOut();
                });
            });
        </script>
        <?php
    }

    public function should_skip_rate_limit($skip): bool
    {
        if ($skip) {
            return true;
        }

        // Skip for WooCommerce AJAX
        if (PluginDetection::is_woocommerce_ajax()) {
            return true;
        }

        // Skip for whitelisted AJAX actions
        if (PluginDetection::is_whitelisted_ajax_action()) {
            return true;
        }

        // Skip for page builder editors
        if (PluginDetection::is_any_page_builder_editor() && current_user_can('edit_posts')) {
            return true;
        }

        // Skip for Flavor requests
        if (PluginDetection::is_flavor_request() && current_user_can('edit_posts')) {
            return true;
        }

        return false;
    }

    public function should_skip_rest_protection($skip, $namespace): bool
    {
        if ($skip) {
            return true;
        }

        // Whitelist WooCommerce REST API
        if (PluginDetection::is_woocommerce_active() && strpos($namespace, 'wc/') === 0) {
            return true;
        }

        // Whitelist Elementor REST API
        if (PluginDetection::is_elementor_active() && strpos($namespace, 'elementor/') === 0) {
            return true;
        }

        // Whitelist WPForms REST API
        if (PluginDetection::is_wpforms_active() && strpos($namespace, 'wpforms/') === 0) {
            return true;
        }

        return false;
    }

    public function get_active_integrations(): array
    {
        return $this->active_integrations;
    }

    public static function get_compatibility_status(): array
    {
        return [
            'plugins' => [
                'woocommerce' => PluginDetection::is_woocommerce_active(),
                'elementor' => PluginDetection::is_elementor_active(),
                'divi' => PluginDetection::is_divi_active(),
                'avada' => PluginDetection::is_avada_active(),
                'wpbakery' => PluginDetection::is_wpbakery_active(),
                'beaver_builder' => PluginDetection::is_beaver_builder_active(),
                'cf7' => PluginDetection::is_cf7_active(),
                'wpforms' => PluginDetection::is_wpforms_active(),
                'gravity_forms' => PluginDetection::is_gravity_forms_active(),
                'litespeed' => PluginDetection::is_litespeed_active(),
                'yoast' => PluginDetection::is_yoast_active(),
                'rank_math' => PluginDetection::is_rank_math_active(),
                'wordfence' => PluginDetection::is_wordfence_active(),
                'memberpress' => PluginDetection::is_memberpress_active(),
                'learndash' => PluginDetection::is_learndash_active(),
            ],
            'themes' => [
                'divi' => PluginDetection::is_divi_theme_active(),
                'avada' => PluginDetection::is_avada_theme_active(),
                'astra' => PluginDetection::is_astra_theme_active(),
                'generatepress' => PluginDetection::is_generatepress_theme_active(),
                'flavor' => PluginDetection::is_flavor_theme_active(),
                'flavor_developer' => PluginDetection::is_flavor_developer_theme_active(),
                'flavor_starter' => PluginDetection::is_flavor_starter_theme_active(),
            ],
            'conflicts' => PluginDetection::get_conflicting_security_plugins(),
        ];
    }
}
