<?php
/**
 * 模板管理API
 */

require_once __DIR__ . '/../base_api.php';
require_once __DIR__ . '/../../TemplateManager.php';

class TemplateAPI extends BaseAPI {
    
    /**
     * 获取所有可用模板
     */
    public function getAll() {
        $templates = TemplateManager::getAllTemplates();
        $current = getTemplate()->getTemplate();
        
        $result = [];
        foreach ($templates as $id => $config) {
            $result[] = [
                'id' => $id,
                'name' => $config['name'] ?? $id,
                'version' => $config['version'] ?? '1.0.0',
                'author' => $config['author'] ?? 'Unknown',
                'description' => $config['description'] ?? '',
                'preview' => 'templates/' . $id . '/' . ($config['preview'] ?? 'assets/images/preview.png'),
                'current' => ($id === $current)
            ];
        }
        
        $this->success(['templates' => $result, 'current' => $current]);
    }
    
    /**
     * 切换模板
     */
    public function switch() {
        $templateId = $_POST['template'] ?? '';
        
        if (empty($templateId)) {
            $this->error('请选择模板');
        }
        
        if (TemplateManager::switchTemplate($templateId)) {
            $this->success(['message' => '模板切换成功', 'template' => $templateId]);
        } else {
            $this->error('模板切换失败，模板不存在');
        }
    }
    
    /**
     * 获取当前模板信息
     */
    public function getCurrent() {
        $template = getTemplate();
        $this->success($template->getInfo());
    }
}

// 处理请求
$api = new TemplateAPI();
$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    switch ($action) {
        case 'getAll':
            $api->getAll();
            break;
        case 'switch':
            $api->switch();
            break;
        case 'getCurrent':
            $api->getCurrent();
            break;
        default:
            echo json_encode(['status' => false, 'code' => 'error', 'msg' => '未知操作']);
    }
} catch (Exception $e) {
    echo json_encode(['status' => false, 'code' => 'error', 'msg' => $e->getMessage()]);
}
