<?php
/**
 * Automatically configure caching plugins to bypass cache for custom cookies.
 */
function wcmlim_configure_caching_plugins() {
    // Define custom cookies that need to bypass caching
    $custom_cookies = array(
        'wcmlim_selected_location',
        'wcmlim_nearby_location',
        'wcmlim_selected_location_termid',
        'autodetect_independent_wcmlim_nearby_location',
        'wcmlim_selected_location_regid',
        'maxmind_wcmlim_nearby_location',
        'wcmlim_city',
        'wcmlim_statecode',
        'wcmlim_zipCode',
        'wcmlim_countryCode',
        'wcmlim_widget_chosenlc'
    );

    // Step 1: Handle WP Rocket
    wcmlim_handle_wp_rocket($custom_cookies);

    // Step 2: Handle W3 Total Cache
    wcmlim_handle_w3_total_cache($custom_cookies);

    // Step 3: Handle LiteSpeed Cache
    wcmlim_handle_litespeed_cache($custom_cookies);

    // Step 4: Handle SiteGround Optimizer
    wcmlim_handle_siteground_optimizer($custom_cookies);

    // Step 5: Add generic cache-control headers for fallback
    wcmlim_add_cache_control_headers($custom_cookies);

    // Log the configurations for debugging purposes
    wcmlim_log_cache_configurations($custom_cookies);
}
add_action('init', 'wcmlim_configure_caching_plugins');

/**
 * Configures WP Rocket to exclude custom cookies.
 */
function wcmlim_handle_wp_rocket($custom_cookies) {
    if (function_exists('rocket_add_cookie')) {
        foreach ($custom_cookies as $cookie_name) {
            rocket_add_cookie($cookie_name);
        }
        wcmlim_log_message('WP Rocket: Custom cookies added to "Never Cache Cookies".');
    } else {
        // wcmlim_log_message('WP Rocket: Not detected on this site.');
    }
}

/**
 * Configures W3 Total Cache to exclude custom cookies.
 */
function wcmlim_handle_w3_total_cache($custom_cookies) {
    if (defined('W3TC')) {
        $config = w3_instance('W3_Config');
        $rejected_cookies = $config->get_string('pgcache.reject.cookies');
        $rejected_cookies_array = explode("\n", $rejected_cookies);

        foreach ($custom_cookies as $cookie_name) {
            if (!in_array($cookie_name, $rejected_cookies_array, true)) {
                $rejected_cookies_array[] = $cookie_name;
            }
        }

        $config->set('pgcache.reject.cookies', implode("\n", $rejected_cookies_array));
        $config->save();
        wcmlim_log_message('W3 Total Cache: Custom cookies added to "Rejected Cookies".');
    } else {
        // wcmlim_log_message('W3 Total Cache: Not detected on this site.');
    }
}

/**
 * Configures LiteSpeed Cache to exclude custom cookies.
 */
/**
 * Configures LiteSpeed Cache to exclude custom cookies.
 */
/**
 * Configures LiteSpeed Cache to exclude custom cookies using LiteSpeed Cache's API.
 */
function wcmlim_handle_litespeed_cache($custom_cookies) {
    if (defined('LSCWP_V')) {
        // Fetch current LiteSpeed Cache settings from wp_options
        $lite_speed_cache_settings = get_option('litespeed-cache-conf');

        // Check if the option is available, otherwise initialize it
        if (!$lite_speed_cache_settings) {
            $lite_speed_cache_settings = array();
        }

        // Retrieve the current "nocache-cookies" setting
        $nocache_cookies = isset($lite_speed_cache_settings['nocache-cookies']) ? $lite_speed_cache_settings['nocache-cookies'] : '';

        // Split the existing cookies into an array
        $nocache_cookies_array = explode(',', $nocache_cookies);

        // Add custom cookies to the array if not already present
        foreach ($custom_cookies as $cookie_name) {
            if (!in_array($cookie_name, $nocache_cookies_array, true)) {
                $nocache_cookies_array[] = $cookie_name;
            }
        }

        // Update the configuration with the new cookies list
        $lite_speed_cache_settings['nocache-cookies'] = implode(',', $nocache_cookies_array);

        // Apply the updated settings using update_option
        $result = update_option('litespeed-cache-conf', $lite_speed_cache_settings);

        if ($result) {
            wcmlim_log_message('LiteSpeed Cache: Custom cookies added to "Do Not Cache Cookies".');
        } else {
            wcmlim_log_message('LiteSpeed Cache: Failed to update "nocache-cookies".');
        }
    } else {
        // wcmlim_log_message('LiteSpeed Cache: Plugin not detected on this site.');
    }
}

/**
 * Warns about manual configuration for SiteGround Optimizer.
 */
function wcmlim_handle_siteground_optimizer($custom_cookies) {
    if (defined('SG_CACHEPRESS_VERSION')) {
        foreach ($custom_cookies as $cookie_name) {
            if (getLocation($cookie_name)) {
                header('Cache-Control: no-cache, must-revalidate, max-age=0');
                header('Pragma: no-cache');
                // wcmlim_log_message("Cache-Control headers applied for cookie: $cookie_name");
                break;
            }
        }
    } else {
        // wcmlim_log_message('SiteGround Optimizer: Not detected on this site.');
    }
}

/**
 * Adds cache-control headers as a fallback for unknown caching plugins.
 */
function wcmlim_add_cache_control_headers($custom_cookies) {
    add_action('send_headers', function () use ($custom_cookies) {
        foreach ($custom_cookies as $cookie_name) {
            if (getLocation($cookie_name)) {
                header('Cache-Control: no-cache, must-revalidate, max-age=0');
                header('Pragma: no-cache');
                // wcmlim_log_message("Cache-Control headers applied for cookie: $cookie_name");
                break;
            }
        }
    });
}

function wcmlim_log_cache_configurations($custom_cookies) {
    // wcmlim_log_message('Custom cookies configured for cache bypass: ' . implode(', ', $custom_cookies));
}

/**
 * Logs messages to the debug log for troubleshooting.
 */
function wcmlim_log_message($message) {
    if (defined('WP_DEBUG') && WP_DEBUG === true) {
        error_log('[WCMLIM Cache Config] ' . $message);
    }
}
