<?php

namespace App\Models;

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

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

    public static function getAllMerged(): array
    {
        return Cache::remember('site_settings_merged', 300, function () {
            $defaults = config('cms_settings.defaults', []);
            $stored = static::query()->pluck('value', 'key')->all();

            return array_merge($defaults, $stored);
        });
    }

    public static function setMany(array $data): void
    {
        $allowed = config('cms_settings.keys', []);

        foreach ($data as $key => $value) {
            if (! in_array($key, $allowed, true)) {
                continue;
            }
            static::updateOrCreate(
                ['key' => $key],
                ['value' => is_null($value) ? '' : (string) $value]
            );
        }

        Cache::forget('site_settings_merged');
    }

    public static function clearCache(): void
    {
        Cache::forget('site_settings_merged');
    }
}
