<?php
/**
 * Bizmart — Cache invalidation.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */
if (!defined('ABSPATH')) exit;

/**
 * Central cache invalidation for Bizmart metrics.
 * Uses a single versioned transient key pattern for efficient cleanup.
 */
if (!function_exists('bizmart_invalidate_product_metrics_cache')) {
    function bizmart_invalidate_product_metrics_cache($product_id = null, string $reason = ''): void {
        $blog_id = (int) get_current_blog_id();

        // Current version transient
        delete_transient('bizmart_inventory_totals_v9_' . $blog_id);

        // Legacy caches (one release back for backward compat)
        $legacy_keys = [
            'bizmart_inventory_totals_v8_',
            'bizmart_products_stats_v5_',
        ];
        foreach ($legacy_keys as $prefix) {
            delete_transient($prefix . $blog_id);
        }

        delete_transient('bizmart_dash_missing_purchase_prices_v2');
        delete_transient('bizmart_dash_missing_pricing_v3');

        // v3.0 — Also invalidate WAC cache
        if (function_exists('bizmart_invalidate_wac_cache')) {
            bizmart_invalidate_wac_cache();
        }

        // Allow extensions to clear their own caches
        do_action('bizmart_invalidate_more_caches', $product_id, $reason);

        if ($product_id && function_exists('wc_delete_product_transients')) {
            wc_delete_product_transients((int) $product_id);
        }

        do_action('bizmart_metrics_cache_invalidated', $product_id ? (int)$product_id : 0, $reason);
    }
}

// --- Hooks to invalidate caches deterministically ---

add_action('woocommerce_product_set_stock', function($product) {
    if (!is_object($product) || !method_exists($product, 'get_id')) return;
    bizmart_invalidate_product_metrics_cache((int) $product->get_id(), 'woocommerce_product_set_stock');
}, 20, 1);

add_action('woocommerce_product_set_stock_status', function($product_id) {
    bizmart_invalidate_product_metrics_cache((int) $product_id, 'woocommerce_product_set_stock_status');
}, 20, 1);

add_action('save_post_product', function($post_id) {
    if (wp_is_post_revision($post_id) || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) return;
    bizmart_invalidate_product_metrics_cache((int) $post_id, 'save_post_product');
}, 20, 1);

add_action('save_post_product_variation', function($post_id) {
    if (wp_is_post_revision($post_id) || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) return;
    bizmart_invalidate_product_metrics_cache((int) $post_id, 'save_post_product_variation');
}, 20, 1);

add_action('updated_post_meta', function($meta_id, $object_id, $meta_key, $_meta_value) {
    static $keys = [
        '_stock','_stock_status','_manage_stock',
        '_price','_regular_price','_sale_price',
        '_purchase_price','_alg_wc_cog_cost',
    ];
    if (!in_array($meta_key, $keys, true)) return;

    $post_type = get_post_type($object_id);
    if ($post_type !== 'product' && $post_type !== 'product_variation') return;

    bizmart_invalidate_product_metrics_cache((int) $object_id, 'updated_post_meta:' . $meta_key);
}, 20, 4);

add_action('added_post_meta', function($meta_id, $object_id, $meta_key, $_meta_value) {
    static $keys = [
        '_stock','_stock_status','_manage_stock',
        '_price','_regular_price','_sale_price',
        '_purchase_price','_alg_wc_cog_cost',
    ];
    if (!in_array($meta_key, $keys, true)) return;

    $post_type = get_post_type($object_id);
    if ($post_type !== 'product' && $post_type !== 'product_variation') return;

    bizmart_invalidate_product_metrics_cache((int) $object_id, 'added_post_meta:' . $meta_key);
}, 20, 4);

add_action('deleted_post_meta', function($meta_ids, $object_id, $meta_key, $_meta_values) {
    static $keys = [
        '_stock','_stock_status','_manage_stock',
        '_price','_regular_price','_sale_price',
        '_purchase_price','_alg_wc_cog_cost',
    ];
    if (!in_array($meta_key, $keys, true)) return;

    $post_type = get_post_type($object_id);
    if ($post_type !== 'product' && $post_type !== 'product_variation') return;

    bizmart_invalidate_product_metrics_cache((int) $object_id, 'deleted_post_meta:' . $meta_key);
}, 20, 4);
