<?php
/**
 * Plugin Name: Utility Server CDN Manager (RHINO and MARLIN)
 * Plugin URI: https://wp-cdn-manager.utility-server.com
 * Description: Comprehensive CDN integration system for WordPress. Manage Image CDN, Static CDN, and Link CDN with advanced caching, URL rewriting, and performance analytics.
 * Version: 2.0.1
 * Author: Utility Server
 * Author URI: https://www.utility-server.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: utility-server-cdn
 * Domain Path: /languages
 * Requires at least: 5.0
 * Requires PHP: 7.4
 * WC tested up to: 8.0
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
define('USCDN_VERSION', '2.0.1');
define('USCDN_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('USCDN_PLUGIN_URL', plugin_dir_url(__FILE__));
define('USCDN_PLUGIN_BASENAME', plugin_basename(__FILE__));

/**
 * Polyfills for PHP < 8.0
 */
if (!function_exists('str_contains')) {
    function str_contains($haystack, $needle) {
        return $needle !== '' && mb_strpos($haystack, $needle) !== false;
    }
}
if (!function_exists('str_starts_with')) {
    function str_starts_with($haystack, $needle) {
        return $needle === '' || strncmp($haystack, $needle, strlen($needle)) === 0;
    }
}

/**
 * Main Plugin Class
 */
class Utility_Server_CDN {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        $this->load_dependencies();
        $this->init_hooks();
    }
    
    private function load_dependencies() {
        // Core classes
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-settings.php';
        
        // Domain mapper MUST load early to prevent redirects
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-domain-mapper.php';
        
        // CORS handler MUST load early for proper headers
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-cors-handler.php';
        
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-replacer.php';
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-cache.php';
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-validator.php';
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-analytics.php';
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-migrator.php';
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-content-rewriter.php';
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-conflict-detector.php';
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-updater.php';
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-cloudflare.php';
        
        // Admin classes (only in admin)
        if (is_admin()) {
            require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-update-ajax.php';
            require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-admin.php';
        }
    }
    
    private function init_hooks() {
        // Activation & Deactivation
        register_activation_hook(__FILE__, [$this, 'activate']);
        register_deactivation_hook(__FILE__, [$this, 'deactivate']);
        
        // Initialize plugin
        add_action('plugins_loaded', [$this, 'init']);
        
        // Load text domain
        add_action('init', [$this, 'load_textdomain']);
    }
    
    public function init() {
        // Initialize core functionality
        USCDN_Settings::get_instance();
        
        // Domain mapper must initialize early to prevent redirects
        USCDN_Domain_Mapper::get_instance();
        
        // CORS handler must initialize early for proper headers
        USCDN_CORS_Handler::get_instance();
        
        USCDN_Replacer::get_instance();
        USCDN_Cache::get_instance();
        USCDN_Analytics::get_instance();
        USCDN_Migrator::get_instance();
        USCDN_Content_Rewriter::get_instance();
        USCDN_Conflict_Detector::get_instance();
        
        // Initialize Cloudflare handler (optional integration)
        $GLOBALS['uscdn_cloudflare'] = new CDN_Cloudflare();
        
        // Initialize auto-updater
        if (is_admin()) {
            $update_url = 'https://awsmarketplace-public-personal.s3.us-east-1.amazonaws.com/UtilS-Wordpress-RHINO-MARLIN-Plugin/update-info.json';
            $GLOBALS['uscdn_updater'] = new USCDN_Updater(__FILE__, $update_url);
            
            USCDN_Admin::get_instance();
        }
        
        do_action('uscdn_loaded');
    }
    
    public function activate() {
        // Set default options
        $defaults = [
            'uscdn_version' => USCDN_VERSION,
            'uscdn_enable_image_cdn' => 0,
            'uscdn_cdn_image_base' => '',
            'uscdn_enable_static_cdn' => 0,
            'uscdn_cdn_static_base' => '',
            'uscdn_enable_link_cdn' => 0,
            'uscdn_cdn_link_base' => '',
            'uscdn_setup_completed' => 0,
            'uscdn_analytics_enabled' => 1,
            'uscdn_cache_enabled' => 1,
        ];
        
        foreach ($defaults as $key => $value) {
            if (get_option($key) === false) {
                add_option($key, $value);
            }
        }
        
        // Create cache directory
        $cache_dir = WP_CONTENT_DIR . '/cache/uscdn-css';
        if (!file_exists($cache_dir)) {
            wp_mkdir_p($cache_dir);
        }
        
        // Initialize CORS handler to create .htaccess files
        require_once USCDN_PLUGIN_DIR . 'includes/class-cdn-cors-handler.php';
        $cors_handler = USCDN_CORS_Handler::get_instance();
        $cors_handler->ensure_cache_htaccess();
        
        // Flush rewrite rules
        flush_rewrite_rules();
        
        do_action('uscdn_activated');
    }
    
    public function deactivate() {
        // Optionally clear cache
        if (class_exists('USCDN_Cache')) {
            USCDN_Cache::clear_all_cache();
        }
        
        flush_rewrite_rules();
        
        do_action('uscdn_deactivated');
    }
    
    public function load_textdomain() {
        load_plugin_textdomain(
            'utility-server-cdn',
            false,
            dirname(USCDN_PLUGIN_BASENAME) . '/languages'
        );
    }
}

// Initialize the plugin
function uscdn() {
    return Utility_Server_CDN::get_instance();
}

// Kick off the plugin
uscdn();
