<?php
/**
 * pawwell Performance Optimization
 *
 * @package pawwell
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Fragment Caching for Product Cards
 *
 * Caches product card HTML to improve performance on large shops.
 *
 * @param int $product_id Product ID
 * @return string Cached HTML
 */
if (!function_exists('pawwell_get_cached_product_card')) {
    function pawwell_get_cached_product_card($product_id) {
        $cache_key = 'pawwell_product_card_' . $product_id;
        $html = get_transient($cache_key);

        if ($html === false) {
            ob_start();
            wc_get_template_part('content', 'product');
            $html = ob_get_clean();

            // Cache for 6 hours
            set_transient($cache_key, $html, 6 * HOUR_IN_SECONDS);
        }

        return $html;
    }
}

/**
 * Clear product card cache when product is updated
 *
 * @param int $product_id Product ID
 */
if (!function_exists('pawwell_clear_product_card_cache')) {
    function pawwell_clear_product_card_cache($product_id) {
        $cache_key = 'pawwell_product_card_' . $product_id;
        delete_transient($cache_key);
    }
}
if (class_exists('WooCommerce')) {
    add_action('woocommerce_update_product', 'pawwell_clear_product_card_cache');
    add_action('woocommerce_delete_product', 'pawwell_clear_product_card_cache');
}

/**
 * Defer non-critical JavaScript
 *
 * Defers loading of non-critical JavaScript for better page load performance.
 *
 * @param string $tag Script tag
 * @param string $handle Script handle
 * @return string Modified script tag
 */
if (!function_exists('pawwell_defer_scripts')) {
    function pawwell_defer_scripts($tag, $handle) {
        $defer_scripts = array(
            'pawwell-script',
            'pawwell-woocommerce-single-product',
        );

        if (in_array($handle, $defer_scripts)) {
            return str_replace(' src', ' defer src', $tag);
        }

        return $tag;
    }
}
add_filter('script_loader_tag', 'pawwell_defer_scripts', 10, 2);
