<?php

/**
 * Schema Enhancement Cache
 *
 * Caches AI-generated schema enhancements to improve performance
 *
 * @package ProRank\SEO\Core\Schema
 * @since   2.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\Schema;

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


/**
 * SchemaEnhancementCache class
 */


class SchemaEnhancementCache {
    
    /**
     * Cache group name
     */
    private const CACHE_GROUP = 'prorank_schema_enhancements';
    
    /**
     * Cache expiration time (24 hours)
     */
    private const CACHE_EXPIRATION = 86400;
    
    /**
     * Get cached enhancement for a product
     *
     * @param int $product_id Product ID.
     * @return array|null Cached enhancement or null if not found.
     */
    public function get(int $product_id): ?array {
        $cache_key = $this->get_cache_key($product_id);
        $cached = wp_cache_get($cache_key, self::CACHE_GROUP);
        
        if (false !== $cached) {
            return $cached;
        }
        
        // Try transient as fallback for persistent cache
        $transient_key = 'prorank_schema_' . $product_id;
        $cached = get_transient($transient_key);
        
        if (false !== $cached) {
            // Re-populate object cache
            wp_cache_set($cache_key, $cached, self::CACHE_GROUP, self::CACHE_EXPIRATION);
            return $cached;
        }
        
        return null;
    }
    
    /**
     * Set cached enhancement for a product
     *
     * @param int   $product_id  Product ID.
     * @param array $enhancement Enhancement data.
     * @return bool Success status.
     */
    public function set(int $product_id, array $enhancement): bool {
        $cache_key = $this->get_cache_key($product_id);
        
        // Set in object cache
        $result = wp_cache_set($cache_key, $enhancement, self::CACHE_GROUP, self::CACHE_EXPIRATION);
        
        // Also set as transient for persistence
        $transient_key = 'prorank_schema_' . $product_id;
        set_transient($transient_key, $enhancement, self::CACHE_EXPIRATION);
        
        return $result;
    }
    
    /**
     * Delete cached enhancement for a product
     *
     * @param int $product_id Product ID.
     * @return bool Success status.
     */
    public function delete(int $product_id): bool {
        $cache_key = $this->get_cache_key($product_id);
        
        // Delete from object cache
        $result = wp_cache_delete($cache_key, self::CACHE_GROUP);
        
        // Delete transient
        $transient_key = 'prorank_schema_' . $product_id;
        delete_transient($transient_key);
        
        return $result;
    }
    
    /**
     * Clear all cached enhancements
     *
     * @return void
     */
    public function clear_all(): void {
        // Clear object cache group
        wp_cache_flush_group(self::CACHE_GROUP);
        
        // Clear all schema transients
        global $wpdb;
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->options} 
                WHERE option_name LIKE %s 
                OR option_name LIKE %s",
                '_transient_prorank_schema_%',
                '_transient_timeout_prorank_schema_%'
            )
        );
    }
    
    /**
     * Get cache key for a product
     *
     * @param int $product_id Product ID.
     * @return string Cache key.
     */
    private function get_cache_key(int $product_id): string {
        // Include version in key to invalidate cache on plugin updates
        $version = defined('PRORANK_SEO_VERSION') ? PRORANK_SEO_VERSION : '1.0.0';
        
        // Include settings hash to invalidate when settings change
        $settings_hash = $this->get_settings_hash();
        
        return sprintf('product_%d_v%s_%s', $product_id, $version, $settings_hash);
    }
    
    /**
     * Get hash of relevant settings
     *
     * @return string Settings hash.
     */
    private function get_settings_hash(): string {
        $settings = [
            get_option('prorank_seo_enable_ai_schema_enhancement', true),
            get_option('prorank_seo_ai_detect_brand', true),
            get_option('prorank_seo_ai_generate_descriptions', true),
            get_option('prorank_seo_ai_extract_features', true),
            get_option('prorank_seo_ai_generate_faq', true),
            get_option('prorank_seo_ai_detect_energy', true),
            get_option('prorank_seo_ai_detect_sustainability', true),
            get_option('prorank_seo_ai_detect_warranty', true),
        ];
        
        return substr(md5(serialize($settings)), 0, 8);
    }
    
    /**
     * Hook into product updates to clear cache
     *
     * @return void
     */
    public static function init_hooks(): void {
        $instance = new self();
        
        // Clear cache when product is saved
        add_action('woocommerce_update_product', [$instance, 'delete']);
        add_action('woocommerce_new_product', [$instance, 'delete']);
        
        // Clear cache when product meta is updated
        add_action('updated_post_meta', function($meta_id, $post_id, $meta_key) use ($instance) {
            if (get_post_type($post_id) === 'product') {
                $instance->delete($post_id);
            }
        }, 10, 3);
        
        // Clear all cache when settings are updated
        add_action('update_option_prorank_seo_enable_ai_schema_enhancement', [$instance, 'clear_all']);
        add_action('update_option_prorank_seo_ai_detect_brand', [$instance, 'clear_all']);
        add_action('update_option_prorank_seo_ai_generate_descriptions', [$instance, 'clear_all']);
        add_action('update_option_prorank_seo_ai_extract_features', [$instance, 'clear_all']);
        add_action('update_option_prorank_seo_ai_generate_faq', [$instance, 'clear_all']);
        add_action('update_option_prorank_seo_ai_detect_energy', [$instance, 'clear_all']);
        add_action('update_option_prorank_seo_ai_detect_sustainability', [$instance, 'clear_all']);
        add_action('update_option_prorank_seo_ai_detect_warranty', [$instance, 'clear_all']);
    }
}