<?php
/**
 * Main Plugin Bootstrap Class
 *
 * Initializes all plugin modules, registers hooks for multisite support,
 * and coordinates the overall plugin functionality.
 *
 * @package Mamba
 * @since   1.0.0
 */

namespace Mamba;

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

use Mamba\Settings\AdminPage;
use Mamba\Modules\Caching\Module as CachingModule;
use Mamba\Modules\Bloat\Module as BloatModule;
use Mamba\Modules\Media\Module as MediaModule;
use Mamba\Modules\DB\Module as DbModule;
use Mamba\Modules\CDN\Module as CdnModule;
use Mamba\Modules\Logs\Module as LogsModule;
use Mamba\Modules\CriticalCss\Module as CriticalCssModule;
use Mamba\Lifecycle\Welcome;
use Mamba\Lifecycle\Activator;
use Mamba\Lifecycle\ConflictDetector;

/**
 * Class Plugin
 *
 * Core plugin class that bootstraps all modules and handles multisite events.
 *
 * @since 1.0.0
 */
final class Plugin {

    /**
     * Constructor
     *
     * @param string $file Main plugin file path.
     */
    public function __construct(private string $file) {}

    /**
     * Boot the plugin
     *
     * Initializes all modules, registers admin pages, and sets up multisite hooks.
     *
     * @return void
     */
    public function boot(): void {
        $paths = new \Mamba\Support\Paths($this->file);
        // Licensing and Updates removed in favor of Freemius

        (new AdminPage($paths))->register();
        (new CachingModule($paths))->register();
        (new BloatModule())->register();
        (new MediaModule())->register();
        (new DbModule())->register();
        (new CdnModule())->register();
        (new LogsModule())->register();
        (new CriticalCssModule())->register();
        
        // Register CDN controller
        (new \Mamba\Modules\CDN\Controller())->register();
        
        // Register welcome modal for first-time activation
        Welcome::register();
        
        // Register caching plugin conflict detector
        ConflictDetector::register();
        
        // Multisite: Initialize plugin when a new site is created
        add_action('wp_initialize_site', [$this, 'onNewSiteCreated'], 10, 1);
        
        // Multisite: Clean up when a site is deleted
        add_action('wp_uninitialize_site', [$this, 'onSiteDeleted'], 10, 1);
    }
    
    /**
     * Initialize plugin for a newly created site in the network
     * Only runs if the plugin is network-activated
     * 
     * @param \WP_Site $newSite The new site object
     */
    public function onNewSiteCreated(\WP_Site $newSite): void {
        // Only initialize if plugin is network-activated
        if (!is_plugin_active_for_network(plugin_basename($this->file))) {
            return;
        }
        
        switch_to_blog($newSite->blog_id);
        Activator::activateSingleSite();
        restore_current_blog();
    }
    
    /**
     * Clean up when a site is deleted from the network
     * Removes the site's cache directory
     * 
     * @param \WP_Site $oldSite The site being deleted
     */
    public function onSiteDeleted(\WP_Site $oldSite): void {
        // Get the site's home URL to determine cache path
        switch_to_blog($oldSite->blog_id);
        $homeUrl = home_url();
        restore_current_blog();
        
        // Clean up the site's cache directory
        $host = parse_url($homeUrl, PHP_URL_HOST);
        if ($host && defined('WP_CONTENT_DIR')) {
            $siteDir = WP_CONTENT_DIR . '/cache/mamba/' . strtolower($host);
            if (is_dir($siteDir)) {
                $it = new \RecursiveIteratorIterator(
                    new \RecursiveDirectoryIterator($siteDir, \RecursiveDirectoryIterator::SKIP_DOTS),
                    \RecursiveIteratorIterator::CHILD_FIRST
                );
                foreach ($it as $fi) {
                    $todo = $fi->isDir() ? 'rmdir' : 'unlink';
                    @$todo($fi->getRealPath());
                }
                @rmdir($siteDir);
            }
        }
    }
}
