<?php
/**
 * Endpoint Configuration Manager
 * 
 * Fetches and caches API endpoint URLs from the server dynamically.
 * Eliminates hardcoded URLs and enables zero-downtime endpoint changes.
 *
 * @package    VMPFence
 * @subpackage Lib
 * @since      1.0.0
 */

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

class VMPFence_Endpoint_Config {
    
    /**
     * Cache key for endpoint configuration
     */
    const CACHE_KEY = 'vmpfence_endpoint_config';
    
    /**
     * Cache expiration (12 hours)
     */
    const CACHE_EXPIRATION = 43200;
    
    /**
     * Fallback API base URL (obfuscated, decoded at runtime)
     * Base64 encoded: https://newton-wordpress-security.vpnmasterpro.com/api/v1
     */
    const FALLBACK_API_ENCODED = 'aHR0cHM6Ly9uZXd0b24td29yZHByZXNzLXNlY3VyaXR5LnZwbm1hc3RlcnByby5jb20vYXBpL3Yx';
    
    /**
     * Get fallback API URL (decoded from obfuscated constant)
     * 
     * @return string Fallback API base URL
     */
    private static function get_fallback_url() {
        return base64_decode(self::FALLBACK_API_ENCODED);
    }
    
    /**
     * Get endpoint configuration (cached)
     * 
     * @param bool $force_refresh Force refresh from server
     * @return array Endpoint configuration
     */
    public static function get_config($force_refresh = false) {
        // Try to get from cache first
        if (!$force_refresh) {
            $cached = get_transient(self::CACHE_KEY);
            if ($cached !== false && is_array($cached)) {
                return $cached;
            }
        }
        
        // Fetch fresh configuration from server
        $config = self::fetch_from_server();
        
        // Cache for 12 hours
        if ($config && is_array($config)) {
            set_transient(self::CACHE_KEY, $config, self::CACHE_EXPIRATION);
            return $config;
        }
        
        // Fallback to defaults if fetch failed
        return self::get_default_config();
    }
    
    /**
     * Fetch endpoint configuration from server
     * 
     * @return array|false Configuration array or false on failure
     */
    private static function fetch_from_server() {
        // Use fallback URL for the fetch endpoint itself
        $endpoint_url = self::get_fallback_url() . '/system/config/endpoints';
        
        VMPFence_Secure_Logger::debug('Fetching endpoint configuration from server');
        
        // Make request to server
        $response = wp_remote_get($endpoint_url, [
            'timeout' => 10,
            'redirection' => 5, // Explicitly follow up to 5 redirects
            'sslverify' => true, // Always verify SSL certificates
            'httpversion' => '1.1',
            'headers' => [
                'User-Agent' => 'VMPFence/' . VMPFENCE_VERSION,
                'Accept' => 'application/json'
            ]
        ]);
        
        // Check for errors
        if (is_wp_error($response)) {
            VMPFence_Secure_Logger::error('Failed to fetch endpoint config', [
                'error' => $response->get_error_message(),
                'endpoint_url' => $endpoint_url
            ]);
            return false;
        }
        
        // Log successful response details
        $response_code = wp_remote_retrieve_response_code($response);
        $headers = wp_remote_retrieve_headers($response);
        VMPFence_Secure_Logger::debug('Endpoint config response received', [
            'code' => $response_code,
            'endpoint_url' => $endpoint_url,
            'headers' => $headers->getAll() // Get all headers for debugging
        ]);
        
        // Check response code
        if ($response_code !== 200) {
            $body = wp_remote_retrieve_body($response);
            VMPFence_Secure_Logger::error('Endpoint config fetch returned non-200', [
                'code' => $response_code,
                'endpoint_url' => $endpoint_url,
                'response_body' => substr($body, 0, 500) // First 500 chars for debugging
            ]);
            return false;
        }
        
        // Parse JSON
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data || !is_array($data)) {
            VMPFence_Secure_Logger::error('Invalid endpoint config response', [
                'json_error' => json_last_error_msg(),
                'body_preview' => substr($body, 0, 200)
            ]);
            return false;
        }
        
        // Validate required fields
        $required_fields = ['api_base_url', 'update_api_url', 'docs_url', 'support_url'];
        foreach ($required_fields as $field) {
            if (empty($data[$field])) {
                VMPFence_Secure_Logger::error('Missing required field in config', ['field' => $field]);
                return false;
            }
        }
        
        // Ensure endpoint_map exists
        if (!isset($data['endpoint_map'])) {
            $data['endpoint_map'] = array();
        }
        if (!isset($data['map_version'])) {
            $data['map_version'] = '1.0';
        }
        
        VMPFence_Secure_Logger::info('Endpoint configuration fetched successfully', [
            'version' => $data['version'] ?? 'unknown',
            'endpoint_count' => is_array($data['endpoint_map']) ? count($data['endpoint_map']) : 0,
            'map_version' => $data['map_version']
        ]);
        
        return $data;
    }
    
    /**
     * Get default/fallback configuration
     * 
     * @return array Default configuration
     */
    private static function get_default_config() {
        $fallback_url = self::get_fallback_url();
        return [
            'api_base_url' => $fallback_url,
            'update_api_url' => $fallback_url . '/plugin/check-update',
            'docs_url' => 'https://newton-wordpress-security.vpnmasterpro.com/docs',
            'support_url' => 'https://newton-wordpress-security.vpnmasterpro.com/support',
            'cdn_url' => '',
            'endpoint_map' => array(),  // Empty map - will use fallback paths
            'map_version' => '1.0',
            'version' => 'fallback',
            'last_updated' => gmdate('Y-m-d\TH:i:s\Z')
        ];
    }
    
    /**
     * Get API base URL
     * 
     * @return string API base URL
     */
    public static function get_api_base_url() {
        $config = self::get_config();
        return $config['api_base_url'];
    }
    
    /**
     * Get update API URL
     * 
     * @return string Update API URL
     */
    public static function get_update_api_url() {
        $config = self::get_config();
        return $config['update_api_url'];
    }
    
    /**
     * Get docs URL
     * 
     * @return string Documentation URL
     */
    public static function get_docs_url() {
        $config = self::get_config();
        return $config['docs_url'];
    }
    
    /**
     * Get support URL
     * 
     * @return string Support URL
     */
    public static function get_support_url() {
        $config = self::get_config();
        return $config['support_url'];
    }
    
    /**
     * Get CDN URL
     * 
     * @return string CDN URL
     */
    public static function get_cdn_url() {
        $config = self::get_config();
        return $config['cdn_url'] ?? '';
    }
    
    /**
     * Clear cached configuration (force refresh on next request)
     */
    public static function clear_cache() {
        delete_transient(self::CACHE_KEY);
        VMPFence_Secure_Logger::info('Endpoint configuration cache cleared');
    }
    
    /**
     * Fetch configuration on plugin activation
     */
    public static function on_activation() {
        // Force fresh fetch and cache
        self::get_config(true);
        VMPFence_Secure_Logger::info('Endpoint configuration initialized on activation');
    }
}
