<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Traits\ModelTrait;

class Setting extends Model
{
    use ModelTrait;

    protected $table   = 'settings';
    protected $guarded = [];

    /**
     * 获取某个配置
     * @param string $key
     * @return mixed
     */
    public static function get($key)
    {
        static $setting = null;

        $setting = $setting ?? static::where('lang', 'single')->orWhere('lang', config('lang'))->lists('value', 'name');

        return $key == "*" ? $setting->all() : array_get($setting, $key, '');
    }

    public static function set($data, $langId = 'single') 
    {
    	if (isset($data['description'])) {
            foreach ($data['description'] as $key => $value) {
                foreach ($value as $k => $val) {
                    Setting::FindOrCreate($k, $val, $key);
                }
            }
            $data = array_except($data, ['description']);
        }
        if (!empty($data)) {
            foreach ($data as $name => $value) {
                Setting::FindOrCreate($name, $value, $langId);
            }
        }

        return true;
    }

    // 保存和更新对应的键值对，如果键不存在，则添加对应的键
	public function scopeFindOrCreate($query, $name, $value, $langId)
	{
	    $obj    = $query->where('lang', $langId)->whereName($name)->first();
	    $config = $obj ?: new static;

	    $config->name  = $name;
		$config->lang  = $langId;
	    $config->value = is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : (string)$value;

	    $config->save();
	}

    public static function seo($key)
    {
        static $setting = null;

        $lang = config('lang') ?: config('setting.lang');

        $setting = $setting ?? static::where('lang', $lang)->lists('value', 'name');

        return $key == "*" ? $setting->all() : array_get($setting, $key, '');
    }
}
