<?php
/**
 * Theme Manager Service
 * 
 * Handles theme selection and configuration reading from YAML files
 * 
 * @package AtomicEvents
 * @since 1.0.0
 */

defined('WPINC') or die;

class ATMCEVNTS_Theme_Manager {
    
    private static $selected_theme = null;
    private static $theme_config = null;
    
    /**
     * Get the currently selected theme
     * 
     * @return string Theme name (default: 'default')
     */
    public static function get_selected_theme() {
        if (self::$selected_theme === null) {
            self::$selected_theme = self::read_theme_from_config();
        }
        return self::$selected_theme;
    }
    
    /**
     * Get theme configuration data
     * 
     * @return array|null Theme configuration or null if not found
     */
    public static function get_theme_config($theme_name = null) {
        if ($theme_name === null) {
            $theme_name = self::get_selected_theme();
        }
        
        if (self::$theme_config === null || !isset(self::$theme_config[$theme_name])) {
            self::$theme_config = self::load_theme_config($theme_name);
        }
        
        return isset(self::$theme_config[$theme_name]) ? self::$theme_config[$theme_name] : null;
    }
    
    /**
     * Read theme selection from YAML configuration files
     * 
     * @return string Theme name
     */
    private static function read_theme_from_config() {
        // Check child theme first
        $child_theme_path = get_stylesheet_directory() . '/atomic-events/atomic-events-settings.yml';
        if (file_exists($child_theme_path)) {
            $config = self::parse_yaml_file($child_theme_path);
            if (isset($config['theme']) && !empty($config['theme'])) {
                return sanitize_text_field($config['theme']);
            }
        }
        
        // Check parent theme
        $parent_theme_path = get_template_directory() . '/atomic-events/atomic-events-settings.yml';
        if (file_exists($parent_theme_path)) {
            $config = self::parse_yaml_file($parent_theme_path);
            if (isset($config['theme']) && !empty($config['theme'])) {
                return sanitize_text_field($config['theme']);
            }
        }
        
        // Default fallback
        return 'default';
    }
    
    /**
     * Load theme configuration from theme.yaml file
     * 
     * @param string $theme_name Theme name
     * @return array|null Theme configuration
     */
    private static function load_theme_config($theme_name) {
        $config = array();
        
        // Check child theme first
        $child_theme_path = get_stylesheet_directory() . '/atomic-events/themes/' . $theme_name . '/theme.yaml';
        if (file_exists($child_theme_path)) {
            $config[$theme_name] = self::parse_yaml_file($child_theme_path);
            return $config;
        }
        
        // Check parent theme
        $parent_theme_path = get_template_directory() . '/atomic-events/themes/' . $theme_name . '/theme.yaml';
        if (file_exists($parent_theme_path)) {
            $config[$theme_name] = self::parse_yaml_file($parent_theme_path);
            return $config;
        }
        
        // Check plugin theme
        $plugin_theme_path = plugin_dir_path(dirname(__FILE__)) . 'templates/themes/' . $theme_name . '/theme.yaml';
        if (file_exists($plugin_theme_path)) {
            $config[$theme_name] = self::parse_yaml_file($plugin_theme_path);
            return $config;
        }
        
        // Return default theme config if theme not found
        $default_theme_path = plugin_dir_path(dirname(__FILE__)) . 'templates/themes/default/theme.yaml';
        if (file_exists($default_theme_path)) {
            $config['default'] = self::parse_yaml_file($default_theme_path);
        } else {
            // Fallback default config
            $config['default'] = array(
                'name' => 'Default',
                'description' => 'Default Atomic Events theme',
                'version' => ATOMIC_EVENTS_VERSION
            );
        }
        
        return $config;
    }
    
    /**
     * Parse YAML file safely
     * 
     * @param string $file_path Path to YAML file
     * @return array Parsed YAML data or empty array on error
     */
    private static function parse_yaml_file($file_path) {
        if (!file_exists($file_path)) {
            return array();
        }
        
        $content = file_get_contents($file_path);
        if ($content === false) {
            return array();
        }
        
        // Simple YAML parser for basic key-value pairs
        // This handles the basic format we need: theme: "hydrogen"
        $lines = explode("\n", $content);
        $data = array();
        
        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line) || strpos($line, '#') === 0) {
                continue; // Skip empty lines and comments
            }
            
            if (strpos($line, ':') !== false) {
                $parts = explode(':', $line, 2);
                $key = trim($parts[0]);
                $value = trim($parts[1]);
                
                // Remove quotes if present
                if ((substr($value, 0, 1) === '"' && substr($value, -1) === '"') ||
                    (substr($value, 0, 1) === "'" && substr($value, -1) === "'")) {
                    $value = substr($value, 1, -1);
                }
                
                $data[$key] = $value;
            }
        }
        
        return $data;
    }
    
    /**
     * Check if a theme exists
     * 
     * @param string $theme_name Theme name to check
     * @return bool True if theme exists
     */
    public static function theme_exists($theme_name) {
        // Check child theme
        $child_theme_path = get_stylesheet_directory() . '/atomic-events/themes/' . $theme_name;
        if (is_dir($child_theme_path)) {
            return true;
        }
        
        // Check parent theme
        $parent_theme_path = get_template_directory() . '/atomic-events/themes/' . $theme_name;
        if (is_dir($parent_theme_path)) {
            return true;
        }
        
        // Check plugin theme
        $plugin_theme_path = plugin_dir_path(dirname(__FILE__)) . 'templates/themes/' . $theme_name;
        if (is_dir($plugin_theme_path)) {
            return true;
        }
        
        return false;
    }
    
    /**
     * Get available themes
     * 
     * @return array Array of available theme names
     */
    public static function get_available_themes() {
        $themes = array();
        
        // Check plugin themes
        $plugin_themes_path = plugin_dir_path(dirname(__FILE__)) . 'templates/themes/';
        if (is_dir($plugin_themes_path)) {
            $plugin_themes = glob($plugin_themes_path . '*', GLOB_ONLYDIR);
            foreach ($plugin_themes as $theme_path) {
                $theme_name = basename($theme_path);
                $themes[] = $theme_name;
            }
        }
        
        // Check parent theme themes
        $parent_themes_path = get_template_directory() . '/atomic-events/themes/';
        if (is_dir($parent_themes_path)) {
            $parent_themes = glob($parent_themes_path . '*', GLOB_ONLYDIR);
            foreach ($parent_themes as $theme_path) {
                $theme_name = basename($theme_path);
                if (!in_array($theme_name, $themes)) {
                    $themes[] = $theme_name;
                }
            }
        }
        
        // Check child theme themes
        $child_themes_path = get_stylesheet_directory() . '/atomic-events/themes/';
        if (is_dir($child_themes_path)) {
            $child_themes = glob($child_themes_path . '*', GLOB_ONLYDIR);
            foreach ($child_themes as $theme_path) {
                $theme_name = basename($theme_path);
                if (!in_array($theme_name, $themes)) {
                    $themes[] = $theme_name;
                }
            }
        }
        
        return $themes;
    }
}
