<?php

namespace Edoobox\Base;

class Cache {
    private static array $localCache = [];

    public static function cleanup() {
        $intervalInSeconds = 43200; // 12 hours
        $lastCleanup = Options::get("edoobox_last_cleanup_in_s", 0);
        $nextCleanup = $lastCleanup + $intervalInSeconds;
        $currentTime = current_time('timestamp');

        if ( $nextCleanup > $currentTime ) {
            return $lastCleanup;
        }

        self::deleteExpired();
        Options::set("edoobox_last_cleanup_in_s", $currentTime);

        return $currentTime;
    }

    public static function deleteAll() {
        global $wpdb;
        
        // Delete all edoobox cache transients and their timeouts in one query
        $wpdb->query("
            DELETE FROM $wpdb->options 
            WHERE option_name LIKE '_transient_edoobox_cache_%' 
            OR option_name LIKE '_transient_timeout_edoobox_cache_%'
        ");

        Options::set('edoobox_last_cleanup_in_s', current_time('timestamp'));
        $wpdb->query("OPTIMIZE TABLE $wpdb->options");
    }

    public static function deleteExpired() {
        global $wpdb;
        $current_time = current_time('timestamp');

        // Delete expired transients and their timeouts
        $wpdb->query($wpdb->prepare("
            DELETE t1, t2 
            FROM $wpdb->options t1
            JOIN $wpdb->options t2 
            ON t2.option_name = REPLACE(t1.option_name, '_transient_', '_transient_timeout_')
            WHERE t1.option_name LIKE '_transient_edoobox_cache_%'
            AND t2.option_value < %d
        ", $current_time));

        $wpdb->query("OPTIMIZE TABLE $wpdb->options");
    }

    public static function get($key) {
       // xdebug_break();
        if (isset(self::$localCache[$key])) {
            return self::$localCache[$key];
        }
        $cache = get_transient('edoobox_cache_' . $key);
        self::$localCache[$key] = $cache === false ? '' : $cache;
        return self::$localCache[$key];
    }

    public static function set($key, $data, $timeInSeconds = 5) {
        LogTime::start('cache set');
        // Minimum 5s to avoid autoload cache and to throttle requests
        $expirationTime = max($timeInSeconds, 5);
        set_transient('edoobox_cache_' . $key, $data, $expirationTime);
        self::$localCache[$key] = $data;
        LogTime::stop('cache set');
    }
}