<?php

namespace WPUltimateSecurity\UltimateSecurity\Modules\Compatibility;

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

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

    public function init()
    {
        // Exclude security pages from caching
        add_action('template_redirect', [$this, 'exclude_security_pages_from_cache'], 1);

        // Purge cache when settings change
        add_action('ultimate_security_settings_saved', [$this, 'purge_cache_on_settings_change']);

        // Handle nonce caching issues
        add_filter('nonce_life', [$this, 'adjust_nonce_life_for_cache']);

        // Add cache-busting for login pages
        add_action('login_init', [$this, 'set_login_no_cache'], 1);
    }

    public function exclude_security_pages_from_cache()
    {
        $should_exclude = false;

        // Always exclude login/registration pages
        if (is_page('login') || is_page('register') || is_page('my-account')) {
            $should_exclude = true;
        }

        // Check for custom login URL
        $options = Utils::ultimate_security_get_option();
        $custom_login_slug = $options['security']['login_url']['custom_login_slug'] ?? '';

        if (!empty($custom_login_slug)) {
            $current_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
            if (strpos($current_uri, $custom_login_slug) !== false) {
                $should_exclude = true;
            }
        }

        // Check for 2FA verification page
        if (isset($_GET['action']) && $_GET['action'] === 'ultimate_security_2fa') {
            $should_exclude = true;
        }

        if ($should_exclude) {
            $this->set_no_cache();
        }
    }

    public function purge_cache_on_settings_change()
    {
        PluginDetection::purge_all_caches();
    }

    public function adjust_nonce_life_for_cache($life): int
    {
        // If any caching plugin is active, extend nonce life
        if (
            PluginDetection::is_litespeed_active() ||
            PluginDetection::is_wp_super_cache_active() ||
            PluginDetection::is_w3_total_cache_active() ||
            PluginDetection::is_wp_rocket_active() ||
            PluginDetection::is_wp_fastest_cache_active()
        ) {
            // Extend to 2 days for cached pages
            return max($life, 2 * DAY_IN_SECONDS);
        }

        return $life;
    }

    public function set_login_no_cache()
    {
        $this->set_no_cache();
    }

    private function set_no_cache()
    {
        // LiteSpeed Cache header
        if (PluginDetection::is_litespeed_active()) {
            header('X-LiteSpeed-Cache-Control: no-cache');
        }

        // W3 Total Cache
        if (!defined('DONOTCACHEPAGE')) {
            define('DONOTCACHEPAGE', true);
        }

        // WP Super Cache
        if (!defined('DONOTCACHEDB')) {
            define('DONOTCACHEDB', true);
        }

        // WP Rocket
        if (!defined('DONOTROCKETOPTIMIZE')) {
            define('DONOTROCKETOPTIMIZE', true);
        }

        // Send standard no-cache headers
        nocache_headers();
    }

    public static function get_excluded_urls(): array
    {
        $options = Utils::ultimate_security_get_option();
        $custom_login_slug = $options['security']['login_url']['custom_login_slug'] ?? '';

        $urls = [
            '/wp-login.php',
            '/wp-admin/',
            '/my-account/',
        ];

        if (!empty($custom_login_slug)) {
            $urls[] = '/' . $custom_login_slug;
        }

        return $urls;
    }
}
