<?php

class KavehCustomQuery
{
    private static $cache_duration = 86400; // Default cache duration in seconds

    public function __construct()
    {
        // Hook into WordPress post actions to clear cache
        add_action('save_post', [__CLASS__, 'clear_all_cache']);
        add_action('delete_post', [__CLASS__, 'clear_all_cache']);
        add_action('transition_post_status', [__CLASS__, 'clear_all_cache'], 10, 3);
    }

    /**
     * Set the cache duration (optional method).
     *
     * @param int $duration The cache duration in seconds.
     */
    public static function set_cache_duration($duration)
    {
        self::$cache_duration = $duration;
    }

    /**
     * Generate a unique cache key based on query arguments.
     *
     * @param array $query_args The query arguments.
     * @return string A unique cache key.
     */
    private static function generate_cache_key($query_args)
    {
        return 'custom_query_' . md5(serialize($query_args));
    }

    /**
     * Run a custom WP_Query and cache the results.
     *
     * @param array $query_args The query arguments.
     * @return WP_Query The WP_Query object.
     */
    public static function get_cached_query($query_args)
    {
        // Generate a unique cache key based on the query arguments
        $cache_key = self::generate_cache_key($query_args);

        // Check if we have a cached result
        $cached_results = get_transient($cache_key);

        if ($cached_results !== false) {
            return $cached_results;
        }

        // Run the query
        $query = new WP_Query($query_args);

        // Cache the results
        set_transient($cache_key, $query, self::$cache_duration);

        return $query;
    }

    /**
     * Clear cache based on query arguments.
     *
     * @param array $query_args The query arguments to clear cache for.
     * @return bool True if the cache was successfully deleted.
     */
    public static function clear_cache($query_args)
    {
        $cache_key = self::generate_cache_key($query_args);
        return delete_transient($cache_key);
    }

    /**
     * Clear all caches when a post is updated, deleted, or created.
     * Hooked into WordPress post actions.
     */
    public static function clear_all_cache()
    {
        global $wpdb;
        $transients = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '_transient_custom_query_%'");

        foreach ($transients as $transient) {
            $transient_name = str_replace('_transient_', '', $transient);
            delete_transient($transient_name);
        }
    }
}
