<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class WOSR_Cache {

    const GROUP = 'wosr_cache';

    /**
     * Get cached value or fetch + set it.
     *
     * @param string   $key     Unique cache key.
     * @param callable $callback Function to fetch data if cache is empty.
     * @param int      $ttl     Cache lifetime in seconds.
     * @return mixed
     */
    public static function remember( $key, callable $callback, $ttl = 3600 ) {
        $value = wp_cache_get( $key, self::GROUP );

        if ( false === $value ) {
            $value = call_user_func( $callback );
            wp_cache_set( $key, $value, self::GROUP, $ttl );

			$keys = wp_cache_get( 'keys', self::GROUP );
			$keys = is_array( $keys ) ? $keys : array();
			if ( ! in_array( $key, $keys, true ) ) {
				$keys[] = $key;
				wp_cache_set( 'keys', $keys, self::GROUP );
			}
        }

        return $value;
    }

    /**
     * Delete cache by key.
     */
    public static function forget( $key ) {
        wp_cache_delete( $key, self::GROUP );
    }

    /**
     * Flush everything in this plugin’s cache group.
     */
    public static function flush_all() {
		$keys = wp_cache_get( 'keys', self::GROUP, true ) ?: [];
		foreach ( $keys as $key ) {
			wp_cache_delete( $key, self::GROUP );
		}
		wp_cache_delete( 'keys', self::GROUP ); // reset tracking
	}
 
}
