<?php

namespace XZD\AI\V5\REST\Controllers;

use WP_REST_Request;
use XZD\AI\V5\REST\BaseController;
use XZD\AI\V5\Theme\TagStyleManager;

/**
 * 标签美化 REST API
 */
class TagStyleController extends BaseController
{
    public function registerRoutes(): void
    {
        $this->registerGet('tag-style/settings', [$this, 'getSettings'], 'manage_options');
        $this->registerPost('tag-style/settings', [$this, 'saveSettings'], 'manage_options');
        $this->registerPost('tag-style/reset', [$this, 'resetSettings'], 'manage_options');
        $this->registerGet('tag-style/preview', [$this, 'previewCSS'], 'manage_options');
    }

    public function getSettings(WP_REST_Request $request)
    {
        $licenseGuard = $this->guardLicense();
        if ($licenseGuard !== null) {
            return $licenseGuard;
        }

        $manager = TagStyleManager::instance();
        $settings = $manager->getSettings();

        return $this->success([
            'settings'    => $settings,
            'themes'      => $manager->getThemeMeta(),
            'hash_styles' => $manager->getHashStyles(),
        ]);
    }

    public function saveSettings(WP_REST_Request $request)
    {
        $licenseGuard = $this->guardLicense();
        if ($licenseGuard !== null) {
            return $licenseGuard;
        }

        $data = $this->getBodyParams($request);
        if (empty($data)) {
            return $this->error('请提供设置数据', 'empty_body');
        }

        $manager = TagStyleManager::instance();
        $manager->saveSettings($data);

        return $this->success([
            'settings' => $manager->getSettings(),
        ], '保存成功');
    }

    public function resetSettings(WP_REST_Request $request)
    {
        $licenseGuard = $this->guardLicense();
        if ($licenseGuard !== null) {
            return $licenseGuard;
        }

        $manager = TagStyleManager::instance();
        $settings = $manager->resetSettings();

        return $this->success([
            'settings' => $settings,
        ], '已恢复默认设置');
    }

    public function previewCSS(WP_REST_Request $request)
    {
        $licenseGuard = $this->guardLicense();
        if ($licenseGuard !== null) {
            return $licenseGuard;
        }

        $params = $this->getBodyParams($request);
        // 也支持GET参数预览
        if (empty($params)) {
            $params = $request->get_params();
        }

        $manager = TagStyleManager::instance();
        $css = $manager->previewCSS($params);

        return $this->success([
            'css' => $css,
        ]);
    }
}
