<?php
/**
 * Cache Invalidation Manager
 * Automatically clears relevant cache when data changes
 */
class CacheInvalidator {
    /**
     * Invalidate stock-related caches when stock changes
     */
    public static function invalidateStock(int $tenantId, ?int $productId = null): void {
        // Clear stock summary cache
        $pattern = "stock_summary_{$tenantId}_*";
        Cache::clear($pattern);
        
        // Clear inventory cache
        $pattern = "inventory_{$tenantId}_*";
        Cache::clear($pattern);
        
        // Clear stock valuation cache
        $pattern = "stock_valuation_{$tenantId}_*";
        Cache::clear($pattern);
        
        // If specific product, also clear product-specific caches
        if ($productId) {
            $pattern = "product_{$tenantId}_{$productId}_*";
            Cache::clear($pattern);
        }
    }
    
    /**
     * Invalidate sales-related caches when sales change
     */
    public static function invalidateSales(int $tenantId): void {
        $pattern = "sales_report_{$tenantId}_*";
        Cache::clear($pattern);
        
        $pattern = "daily_sales_{$tenantId}_*";
        Cache::clear($pattern);
        
        $pattern = "tax_report_{$tenantId}_*";
        Cache::clear($pattern);
    }
    
    /**
     * Invalidate purchase-related caches when purchases change
     */
    public static function invalidatePurchases(int $tenantId): void {
        $pattern = "purchases_report_{$tenantId}_*";
        Cache::clear($pattern);
    }
    
    /**
     * Invalidate all caches for a tenant
     */
    public static function invalidateTenant(int $tenantId): void {
        $pattern = "*_{$tenantId}_*";
        Cache::clear($pattern);
    }
    
    /**
     * Clear all expired cache files
     */
    public static function cleanExpired(): int {
        return Cache::cleanExpired();
    }
}

/**
 * Helper function to invalidate stock cache
 */
function invalidateStockCache(int $tenantId, ?int $productId = null): void {
    CacheInvalidator::invalidateStock($tenantId, $productId);
}
