<?php
/**
 * Cache Tags Service
 *
 * Detects and manages cache tags for content-based invalidation.
 * Tags enable granular cache purging by product, category, or content type.
 *
 * @package Mamba\Modules\Caching\Services
 * @since   1.0.0
 */

namespace Mamba\Modules\Caching\Services;

/**
 * Class Tags
 *
 * Detects cache tags for the current request and manages tag-based
 * cache invalidation for products, categories, and other content types.
 *
 * @since 1.0.0
 */
final class Tags {
    public static function detectForCurrentRequest(): array {
        $tags = [];
        if (function_exists('is_product') && is_product()) {
            global $product;
            if ($product && is_object($product) && method_exists($product, 'get_id')) {
                $pid = $product->get_id();
                $tags[] = 'product_'.$pid;
                $cats = get_the_terms($pid, 'product_cat');
                if ($cats && !is_wp_error($cats)) foreach ($cats as $c) $tags[] = 'category_'.$c->term_id;
                $tagsTerms = get_the_terms($pid, 'product_tag');
                if ($tagsTerms && !is_wp_error($tagsTerms)) {
                    foreach ($tagsTerms as $t) { 
                        $tags[] = 'tag_'.$t->term_id; 
                    }
                }
            }
        } elseif (function_exists('is_product_category') && is_product_category()) {
            $cat = get_queried_object(); if ($cat) $tags[] = 'category_'.$cat->term_id;
        } elseif (function_exists('is_shop') && is_shop()) {
            // Keep legacy simple tag for compatibility, and add a TagMarkers-compatible variant
            $tags[] = 'shop';
            $tags[] = 'shop_1';
        }
        elseif (is_front_page()) { $tags[] = 'home'; }
        return $tags;
    }
    public static function bump(string $type, string $id): bool {
        // Use universal cache adapter (object cache preferred, file cache fallback)
        if (class_exists('\Mamba\Modules\Caching\Services\TagMarkers')) {
            return \Mamba\Modules\Caching\Services\TagMarkers::bump($type, $id);
        }
        
        // Fallback to transients only if TagMarkers class not available
        return set_transient('mamba_cache_tag_'.$type.'_'.$id, time(), 30 * DAY_IN_SECONDS);
    }
    public static function isStale(array $tags, int $fileTime): bool {
        // Use universal cache adapter (object cache preferred, file cache fallback)
        if (class_exists('\Mamba\Modules\Caching\Services\TagMarkers')) {
            return \Mamba\Modules\Caching\Services\TagMarkers::isStale($tags, $fileTime);
        }
        
        // Fallback to transients only if TagMarkers class not available
        foreach ($tags as $t) {
            $parts = explode('_', $t, 2);
            if (count($parts)===2) {
                $when = get_transient('mamba_cache_tag_'.$parts[0].'_'.$parts[1]);
                if ($when && $when > $fileTime) return true;
            }
        }
        return false;
    }
}
