<?php

    class KavehCustomQueryStatic
    {
        private static $cache_duration = 86400; // Default cache duration in seconds
        private static $cache_dir; // Directory to store cache files

        public function __construct()
        {
            // Define the cache directory path
            self::$cache_dir = wp_upload_dir()['basedir'] . '/query-cache/';
            
            // Ensure the cache directory exists
            if (!file_exists(self::$cache_dir)) {
                mkdir(self::$cache_dir, 0755, true);
            }

            // 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 filename based on query arguments.
         *
         * @param array $query_args The query arguments.
         * @return string A unique cache filename.
         */
        private static function generate_cache_filename($query_args)
        {
            return self::$cache_dir . 'custom_query_' . md5(serialize($query_args)) . '.cache';
        }

        /**
         * Run a custom WP_Query and cache the results in a file.
         *
         * @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 filename based on the query arguments
            $cache_file = self::generate_cache_filename($query_args);

            // Check if we have a cached result
            if (file_exists($cache_file) && (filemtime($cache_file) + self::$cache_duration > time())) {
                // Read from the cache file
                $cached_results = file_get_contents($cache_file);
                if ($cached_results !== false) {
                    return unserialize($cached_results);
                }
            }

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

            // Cache the results in a file
            file_put_contents($cache_file, serialize($query));

            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_file = self::generate_cache_filename($query_args);
            if (file_exists($cache_file)) {
                return unlink($cache_file);
            }
            return false;
        }

        /**
         * Clear all cache files.
         * Hooked into WordPress post actions.
         */
        public static function clear_all_cache()
        {
            // Get all cache files in the cache directory
            $files = glob(self::$cache_dir . 'custom_query_*.cache');

            // Delete each cache file
            foreach ($files as $file) {
                if (file_exists($file)) {
                    unlink($file);
                }
            }
        }
    }
