<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class SiteSetting extends Model
{
    protected $fillable = ['key', 'value'];

    /** Get a setting value. JSON is automatically decoded. */
    public static function get(string $key, mixed $default = null): mixed
    {
        $record = static::where('key', $key)->first();
        if (!$record) return $default;
        $decoded = json_decode($record->value, true);
        return ($decoded !== null || $record->value === 'null') ? $decoded : $record->value;
    }

    /** Set a setting value. Arrays/objects are JSON-encoded automatically. */
    public static function set(string $key, mixed $value): void
    {
        static::updateOrCreate(
            ['key' => $key],
            ['value' => is_array($value) || is_object($value) ? json_encode($value) : $value]
        );
    }

    /** Return all settings as a flat key→value array (JSON decoded). */
    public static function allDecoded(): array
    {
        return static::all()->mapWithKeys(function ($record) {
            $decoded = json_decode($record->value, true);
            return [$record->key => ($decoded !== null || $record->value === 'null') ? $decoded : $record->value];
        })->toArray();
    }
}
