<?php

/**
 * 文件功能：系统参数配置控制器
 * (替代原版 VIEWSYS.ASP / SetSYS.ASP)
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SysParam;
use App\Services\ChatStateService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SystemController extends Controller
{
    public function __construct(
        private readonly ChatStateService $chatState
    ) {}

    /**
     * 显示全局参数配置表单
     */
    public function edit(): View
    {
        // 读取数据库中最新的参数 (剔除专属模块已接管的配置，避免重复显示)
        $params = SysParam::whereNotIn('alias', ['chatbot_enabled'])
            ->where('alias', 'not like', 'smtp_%')
            ->get()->pluck('body', 'alias')->toArray();

        // 为后台界面准备的文案对照 (可动态化或硬编码)
        $descriptions = SysParam::whereNotIn('alias', ['chatbot_enabled'])
            ->where('alias', 'not like', 'smtp_%')
            ->get()->pluck('guidetxt', 'alias')->toArray();

        return view('admin.system.edit', compact('params', 'descriptions'));
    }

    /**
     * 更新全局参数，并刷新全站 Cache 缓存
     */
    public function update(Request $request): RedirectResponse
    {
        $data = $request->except(['_token', '_method']);

        foreach ($data as $alias => $body) {
            SysParam::updateOrCreate(
                ['alias' => $alias],
                ['body' => $body]
            );

            // 写入 Cache 保证极速读取
            $this->chatState->setSysParam($alias, $body);

            // 同时清除 Sysparam 模型的内部缓存
            SysParam::clearCache($alias);
        }

        return redirect()->route('admin.system.edit')->with('success', '系统参数已成功更新并生效！');
    }
}
