<?php

namespace WPUltimateSecurity\UltimateSecurity\Modules\Compatibility;

use WPUltimateSecurity\UltimateSecurity\Support\Helpers\PluginDetection;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;

class FormPluginsIntegration
{
    public function __construct()
    {
        $this->init();
    }

    public function init()
    {
        // Skip rate limiting for form AJAX submissions
        add_filter('ultimate_security_rate_limit_check', [$this, 'skip_form_ajax'], 10, 2);

        // Handle CAPTCHA coordination
        add_filter('ultimate_security_captcha_check', [$this, 'coordinate_captcha']);

        // Whitelist form submission endpoints
        add_filter('ultimate_security_url_guard_check', [$this, 'whitelist_form_endpoints'], 10, 2);
    }

    public function skip_form_ajax($should_limit, $context): bool
    {
        if (!isset($_REQUEST['action'])) {
            return $should_limit;
        }

        $action = sanitize_text_field(wp_unslash($_REQUEST['action']));
        $whitelist = $this->get_all_form_ajax_whitelist();

        if (in_array($action, $whitelist, true)) {
            return false; // Don't rate limit
        }

        return $should_limit;
    }

    public function coordinate_captcha($should_add_captcha): bool
    {
        $options = Utils::ultimate_security_get_option();
        $skip_on_cf7 = $options['compatibility']['skip_captcha_on_cf7'] ?? '0';
        $skip_on_wpforms = $options['compatibility']['skip_captcha_on_wpforms'] ?? '0';
        $skip_on_gravity = $options['compatibility']['skip_captcha_on_gravity_forms'] ?? '0';

        // Skip our CAPTCHA if CF7 has its own and setting is enabled
        if ($skip_on_cf7 === '1' && PluginDetection::is_cf7_active() && PluginDetection::cf7_has_recaptcha()) {
            // Check if we're on a page with CF7 form
            if ($this->is_cf7_form_present()) {
                return false;
            }
        }

        // Skip for WPForms if enabled
        if ($skip_on_wpforms === '1' && PluginDetection::is_wpforms_active()) {
            if ($this->is_wpforms_form_present()) {
                return false;
            }
        }

        // Skip for Gravity Forms if enabled
        if ($skip_on_gravity === '1' && PluginDetection::is_gravity_forms_active()) {
            if ($this->is_gravity_form_present()) {
                return false;
            }
        }

        return $should_add_captcha;
    }

    public function whitelist_form_endpoints($should_block, $request_uri): bool
    {
        // Whitelist CF7 REST API
        if (PluginDetection::is_cf7_active() && strpos($request_uri, '/wp-json/contact-form-7/') !== false) {
            return false;
        }

        // Whitelist WPForms REST API
        if (PluginDetection::is_wpforms_active() && strpos($request_uri, '/wp-json/wpforms/') !== false) {
            return false;
        }

        // Whitelist Gravity Forms REST API
        if (PluginDetection::is_gravity_forms_active() && strpos($request_uri, '/wp-json/gf/') !== false) {
            return false;
        }

        return $should_block;
    }

    private function get_all_form_ajax_whitelist(): array
    {
        $whitelist = [];

        if (PluginDetection::is_cf7_active()) {
            $whitelist = array_merge($whitelist, PluginDetection::get_cf7_ajax_whitelist());
        }
        if (PluginDetection::is_wpforms_active()) {
            $whitelist = array_merge($whitelist, PluginDetection::get_wpforms_ajax_whitelist());
        }
        if (PluginDetection::is_gravity_forms_active()) {
            $whitelist = array_merge($whitelist, PluginDetection::get_gravity_forms_ajax_whitelist());
        }
        if (PluginDetection::is_fluent_forms_active()) {
            $whitelist = array_merge($whitelist, PluginDetection::get_fluent_forms_ajax_whitelist());
        }

        // Add ninja forms actions
        if (PluginDetection::is_ninja_forms_active()) {
            $whitelist[] = 'nf_ajax_submit';
            $whitelist[] = 'ninja_forms_ajax_submit';
        }

        // Add formidable actions
        if (PluginDetection::is_formidable_active()) {
            $whitelist[] = 'frm_entries_create';
            $whitelist[] = 'frm_entries_update';
        }

        return array_unique($whitelist);
    }

    private function is_cf7_form_present(): bool
    {
        global $post;

        if (!$post) {
            return false;
        }

        // Check if post content contains CF7 shortcode
        return has_shortcode($post->post_content, 'contact-form-7') ||
            has_shortcode($post->post_content, 'contact-form');
    }

    private function is_wpforms_form_present(): bool
    {
        global $post;

        if (!$post) {
            return false;
        }

        return has_shortcode($post->post_content, 'wpforms');
    }

    private function is_gravity_form_present(): bool
    {
        global $post;

        if (!$post) {
            return false;
        }

        return has_shortcode($post->post_content, 'gravityform') ||
            has_shortcode($post->post_content, 'gravityforms');
    }
}
