<?php
/**
 * Browser Cache Policy Service
 *
 * Manages browser cache headers for different page types including
 * WooCommerce dynamic pages, catalog pages, and static content.
 *
 * @package Mamba\Modules\Caching\Services
 * @since   1.0.0
 */

namespace Mamba\Modules\Caching\Services;

/**
 * Class BrowserCachePolicy
 *
 * Applies appropriate Cache-Control headers based on page type,
 * user login status, and WooCommerce context.
 *
 * @since 1.0.0
 */
final class BrowserCachePolicy {
    
    /**
     * Apply comprehensive browser cache policy via send_headers hook
     */
    public static function applyHeaders(): void {
        // Dynamic WooCommerce pages - never cache in browser
        if (function_exists('is_cart') && (is_cart() || is_checkout() || is_account_page())) {
            header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
            header('Pragma: no-cache');
            header('Expires: ' . gmdate('D, d M Y H:i:s', time() - 3600) . ' GMT');
            header('X-Mamba-Cache: BYPASS');
            return;
        }
        
        // Logged-in users - private cache only
        if (is_user_logged_in()) {
            header('Cache-Control: private, no-cache, must-revalidate, max-age=0');
            header('Pragma: no-cache');
            header('X-Mamba-Cache: BYPASS');
            return;
        }
        
        // Catalog pages - use page cache TTL for consistency
        if (self::isCatalogPage()) {
            // Get intended TTL from PageCache (integration point)
            $intendedTtl = 0;
            if (class_exists('\Mamba\Modules\Caching\Services\PageCache')) {
                $intendedTtl = \Mamba\Modules\Caching\Services\PageCache::getIntendedTtl();
            }
            
            // Use intended TTL if available, otherwise fall back to browser TTL setting
            if ($intendedTtl > 0) {
                $browserTtl = $intendedTtl; // Use page cache TTL for consistency
            } else {
                $browserTtl = (int)get_option('mamba_browser_ttl', 300); // 5 minutes default
            }
            
            // Allow filtering of browser TTL for extensibility
            $browserTtl = (int)apply_filters('mamba_browser_ttl', $browserTtl);
            
            if ($browserTtl > 0) {
                // Get CDN TTL settings for proper harmonization
                $cdnTtl = (int)get_option('mamba_cdn_ttl', 7200); // 2 hours default
                $staleIfError = (int)get_option('mamba_stale_if_error', 86400); // 24 hours default
                $staleWhileRevalidate = min($browserTtl / 2, 120); // 50% of TTL, max 120s for better performance
                
                // Build comprehensive Cache-Control header with CDN harmonization
                $cc = "public, max-age={$browserTtl}, s-maxage={$cdnTtl}, stale-while-revalidate={$staleWhileRevalidate}, stale-if-error={$staleIfError}";
                
                header("Cache-Control: {$cc}");
            }
            // If browser TTL is 0, let browser heuristics apply (no Cache-Control header)
        } else {
            // Non-catalog pages - set bypass header for consistency
            header('X-Mamba-Cache: BYPASS');
        }
    }
    
    /**
     * Apply REST API browser cache policy
     */
    public static function applyRestHeaders($response, $server, $request) {
        $route = $request->get_route();
        $method = $request->get_method();
        
        // Dynamic Store API endpoints - never cache in browser
        if (strpos($route, '/wc/store/') === 0 &&
            ($method !== 'GET' || preg_match('#/wc/store/v\d+/(cart|checkout)#', $route))) {
            $response->header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
            $response->header('Pragma', 'no-cache');
            return $response;
        }
        
        // GET Store API endpoints - configurable browser TTL
        if (strpos($route, '/wc/store/') === 0 && $method === 'GET') {
            $browserTtl = (int)get_option('mamba_store_api_browser_ttl', 300); // 5 minutes default
            if ($browserTtl > 0) {
                // Get CDN TTL settings for proper harmonization
                $cdnTtl = (int)get_option('mamba_cdn_ttl', 7200); // 2 hours default
                $staleIfError = (int)get_option('mamba_stale_if_error', 86400); // 24 hours default
                $staleWhileRevalidate = min($browserTtl / 2, 120); // 50% of TTL, max 120s for better performance
                
                // Build comprehensive Cache-Control header with CDN harmonization
                $cc = "public, max-age={$browserTtl}, s-maxage={$cdnTtl}, stale-while-revalidate={$staleWhileRevalidate}, stale-if-error={$staleIfError}";
                
                $response->header('Cache-Control', $cc);
            }
        }
        
        return $response;
    }
    
    /**
     * Check if current page is a catalog page
     */
    private static function isCatalogPage(): bool {
        if (!function_exists('is_woocommerce')) return false;
        
        return (function_exists('is_front_page') && (is_front_page() || is_home())) ||
               (function_exists('is_product') && is_product()) ||
               (function_exists('is_product_category') && is_product_category()) ||
               (function_exists('is_product_tag') && is_product_tag()) ||
               (function_exists('is_shop') && is_shop()) ||
               (function_exists('is_woocommerce') && is_woocommerce() && !is_cart() && !is_checkout() && !is_account_page());
    }
}
