<?php

namespace WPUltimateSecurity\UltimateSecurity\Modules\Compatibility;

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

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

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

        // Handle 2FA on WooCommerce login forms
        add_action('woocommerce_login_form_end', [$this, 'add_2fa_to_wc_login']);

        // Ensure WooCommerce REST API isn't blocked
        add_filter('ultimate_security_url_guard_check', [$this, 'whitelist_wc_rest_api'], 10, 2);

        // Set no-cache headers for WooCommerce account/checkout
        add_action('template_redirect', [$this, 'set_no_cache_for_wc_pages']);

        // Handle WooCommerce nonces with caching
        add_filter('nonce_life', [$this, 'extend_wc_nonce_life']);
    }

    public function skip_woocommerce_ajax($should_limit, $context): bool
    {
        if (PluginDetection::is_woocommerce_ajax()) {
            return false; // Don't rate limit
        }

        // Check for specific WooCommerce AJAX actions
        if (isset($_REQUEST['wc-ajax'])) {
            $allowed_actions = [
                'checkout',
                'update_order_review',
                'apply_coupon',
                'remove_coupon',
                'update_shipping_method',
                'get_refreshed_fragments',
                'add_to_cart',
                'get_variation',
            ];

            $action = sanitize_text_field(wp_unslash($_REQUEST['wc-ajax']));
            if (in_array($action, $allowed_actions, true)) {
                return false;
            }
        }

        return $should_limit;
    }

    public function add_2fa_to_wc_login()
    {
        $options = Utils::ultimate_security_get_option();
        $two_fa_enabled = $options['security']['login_2fa']['enable'] ?? '0';

        if ($two_fa_enabled !== '1' && $two_fa_enabled !== 1) {
            return;
        }

        // Add 2FA field to WooCommerce login form
        // The actual 2FA validation is handled by the main 2FA module
        wp_nonce_field('ultimate_security_wc_2fa', 'ultimate_security_wc_2fa_nonce');
    }

    public function whitelist_wc_rest_api($should_block, $request_uri): bool
    {
        // Whitelist WooCommerce REST API endpoints
        if (strpos($request_uri, '/wp-json/wc/') !== false) {
            return false; // Don't block
        }

        // Whitelist WooCommerce Store API (blocks)
        if (strpos($request_uri, '/wp-json/wc/store/') !== false) {
            return false;
        }

        return $should_block;
    }

    public function set_no_cache_for_wc_pages()
    {
        if (!PluginDetection::is_woocommerce_active()) {
            return;
        }

        // Don't cache WooCommerce account, cart, and checkout pages
        if (is_cart() || is_checkout() || is_account_page()) {
            PluginDetection::set_no_cache_headers();
        }
    }

    public function extend_wc_nonce_life($life): int
    {
        // Extend nonce life for WooCommerce to handle caching
        if (PluginDetection::is_woocommerce_page()) {
            return max($life, 2 * DAY_IN_SECONDS);
        }

        return $life;
    }

    public static function get_wc_ajax_actions(): array
    {
        return [
            'checkout',
            'update_order_review',
            'apply_coupon',
            'remove_coupon',
            'update_shipping_method',
            'get_refreshed_fragments',
            'add_to_cart',
            'get_variation',
            'add_payment_method',
            'delete_payment_method',
            'get_customer_location',
        ];
    }
}
