<?php

namespace App\Models;

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

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

    /** Read a setting with type casting and caching */
    public static function get(string $key, $default = null)
    {
        $all = self::allCached();
        if (!isset($all[$key])) return $default;
        return $all[$key];
    }

    /** Write a setting and clear cache */
    public static function set(string $key, $value, string $type = 'string', string $group = 'general'): void
    {
        if ($type === 'json' && (is_array($value) || is_object($value))) {
            $value = json_encode($value);
        } elseif ($type === 'boolean') {
            $value = $value ? '1' : '0';
        }

        self::updateOrCreate(
            ['key' => $key],
            ['value' => (string) $value, 'type' => $type, 'group' => $group]
        );

        Cache::forget('site_settings');
    }

    /** Single cache lookup of all settings, type-cast values */
    public static function allCached(): array
    {
        return Cache::rememberForever('site_settings', function () {
            $rows = self::all();
            $map = [];
            foreach ($rows as $r) {
                $map[$r->key] = match ($r->type) {
                    'boolean' => (bool) $r->value,
                    'json'    => json_decode($r->value ?? 'null', true),
                    default   => $r->value,
                };
            }
            return $map;
        });
    }

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