<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace Modules\System\Services;

use Modules\System\Models\Config;

class SettingService {

	/**
	 * @title 获取配置列表
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getDataList(){
		$map = [];

		$data = Config::where($map)->orderBy('sort', 'asc')->pluck('values', 'name');
		return $data;
	}

	public function create($request){
		$request->validate([
			'title' => 'required',
			'name' => 'required',
			'values' => 'required',
		]);

		$data = $request->all();
		$config = Config::create($data);

		$this->setCache(true);
		return $config;
	}

	public function update($request){
		$data = $request->all();

		foreach ($data as $key => $value) {
			Config::where('name', $key)->update(['values' => $value]);
		}

		$this->setCache(true);
		return true;
	}

	public function delete($request){
		$data = $request->all();
		$config = Config::find($data['id']);
		$config->delete();

		$this->setCache(true);
		return $config;
	}

	public function getFields($request){
		$map = [];

		if ($request->filled('group_name')) {
			$map[] = ['group', '=', $request->input('group_name')];
		}

		$config = Config::where($map)->orderBy('sort', 'asc')->get()->append(['options', 'label']);
		return $config;
	}

	public function setCache($refresh = false){
		if (!cache()->has('config') || $refresh) {
			$config = Config::pluck('values', 'name')->toArray();
			cache()->forever('config', $config);
		}
	}
}
