<?php

namespace App\Models;

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

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

    /**
     * Boot method to clear cache when settings change
     */
    protected static function booted(): void
    {
        static::saved(function () {
            Cache::forget('settings_all');
            Cache::forget('app_settings');
        });
        static::deleted(function () {
            Cache::forget('settings_all');
            Cache::forget('app_settings');
        });
    }

    /**
     * Get all settings from cache
     */
    private static function getAllCached(): array
    {
        return Cache::remember('settings_all', 300, function () {
            return static::pluck('value', 'key')->toArray();
        });
    }

    public static function get(string $key, $default = null)
    {
        $all = static::getAllCached();
        if (isset($all[$key]) && $all[$key] !== null && $all[$key] !== '') {
            return $all[$key];
        }
        return $default;
    }

    public static function set(string $key, $value, string $group = 'general', string $label = ''): void
    {
        static::updateOrCreate(
            ['key' => $key],
            ['value' => $value, 'group' => $group, 'label' => $label]
        );
    }
}
