<?php
/**
 * Launchmind Cache Handler
 * 
 * Uses WordPress transients for caching API responses.
 * Default TTL: 10 minutes (configurable)
 */

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

class Launchmind_Cache {
    
    /**
     * Cache prefix
     */
    const PREFIX = 'launchmind_blog_';
    
    /**
     * Get cached value
     * 
     * @param string $key Cache key
     * @return mixed|false Cached value or false if not found
     */
    public static function get($key) {
        $full_key = self::PREFIX . $key;
        $value = get_transient($full_key);
        
        return $value;
    }
    
    /**
     * Set cached value
     * 
     * @param string $key Cache key
     * @param mixed $value Value to cache
     * @param int|null $ttl Time to live in seconds (null = use default)
     * @return bool Success
     */
    public static function set($key, $value, $ttl = null) {
        if (null === $ttl) {
            $ttl = self::get_ttl();
        }
        
        $full_key = self::PREFIX . $key;
        return set_transient($full_key, $value, $ttl);
    }
    
    /**
     * Delete cached value
     * 
     * @param string $key Cache key
     * @return bool Success
     */
    public static function delete($key) {
        $full_key = self::PREFIX . $key;
        return delete_transient($full_key);
    }
    
    /**
     * Clear all plugin cache
     * 
     * @return int Number of cleared entries
     */
    public static function clear_all() {
        global $wpdb;
        
        $count = 0;
        
        // Clear regular transients
        $transients = $wpdb->get_col(
            $wpdb->prepare(
                "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
                '_transient_' . self::PREFIX . '%'
            )
        );
        
        foreach ($transients as $transient) {
            $key = str_replace('_transient_', '', $transient);
            if (delete_transient($key)) {
                $count++;
            }
        }
        
        // Also clear transient timeouts
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
                '_transient_timeout_' . self::PREFIX . '%'
            )
        );
        
        return $count;
    }
    
    /**
     * Generate cache key from parameters
     * 
     * @param string $base Base key name
     * @param array $params Parameters to include in key
     * @return string Cache key
     */
    public static function generate_key($base, $params = array()) {
        $key = $base;
        
        if (!empty($params)) {
            // Sort params for consistent keys
            ksort($params);
            $key .= '_' . md5(serialize($params));
        }
        
        return sanitize_key($key);
    }
    
    /**
     * Get cache TTL from settings
     * 
     * @return int TTL in seconds
     */
    public static function get_ttl() {
        $ttl = Launchmind_Blog_Connector::get_option('cache_ttl', LAUNCHMIND_CACHE_DEFAULT_TTL);
        return max(60, intval($ttl)); // Minimum 60 seconds
    }
    
    /**
     * Get cache statistics
     * 
     * @return array Cache stats
     */
    public static function get_stats() {
        global $wpdb;
        
        $count = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name LIKE %s",
                '_transient_' . self::PREFIX . '%'
            )
        );
        
        return array(
            'entries' => intval($count),
            'ttl' => self::get_ttl(),
            'prefix' => self::PREFIX,
        );
    }
}

