<?php

namespace App\Models;

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

class Setting extends Model
{
    use HasFactory;

    protected $fillable = ['key', 'value', 'group', 'type', 'label'];

    /**
     * Get setting value by key
     *
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public static function getValue($key, $default = null)
    {
        // Cache settings for performance
        $settings = Cache::rememberForever('app_settings', function () {
            return self::all()->pluck('value', 'key');
        });

        return $settings[$key] ?? $default;
    }

    /**
     * Set setting value by key
     *
     * @param string $key
     * @param mixed $value
     * @return void
     */
    public static function setValue($key, $value)
    {
        $setting = self::where('key', $key)->first();
        if ($setting) {
            $setting->update(['value' => $value]);
            Cache::forget('app_settings');
        }
    }
    
    /**
     * Clear cache on save/update/delete
     */
    protected static function booted()
    {
        static::saved(function () {
            Cache::forget('app_settings');
        });
        static::deleted(function () {
            Cache::forget('app_settings');
        });
    }
}
