<?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 App\Services\System;

use App\Models\System\Config;

class SettingService {

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

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

		$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->setConfigCache(true);
		return $config;
	}

	public function update($request){
		$request->validate([
			'title' => 'required',
			'name' => 'required',
		]);
		$config = Config::where('id', $request->input('id'))->first();


		foreach ($config->setFilterFields($request->all()) as $key => $value) {
			$config->$key = $value;
		}
		$config->save();

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

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

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

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

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

		$this->setConfigCache(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 static function setConfigCache($refresh = false){
		if (!cache('config') || $refresh){
			$config = Config::orderBy('sort', 'asc')->pluck('values', 'name');
			cache('config', $config);
		}
	}
}
