<?php
/**
 * 模板管理器
 * 用于管理用户主题模板
 */

class TemplateManager {
    private static $templates = null;
    
    /**
     * 获取所有模板
     */
    public static function getAllTemplates() {
        if (self::$templates !== null) {
            return self::$templates;
        }
        
        $templates = array();
        $themes_dir = __DIR__ . '/../templates/';
        
        // 扫描主题目录
        if (is_dir($themes_dir)) {
            $dirs = scandir($themes_dir);
            foreach ($dirs as $dir) {
                if ($dir == '.' || $dir == '..' || $dir == 'README.md') {
                    continue;
                }
                
                $theme_path = $themes_dir . $dir;
                if (is_dir($theme_path)) {
                    $config_file = $theme_path . '/config.json';
                    
                    // 默认配置
                    $config = array(
                        'id' => $dir,
                        'name' => $dir,
                        'description' => '',
                        'author' => 'Unknown',
                        'version' => '1.0.0',
                        'options' => array(
                            'primary_color' => '#188038'
                        )
                    );
                    
                    // 读取配置文件
                    if (file_exists($config_file)) {
                        $json = file_get_contents($config_file);
                        $theme_config = json_decode($json, true);
                        if ($theme_config) {
                            $config = array_merge($config, $theme_config);
                        }
                    }
                    
                    $templates[$dir] = $config;
                }
            }
        }
        
        self::$templates = $templates;
        return $templates;
    }
    
    /**
     * 获取当前模板
     */
    public static function getCurrentTemplate() {
        global $conf;
        return isset($conf['theme']) && !empty($conf['theme']) ? $conf['theme'] : 'default';
    }
    
    /**
     * 检查模板是否存在
     */
    public static function templateExists($template_id) {
        $templates = self::getAllTemplates();
        return isset($templates[$template_id]);
    }
}
