<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $fillable = [
        'group_key',
        'key',
        'value',
        'type',
        'label',
        'is_public',
    ];

    protected function casts(): array
    {
        return [
            'is_public' => 'boolean',
        ];
    }

    public static function getValue(string $key, mixed $default = null): mixed
    {
        $setting = static::query()->where('key', $key)->first();

        if (!$setting) {
            return $default;
        }

        return match ($setting->type) {
            'number' => (float) $setting->value,
            'boolean' => filter_var($setting->value, FILTER_VALIDATE_BOOL),
            'json' => json_decode((string) $setting->value, true) ?? $default,
            default => $setting->value,
        };
    }

    public static function setValue(string $key, mixed $value): void
    {
        $setting = static::query()->where('key', $key)->first();

        if (!$setting) {
            return;
        }

        $setting->value = is_array($value) ? json_encode($value) : (string) $value;
        $setting->save();
    }
}
