<?php
/**
 * Plugin Activator
 *
 * Handles plugin activation for both single-site and multisite installations.
 * Creates cache directories, sets default options, and schedules cleanup tasks.
 *
 * @package Mamba\Lifecycle
 * @since   1.0.0
 */

namespace Mamba\Lifecycle;

/**
 * Class Activator
 *
 * Manages plugin activation logic including directory creation,
 * default option initialization, and multisite network activation.
 *
 * @since 1.0.0
 */
final class Activator {
    
    /**
     * Main activation entry point
     * Handles both single-site and network-wide activation
     * 
     * @param bool $network_wide Whether this is a network-wide activation
     */
    public static function run(bool $network_wide = false): void {
        // Create the main cache directory (shared across all sites in multisite)
        if (defined('WP_CONTENT_DIR')) {
            $dir = WP_CONTENT_DIR . '/cache/mamba';
            if (!is_dir($dir)) {
                if (wp_mkdir_p($dir)) {
                    self::createProtectionFiles($dir);
                }
            }
        }
        
        // Handle multisite network-wide activation
        if (is_multisite() && $network_wide) {
            self::activateNetworkWide();
        } else {
            self::activateSingleSite();
        }
        
        // Register object cache global groups (once, not per-site)
        if (class_exists('\Mamba\Support\ObjectCache')) {
            \Mamba\Support\ObjectCache::registerGlobalGroups();
        }
    }
    
    /**
     * Activate plugin for all sites in the network
     */
    private static function activateNetworkWide(): void {
        // Get all site IDs in the network
        $sites = get_sites([
            'fields' => 'ids',
            'number' => 0, // All sites
        ]);
        
        foreach ($sites as $siteId) {
            switch_to_blog($siteId);
            self::activateSingleSite();
            restore_current_blog();
        }
    }
    
    /**
     * Activate plugin for a single site
     * This contains all original activation logic
     */
    public static function activateSingleSite(): void {
        if (!defined('WP_CONTENT_DIR')) return;
        
        // Default options (add_option only adds if not exists)
        add_option('mamba_enable_page_cache', 0);
        add_option('mamba_enable_store_api_cache', 0); // Store API caching (Premium feature)
        add_option('mamba_cache_ttl', 7200); // 2 hours for better hit rates
        add_option('mamba_browser_ttl', 300); // 5 minutes for better hit rates
        add_option('mamba_store_api_browser_ttl', 300); // 5 minutes for better hit rates
        add_option('mamba_store_api_ttl', 600);
        add_option('mamba_cache_size_limit', 200 * 1024 * 1024); // 200MB default
        add_option('mamba_cdn_ttl', 7200); // 2 hours CDN cache
        add_option('mamba_stale_if_error', 86400); // 24 hours stale-if-error
        add_option('mamba_cache_stats', ['cache_hits'=>0,'cache_misses'=>0,'cache_size'=>0,'last_cleared'=>0], '', 'no');
        add_option('mamba_daily_stats', [], '', 'no');
        add_option('mamba_warmup_stats', [], '', 'no');
        add_option('mamba_enable_priority_warmup', 0);
        
        // Ensure daily cleanup scheduled for this site
        if (!wp_next_scheduled('mamba_cache_cleanup')) {
            wp_schedule_event(time(), 'daily', 'mamba_cache_cleanup');
        }
        
        // Migrate existing autoloaded options to non-autoloaded
        self::migrateAutoloadedOptions();
        
        // Migration: Update browser TTL defaults for existing installations
        self::migrateBrowserTtlDefaults();
    }
    
    /**
     * Migrate existing autoloaded options to non-autoloaded
     */
    private static function migrateAutoloadedOptions(): void {
        global $wpdb;
        
        // Ensure our own options are seeded non-autoloaded
        add_option('mamba_cache_stats', ['cache_hits'=>0,'cache_misses'=>0,'cache_size'=>0,'last_cleared'=>0], '', 'no');
        add_option('mamba_daily_stats', [], '', 'no');
        add_option('mamba_warmup_stats', [], '', 'no');
        add_option('mamba_stats_last_write', 0, '', 'no');
        add_option('mamba_browser_ttl', 300, '', 'no'); // 5 minutes for better hit rates
        add_option('mamba_store_api_browser_ttl', 300, '', 'no'); // 5 minutes for better hit rates
        add_option('mamba_ns_mamba_store_api', '1', '', 'no');
        add_option('mamba_ns_mamba_tags', '1', '', 'no');
        add_option('mamba_ns_mamba_stats', '1', '', 'no');
        add_option('mamba_ns_mamba_cart_fragments', '1', '', 'no');
        
        // Migration: flip any existing plugin options that ended up autoloaded
        $prefixes = ['mamba_cache_', 'mamba_daily_', 'mamba_warmup_', 'mamba_stats_', 'mamba_browser_', 'mamba_store_api_', 'mamba_'];
        foreach ($prefixes as $p) {
            $wpdb->query($wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
                "UPDATE {$wpdb->options} 
                 SET autoload='no' 
                 WHERE autoload='yes' AND option_name LIKE %s",
                $wpdb->esc_like($p) . '%'
            ));
        }
    }
    
    /**
     * Migrate browser TTL defaults for existing installations
     */
    private static function migrateBrowserTtlDefaults(): void {
        // Update browser TTL defaults if they're still at 0 (old default) or very low values
        $browserTtl = get_option('mamba_browser_ttl');
        if ($browserTtl === '0' || $browserTtl === 0 || $browserTtl < 300) {
            update_option('mamba_browser_ttl', 300); // 5 minutes for better hit rates
        }
        
        $storeApiBrowserTtl = get_option('mamba_store_api_browser_ttl');
        if ($storeApiBrowserTtl === '0' || $storeApiBrowserTtl === 0 || $storeApiBrowserTtl < 300) {
            update_option('mamba_store_api_browser_ttl', 300); // 5 minutes for better hit rates
        }
    }
    
    /**
     * Create protection files in cache directory
     */
    private static function createProtectionFiles(string $cacheDir): void {
        // Create index.html to prevent directory listing
        $indexFile = $cacheDir . '/index.html';
        if (!file_exists($indexFile)) {
            @file_put_contents($indexFile, '<!-- Directory access denied -->');
        }
        
        // Create .htaccess for Apache protection - DENY ALL ACCESS
        $htaccessFile = $cacheDir . '/.htaccess';
        if (!file_exists($htaccessFile)) {
            $htaccessContent = "<IfModule mod_authz_core.c>\n  Require all denied\n</IfModule>\n<IfModule !mod_authz_core.c>\n  Deny from all\n</IfModule>\n";
            @file_put_contents($htaccessFile, $htaccessContent);
        }
    }
}
