<?php
/**
 * CDN Manager Service
 *
 * Handles CDN provider selection, initialization, and credential management
 * for Cloudflare, Bunny CDN, and generic webhook integrations.
 *
 * @package Mamba\Modules\CDN\Services
 * @since   1.0.0
 */

namespace Mamba\Modules\CDN\Services;

/**
 * Class Manager
 *
 * CDN Manager that handles provider selection and initialization,
 * credential retrieval, and Cloudflare plugin integration.
 *
 * @since 1.0.0
 */
final class Manager {
    private static ?Provider $provider = null;
    private static bool $initialized = false;
    
    /**
     * Initialize the CDN manager
     */
    public static function init(): void {
        if (self::$initialized) return;
        
        $provider = self::getProviderFromSettings();
        if ($provider && $provider->isConnected()) {
            self::$provider = $provider;
        }
        
        self::$initialized = true;
    }
    
    /**
     * Get the active provider
     */
    public static function getProvider(): ?Provider {
        if (!self::$initialized) {
            self::init();
        }
        return self::$provider;
    }
    
    /**
     * Get the provider name
     */
    public static function getProviderName(): string {
        $provider = self::getProvider();
        return $provider ? $provider->getName() : '';
    }
    
    /**
     * Check if CDN is enabled
     */
    public static function isEnabled(): bool {
        return self::getProvider() !== null;
    }
    
    /**
     * Create provider from settings
     */
    private static function getProviderFromSettings(): ?Provider {
        $providerType = get_option('mamba_cdn_provider', 'disabled');

        // Create provider based on settings
        switch ($providerType) {
            case 'cloudflare':
                $credentials = self::getCloudflareCredentials();
                return new CloudflareAdapter(
                    $credentials['zone_id'],
                    $credentials['api_token'],
                    get_option('mamba_cloudflare_detect_apo', true),
                    get_option('mamba_cloudflare_send_cache_tags', true)
                );
                
            case 'bunny':
                return new BunnyAdapter(
                    get_option('mamba_bunny_pull_zone_id', ''),
                    get_option('mamba_bunny_api_key', ''),
                    get_option('mamba_bunny_send_cdn_tags', true),
                    get_option('mamba_bunny_use_wildcard_purges', false)
                );
                
            case 'fastly':
                return new FastlyAdapter(
                    get_option('mamba_fastly_service_id', ''),
                    get_option('mamba_fastly_api_token', ''),
                    get_option('mamba_fastly_send_surrogate_keys', true),
                    get_option('mamba_fastly_soft_purge', true)
                );
                
            case 'generic':
                return new GenericWebhookAdapter(
                    get_option('mamba_generic_webhook_url', ''),
                    get_option('mamba_generic_webhook_secret', '')
                );
                
            default:
                return null;
        }
    }
    
    /**
     * Check if Cloudflare plugin is active and configured
     */
    private static function hasCloudflarePlugin(): bool {
        // Check if Cloudflare plugin class exists
        if (!class_exists('CF\WordPress\Hooks')) {
            return false;
        }
        
        // Check if Cloudflare plugin has API credentials - try multiple possible option names
        $apiToken = get_option('cloudflare_api_token') ?: get_option('cf_api_token') ?: get_option('cloudflare_api_key');
        $zoneId = get_option('cloudflare_zone_id') ?: get_option('cf_zone_id');
        
        return !empty($apiToken) && !empty($zoneId);
    }
    
    /**
     * Get Cloudflare plugin status for UI feedback
     */
    public static function getCloudflarePluginStatus(): array {
        $status = [
            'plugin_active' => false,
            'has_credentials' => false,
            'message' => '',
            'debug_info' => []
        ];
        
        // Check if plugin class exists
        if (!class_exists('CF\WordPress\Hooks')) {
            $status['message'] = 'Official Cloudflare plugin not installed or not active.';
            return $status;
        }
        
        $status['plugin_active'] = true;
        
        // Debug: Check what options the plugin actually stores
        $possibleOptions = [
            'cloudflare_api_token',
            'cloudflare_zone_id',
            'cloudflare_api_key',
            'cloudflare_email',
            'cf_api_token',
            'cf_zone_id',
            'cf_api_key',
            'cf_email'
        ];
        
        $foundOptions = [];
        foreach ($possibleOptions as $option) {
            $value = get_option($option);
            if (!empty($value)) {
                $foundOptions[$option] = $value;
            }
        }
        
        $status['debug_info'] = $foundOptions;
        
        // Check credentials - try multiple possible option names
        $apiToken = get_option('cloudflare_api_token') ?: get_option('cf_api_token') ?: get_option('cloudflare_api_key');
        $zoneId = get_option('cloudflare_zone_id') ?: get_option('cf_zone_id');
        
        if (empty($apiToken) || empty($zoneId)) {
            $status['message'] = 'Official Cloudflare plugin detected but not configured (missing API token or Zone ID).';
            if (!empty($foundOptions)) {
                $status['message'] .= ' Found options: ' . implode(', ', array_keys($foundOptions));
            }
            return $status;
        }
        
        $status['has_credentials'] = true;
        $status['message'] = 'Official Cloudflare plugin detected and configured.';
        
        return $status;
    }
    
    /**
     * Get Cloudflare credentials - automatically use plugin credentials if available, otherwise use our settings
     */
    private static function getCloudflareCredentials(): array {
        // Try plugin credentials first (API token or global API key + email)
        $pluginToken = get_option('cloudflare_api_token') ?: get_option('cf_api_token');
        $pluginZoneId = get_option('cloudflare_zone_id') ?: get_option('cf_zone_id');
        
        // If plugin has both token and zone ID, use them
        if (!empty($pluginToken) && !empty($pluginZoneId)) {
            return [
                'zone_id' => $pluginZoneId,
                'api_token' => $pluginToken
            ];
        }
        
        // Fall back to our settings
        return [
            'zone_id' => get_option('mamba_cloudflare_zone_id', ''),
            'api_token' => get_option('mamba_cloudflare_api_token', '')
        ];
    }
}
