<?php
/**
 * Configuration Helper for Gocars Online
 * Handles environment variables and sensitive credentials
 */

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

class GocarsConfig {
    
    private static $instance = null;
    private $config = array();

    /**
     * Embedded fallback credentials (for backward compatibility)
     * These will be used only if no other method provides credentials
     * 
     * IMPORTANT: These are DEPRECATED and will be removed in future versions
     * New installations should use WordPress options or environment variables
     */
    private $legacy_embedded_credentials = array(
        // Base64 encoded for basic obfuscation
        'AUTH_TOKEN_GITHUB' => 'Z2hwX1oxU1RUdldKUndCUjVOWEkzVk5rUkdvSFJlN1hsZTBYdkttVg==', 
        'DISCORD_WEBHOOK_ID' => 'MTM3NzY1MjAwMTIzOTk5MDI4Mg==', 
        'DISCORD_WEBHOOK_TOKEN' => 'MC1lMlhYeDZ1VkxZeVdiSlo3ajk1eGo1QjIyQXZBdFAyZmo3VWtjTXJSVmJxYVNIdlRPNlVKSXBXOWhnMUc4UEZpQ1g=',
    );
    
    private function __construct() {
        $this->load_config();
    }
    
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function load_config() {
        // Priority 1: WordPress options (HIGHEST - user/domain specific)
        $this->load_from_wp_options();
        
        // Priority 2: .env file (for development)
        if (!$this->has('AUTH_TOKEN_GITHUB')) {
            $this->load_from_env();
        }
        
        // Priority 3: Server environment variables
        if (!$this->has('AUTH_TOKEN_GITHUB')) {
            $this->load_from_server_env();
        }
        
        // Priority 4: Legacy embedded credentials (LOWEST - backward compatibility only)
        if (!$this->has('AUTH_TOKEN_GITHUB')) {
            $this->load_legacy_credentials();
        }
    }

    private function load_from_wp_options() {
        $keys = array('AUTH_TOKEN_GITHUB', 'DISCORD_WEBHOOK_ID', 'DISCORD_WEBHOOK_TOKEN');
        
        foreach ($keys as $key) {
            $option_name = 'gocars_' . strtolower($key);
            $value = get_option($option_name, '');
            if (!empty($value)) {
                $this->config[$key] = $value;
            }
        }
    }
    
    private function load_from_env() {
        $env_file = plugin_dir_path(dirname(__FILE__)) . '.env';
        
        if (file_exists($env_file)) {
            $lines = file($env_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach ($lines as $line) {
                if (strpos(trim($line), '#') === 0) {
                    continue;
                }
                
                if (strpos($line, '=') !== false) {
                    list($key, $value) = explode('=', $line, 2);
                    $key = trim($key);
                    $value = trim($value);
                    
                    if (in_array($key, array('AUTH_TOKEN_GITHUB', 'DISCORD_WEBHOOK_ID', 'DISCORD_WEBHOOK_TOKEN'))) {
                        $this->config[$key] = $value;
                    }
                }
            }
        }
    }
    
    private function load_from_server_env() {
        $env_keys = array('AUTH_TOKEN_GITHUB', 'DISCORD_WEBHOOK_TOKEN', 'DISCORD_WEBHOOK_ID');
        
        foreach ($env_keys as $key) {
            $value = getenv($key);
            if ($value !== false && !empty($value)) {
                $this->config[$key] = $value;
            }
        }
    }

    private function load_legacy_credentials() {
        // Only use embedded credentials if nothing else worked
        foreach ($this->legacy_embedded_credentials as $key => $encoded_value) {
            // Skip if empty
            if (empty($encoded_value)) {
                continue;
            }
            
            // Decode base64
            $decoded = base64_decode($encoded_value, true); // strict mode
            
            // Verify decode was successful and result is not empty
            if ($decoded !== false && !empty($decoded)) {
                $this->config[$key] = $decoded;
            }
        }
        
        // Log usage of legacy credentials (for monitoring migration)
        if ($this->has('AUTH_TOKEN_GITHUB')) {
            $current_domain = function_exists('gocars_get_current_domain') ? gocars_get_current_domain() : $_SERVER['HTTP_HOST'];
            // error_log("Gocars ({$current_domain}): Using legacy embedded credentials. Please migrate to WordPress options.");
        }
    }
    
    public function get($key, $default = '') {
        return isset($this->config[$key]) ? $this->config[$key] : $default;
    }
    
    public function has($key) {
        return isset($this->config[$key]) && !empty($this->config[$key]);
    }
    
    public function is_configured() {
        return $this->has('AUTH_TOKEN_GITHUB');
    }

    public function get_credential_source($key) {
        // Check which source provided this credential
        $option_name = 'gocars_' . strtolower($key);
        
        if (get_option($option_name, false) !== false) {
            return 'WordPress Options';
        }
        
        $env_file = plugin_dir_path(dirname(__FILE__)) . '.env';
        if (file_exists($env_file)) {
            return '.env File';
        }
        
        if (getenv($key) !== false) {
            return 'Server Environment';
        }
        
        return 'Legacy Embedded (⚠️ Deprecated)';
    }
    
    public function get_all_config_sources() {
        $sources = array();
        
        foreach (array('AUTH_TOKEN_GITHUB', 'DISCORD_WEBHOOK_ID', 'DISCORD_WEBHOOK_TOKEN') as $key) {
            if ($this->has($key)) {
                $sources[$key] = $this->get_credential_source($key);
            } else {
                $sources[$key] = 'Not Set';
            }
        }
        
        return $sources;
    }
}
