<?php
/**
 * CDN Detectors Service
 *
 * Provides detection utilities for CDN features including Cloudflare APO,
 * Rocket Loader, and header combination generation for cache key variants.
 *
 * @package Mamba\Modules\CDN\Services
 * @since   1.0.0
 */

namespace Mamba\Modules\CDN\Services;

/**
 * Class Detectors
 *
 * Detects CDN features like Cloudflare APO and Rocket Loader,
 * and generates header combinations for APO cache key purging.
 *
 * @since 1.0.0
 */
final class Detectors {
    
    /**
     * Check if Cloudflare APO is active
     */
    public static function isCloudflareAPO(): bool {
        // Header from edge (strongest signal)
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Only checking existence, not using value
        if (!empty($_SERVER['HTTP_CF_APO_VIA'])) {
            return true;
        }

        // Official CF plugin setting (when present)
        if (class_exists('CF\WordPress\Hooks')) {
            // name used by CF plugin for APO; adjust if their option differs
            $apo = get_option('cloudflare_apo_enabled');
            if (!empty($apo)) {
                return true;
            }
        }

        // Check if our detection is enabled and we have a cached APO status
        if (get_option('mamba_cloudflare_detect_apo', true)) {
            $cachedApoStatus = get_option('mamba_cloudflare_apo_status');
            if ($cachedApoStatus === 'enabled') {
                return true;
            }
        }

        // Our toggle should mean "attempt to detect", not "assume true"
        // So: do NOT return true just because mamba_cloudflare_detect_apo is enabled.
        return false;
    }
    
    /**
     * Generate Cloudflare header combinations for APO/custom cache keys
     */
    public static function generateCloudflareHeaderCombos(): array {
        if (!self::isCloudflareAPO()) {
            return [];
        }
        
        $combos = [];
        
        // Device types (APO standard)
        $devices = ['desktop', 'mobile'];
        
        // Primary languages (site's primary languages)
        $languages = self::getPrimaryLanguages();
        
        // Countries (only if geo is enabled and affects content)
        $countries = self::getGeoCountries();
        
        // Check if Rocket Loader affects cache keys
        $rocketLoaderEnabled = self::isRocketLoaderEnabled();
        
        // Generate combinations
        foreach ($devices as $device) {
            foreach ($languages as $lang) {
                if (!empty($countries)) {
                    foreach ($countries as $country) {
                        $combo = [
                            'CF-Device-Type' => $device,
                            'Accept-Language' => $lang,
                            'CF-IPCountry' => $country
                        ];
                        
                        // Add Rocket Loader header if it affects cache keys
                        if ($rocketLoaderEnabled) {
                            $combo['CF-Requested-With'] = 'XMLHttpRequest';
                        }
                        
                        $combos[] = $combo;
                    }
                } else {
                    $combo = [
                        'CF-Device-Type' => $device,
                        'Accept-Language' => $lang
                    ];
                    
                    // Add Rocket Loader header if it affects cache keys
                    if ($rocketLoaderEnabled) {
                        $combo['CF-Requested-With'] = 'XMLHttpRequest';
                    }
                    
                    $combos[] = $combo;
                }
            }
        }
        
        // Return at least one combination if none generated
        if (empty($combos)) {
            $combo = [
                'CF-Device-Type' => 'desktop',
                'Accept-Language' => 'en'
            ];
            
            if ($rocketLoaderEnabled) {
                $combo['CF-Requested-With'] = 'XMLHttpRequest';
            }
            
            $combos[] = $combo;
        }
        
        return $combos;
    }
    
    /**
     * Get primary languages for the site
     */
    private static function getPrimaryLanguages(): array {
        $languages = ['en', 'en-US'];
        
        // Check for Polylang
        if (function_exists('pll_current_language')) {
            $currentLang = pll_current_language();
            if ($currentLang) {
                $languages = array_unique(array_merge($languages, [$currentLang]));
            }
        }
        
        // Check for WPML
        if (defined('ICL_LANGUAGE_CODE')) {
            $wpmlLang = ICL_LANGUAGE_CODE;
            if ($wpmlLang) {
                $languages = array_unique(array_merge($languages, [$wpmlLang]));
            }
        }
        
        // Allow filtering
        return apply_filters('mamba_cdn_primary_languages', $languages);
    }
    
    /**
     * Get geo countries for cache key
     */
    private static function getGeoCountries(): array {
        $countries = [];
        
        // Check if geo is enabled in WooCommerce
        if (get_option('woocommerce_default_customer_address') === 'geolocation_ajax') {
            // Get common countries from WooCommerce settings
            $wcCountries = \WC()->countries ?? null;
            if ($wcCountries) {
                $allCountries = $wcCountries->get_countries();
                // Default small set; sites can expand via filter
                $defaultTop = ['US', 'CA', 'GB'];
                $topCountries = (array) apply_filters('mamba_cdn_geo_top_countries', $defaultTop);
                // Safety cap on list length
                $maxCountries = (int) apply_filters('mamba_cdn_geo_max_countries', 5);
                $topCountries = array_slice(array_unique(array_filter($topCountries)), 0, max(0, $maxCountries));
                foreach ($topCountries as $code) {
                    if (isset($allCountries[$code])) {
                        $countries[] = $code;
                    }
                }
            }
        }
        
        // Allow final filtering
        return apply_filters('mamba_cdn_geo_countries', $countries);
    }
    
    /**
     * Check if Cloudflare plugin is active and configured
     */
    public static function isCloudflarePluginActive(): bool {
        if (!class_exists('CF\WordPress\Hooks')) {
            return false;
        }
        
        $apiToken = get_option('cloudflare_api_token');
        $zoneId = get_option('cloudflare_zone_id');
        
        return !empty($apiToken) && !empty($zoneId);
    }
    
    /**
     * Check if Rocket Loader is enabled and affects cache keys
     */
    public static function isRocketLoaderEnabled(): bool {
        // Check if Rocket Loader is enabled via Cloudflare plugin
        if (class_exists('CF\WordPress\Hooks')) {
            $rocketLoader = get_option('cloudflare_rocket_loader');
            if ($rocketLoader === 'on') {
                return true;
            }
        }
        
        // Check if Rocket Loader is enabled via our settings
        // This would be set when "Apply Recommended Settings" is used
        $rocketLoader = get_option('mamba_cloudflare_rocket_loader_status');
        if ($rocketLoader === 'on') {
            return true;
        }
        
        // Default: assume Rocket Loader is off for cache key safety
        return false;
    }
    
    /**
     * Get Cloudflare plugin credentials
     */
    public static function getCloudflarePluginCredentials(): array {
        if (!self::isCloudflarePluginActive()) {
            return [];
        }
        
        // Try multiple possible option names for better compatibility
        $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 [
            'api_token' => $apiToken,
            'zone_id' => $zoneId
        ];
    }
}
