<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;

#[Fillable(['key', 'value', 'type', 'group'])]
class Setting extends Model
{
    public static function get(string $key, $default = null)
    {
        $row = static::where('key', $key)->first();
        if (!$row) return $default;
        return match ($row->type) {
            'json' => json_decode($row->value ?? 'null', true),
            'bool' => (bool) $row->value,
            'int' => (int) $row->value,
            default => $row->value ?? $default,
        };
    }

    public static function set(string $key, $value, string $type = 'text', string $group = 'general'): void
    {
        $val = is_array($value) ? json_encode($value) : (string) $value;
        static::updateOrCreate(['key' => $key], ['value' => $val, 'type' => $type, 'group' => $group]);
    }
}
