<?php
/**
 * VMPFence Integrity Cache Manager
 * 
 * Handles async downloading and caching of plugin/theme checksums
 * to avoid blocking the main integrity check process.
 * 
 * @package VMPFence
 */

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

class VMPFence_Integrity_Cache_Manager {
    
    /**
     * Singleton instance
     */
    private static $instance = null;
    
    /**
     * Cache TTL (24 hours)
     */
    const CACHE_TTL = DAY_IN_SECONDS;
    
    /**
     * Background job interval (check every 6 hours)
     */
    const JOB_INTERVAL = 6 * HOUR_IN_SECONDS;
    
    /**
     * Get singleton instance
     */
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor - set up hooks
     */
    private function __construct() {
        // Schedule background cache refresh
        add_action('vmpfence_refresh_integrity_cache', array($this, 'refresh_all_checksums'));
        
        // Trigger cache refresh on plugin/theme updates
        add_action('upgrader_process_complete', array($this, 'on_upgrade_complete'), 10, 2);
        add_action('activated_plugin', array($this, 'on_plugin_activated'));
        add_action('switch_theme', array($this, 'on_theme_switched'));
        
        // Schedule the cron job if not already scheduled
        if (!wp_next_scheduled('vmpfence_refresh_integrity_cache')) {
            wp_schedule_event(time(), 'twicedaily', 'vmpfence_refresh_integrity_cache');
        }
    }
    
    /**
     * Refresh all plugin and theme checksums in background
     */
    public function refresh_all_checksums() {
        // Increase timeout for background job
        set_time_limit(600); // 10 minutes
        @ini_set('max_execution_time', '600');
        
        // Load integrity checker
        require_once VMPFENCE_PLUGIN_DIR . 'includes/class-wp-integrity-checker.php';
        $integrity_checker = new VMPFence_WP_Integrity_Checker();
        
        // Get all plugins
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        
        $all_plugins = get_plugins();
        $total_plugins = 0;
        $cached_plugins = 0;
        $total_files = 0;
        
        foreach ($all_plugins as $plugin_path => $plugin_data) {
            $plugin_slug = dirname($plugin_path);
            
            if ($plugin_slug === '.') {
                $plugin_slug = basename($plugin_path, '.php');
            }
            
            $plugin_version = $plugin_data['Version'] ?? '';
            
            if (empty($plugin_version)) {
                continue;
            }
            
            $total_plugins++;
            
            // Check if already cached
            $cache_key = 'vmpfence_plugin_checksums_' . $plugin_slug . '_' . $plugin_version;
            $cached = get_transient($cache_key);
            
            if ($cached !== false && !empty($cached)) {
                $cached_plugins++;
                $total_files += count($cached);
                continue;
            }
            
            // Download and cache checksums
            $checksums = $integrity_checker->get_official_checksums('plugin', $plugin_slug, $plugin_version);
            
            if ($checksums && is_array($checksums) && count($checksums) > 0) {
                $total_files += count($checksums);
            }
            
            // Small delay to avoid overwhelming WordPress.org API
            usleep(500000); // 0.5 second delay between plugins
        }
        
        // Cache theme checksums
        $current_theme = wp_get_theme();
        if ($current_theme->exists()) {
            $theme_slug = $current_theme->get_stylesheet();
            $theme_version = $current_theme->get('Version');
            
            if (!empty($theme_version)) {
                $theme_cache_key = 'vmpfence_theme_checksums_' . $theme_slug . '_' . $theme_version;
                $theme_checksums = $integrity_checker->get_official_checksums('theme', $theme_slug, $theme_version);
                
                if ($theme_checksums && is_array($theme_checksums) && count($theme_checksums) > 0) {
                    $total_files += count($theme_checksums);
                }
            }
        }
        
        // Update metadata about last refresh
        update_option('vmpfence_last_checksum_refresh', array(
            'timestamp' => time(),
            'total_plugins' => $total_plugins,
            'cached_plugins' => $cached_plugins,
            'total_files' => $total_files,
        ));
    }
    
    /**
     * Triggered when plugins are upgraded
     */
    public function on_upgrade_complete($upgrader_object, $options) {
        // Check if this was a plugin or theme update
        if (isset($options['type']) && ($options['type'] === 'plugin' || $options['type'] === 'theme')) {
            // Schedule immediate background refresh (within 60 seconds)
            if (!wp_next_scheduled('vmpfence_refresh_integrity_cache')) {
                wp_schedule_single_event(time() + 60, 'vmpfence_refresh_integrity_cache');
            }
        }
    }
    
    /**
     * Triggered when a plugin is activated
     */
    public function on_plugin_activated($plugin_path) {
        VMPFence_Secure_Logger::log('info', 'Integrity Cache: Plugin activated, clearing relevant cache');
        
        $plugin_slug = dirname($plugin_path);
        if ($plugin_slug === '.') {
            $plugin_slug = basename($plugin_path, '.php');
        }
        
        // Clear cache for this specific plugin so it gets refreshed
        $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin_path);
        $version = $plugin_data['Version'] ?? '';
        
        if (!empty($version)) {
            $cache_key = 'vmpfence_plugin_checksums_' . $plugin_slug . '_' . $version;
            delete_transient($cache_key);
        }
        
        // Schedule refresh
        if (!wp_next_scheduled('vmpfence_refresh_integrity_cache')) {
            wp_schedule_single_event(time() + 60, 'vmpfence_refresh_integrity_cache');
        }
    }
    
    /**
     * Triggered when theme is switched
     */
    public function on_theme_switched($new_name, $new_theme = null) {
        // Clear all theme caches (we don't know which themes were involved)
        global $wpdb;
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_vmpfence_theme_checksums_%'");
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_vmpfence_theme_checksums_%'");
        
        // Schedule refresh
        if (!wp_next_scheduled('vmpfence_refresh_integrity_cache')) {
            wp_schedule_single_event(time() + 60, 'vmpfence_refresh_integrity_cache');
        }
    }
    
    /**
     * Get cache status for admin display
     */
    public function get_cache_status() {
        $last_refresh = get_option('vmpfence_last_checksum_refresh', array());
        $next_scheduled = wp_next_scheduled('vmpfence_refresh_integrity_cache');
        
        return array(
            'last_refresh' => $last_refresh['timestamp'] ?? null,
            'total_plugins' => $last_refresh['total_plugins'] ?? 0,
            'cached_plugins' => $last_refresh['cached_plugins'] ?? 0,
            'total_files' => $last_refresh['total_files'] ?? 0,
            'next_scheduled' => $next_scheduled,
        );
    }
    
    /**
     * Manually trigger cache refresh (admin action)
     */
    public function trigger_manual_refresh() {
        // Clear all existing plugin/theme caches
        global $wpdb;
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_vmpfence_plugin_checksums_%'");
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_vmpfence_plugin_checksums_%'");
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_vmpfence_theme_checksums_%'");
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_vmpfence_theme_checksums_%'");
        
        // Trigger immediate refresh
        $this->refresh_all_checksums();
        
        return true;
    }
    
    /**
     * Cleanup on plugin deactivation
     */
    public static function cleanup() {
        // Remove scheduled job
        $timestamp = wp_next_scheduled('vmpfence_refresh_integrity_cache');
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'vmpfence_refresh_integrity_cache');
        }
        
        // Optionally clear all caches
        global $wpdb;
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_vmpfence_%checksums_%'");
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_vmpfence_%checksums_%'");
        delete_option('vmpfence_last_checksum_refresh');
    }
}

// Initialize the cache manager
VMPFence_Integrity_Cache_Manager::get_instance();
