<?php
/**
 * Cart Fragments Cache Service
 *
 * Caches WooCommerce cart fragments for guest users to reduce
 * AJAX requests and improve cart widget performance.
 *
 * @package Mamba\Modules\Caching\Services\Fragments
 * @since   1.0.0
 */

namespace Mamba\Modules\Caching\Services\Fragments;

use Mamba\Support\CacheAdapter;

/**
 * Class CartFragments
 *
 * Handles caching and serving of WooCommerce cart fragments
 * for guest users with empty carts to reduce server load.
 *
 * @since 1.0.0
 */
final class CartFragments {
    public static function filterFragments($fragments) {
        if (is_user_logged_in()) return $fragments;
        if (function_exists('WC') && WC()->cart && !WC()->cart->is_empty()) return $fragments;
        $key = self::key(); 
        CacheAdapter::set($key, $fragments, 'mamba_cart_fragments', 15 * MINUTE_IN_SECONDS); 
        return $fragments;
    }
    public static function ajax() {
        if (is_user_logged_in()) return;
        if (function_exists('WC') && WC()->cart && !WC()->cart->is_empty()) return;
        $key = self::key(); 
        $cached = CacheAdapter::get($key, 'mamba_cart_fragments'); 
        if ($cached !== null) { 
            wp_send_json($cached); 
            exit; 
        }
    }
    public static function clear() {
        // Use universal cache adapter to clear group
        CacheAdapter::clearGroup('mamba_cart_fragments');
    }
    private static function key(): string {
        $parts = ['guest'];
        $currency = apply_filters('mamba_variant_currency', get_option('woocommerce_currency', ''));
        if (!empty($currency)) {
            $parts[] = 'cur=' . sanitize_text_field((string)$currency);
        }
        $lang = apply_filters('mamba_variant_lang', '');
        if (!empty($lang)) {
            $parts[] = 'lang=' . sanitize_text_field((string)$lang);
        }
        $parts[] = 'd=' . (wp_is_mobile() ? 'm' : 'd');
        
        // Add WooCommerce geo hash if available
        $wooGeoHash = self::detectWooCommerceGeoHash();
        if ($wooGeoHash) {
            $parts[] = 'woo_geo=' . $wooGeoHash;
        }
        
        $hash = md5(implode('|', $parts));
        return 'mamba_wc_cart_fragments_' . $hash;
    }
    
    /**
     * Detect WooCommerce geolocation hash parameter
     * Validates and returns the 'v' parameter if present and valid
     */
    private static function detectWooCommerceGeoHash(): ?string {
        // Check for WooCommerce's v parameter
        if (!empty($_GET['v']) && is_string($_GET['v'])) {
            $hash = sanitize_text_field(wp_unslash($_GET['v']));
            // Validate it looks like a WooCommerce geo hash (alphanumeric, reasonable length)
            if (preg_match('/^[a-zA-Z0-9]{8,32}$/', $hash)) {
                return $hash;
            }
        }
        
        // Check for WooCommerce geo cookie as fallback
        if (!empty($_COOKIE['woocommerce_geo_hash'])) {
            $cookieHash = sanitize_text_field(wp_unslash($_COOKIE['woocommerce_geo_hash']));
            // Validate cookie hash format
            if (preg_match('/^[a-zA-Z0-9]{8,32}$/', $cookieHash)) {
                return $cookieHash;
            }
        }
        
        return null;
    }
}
