<?php

namespace App\Models\Central;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class PlatformSetting extends Model
{
    public $timestamps = true;

    protected $fillable = ['key', 'value'];

    protected $casts = [
        'value' => 'array',
    ];

    public static function get(string $key, $default = null)
    {
        $cached = Cache::remember("psetting:{$key}", 300, function () use ($key) {
            $row = static::where('key', $key)->first();
            return $row?->value;
        });
        return $cached ?? $default;
    }

    public static function put(string $key, $value): void
    {
        static::updateOrCreate(['key' => $key], ['value' => $value]);
        Cache::forget("psetting:{$key}");
    }

    public static function many(array $keys): array
    {
        $rows = static::whereIn('key', $keys)->get()->keyBy('key');
        $out = [];
        foreach ($keys as $k) {
            $out[$k] = $rows[$k]?->value ?? null;
        }
        return $out;
    }
}
