<?php

namespace App\Models;

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

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

    /** Cache TTL: 5 dakika */
    const CACHE_TTL = 300;

    /**
     * Tüm ayarları cache'e yükle (key => value map)
     */
    protected static function allCached(): array
    {
        return Cache::remember('site_settings_all', self::CACHE_TTL, function () {
            return static::all()->pluck('value', 'key')->toArray();
        });
    }

    /**
     * Cache'i temizle (set/update sonrası çağrılır)
     */
    public static function clearCache(): void
    {
        Cache::forget('site_settings_all');
    }

    /**
     * Bir ayarı al
     */
    public static function get(string $key, mixed $default = null): mixed
    {
        $all = static::allCached();
        return array_key_exists($key, $all) ? $all[$key] : $default;
    }

    /**
     * Bir ayarı kaydet veya güncelle
     */
    public static function set(string $key, mixed $value, string $group = 'general'): void
    {
        static::updateOrCreate(
            ['key' => $key],
            ['value' => $value, 'group' => $group]
        );
        static::clearCache();
    }

    /**
     * Bir gruba ait tüm ayarları al (key => value)
     */
    public static function getGroup(string $group): array
    {
        return static::where('group', $group)
            ->pluck('value', 'key')
            ->toArray();
    }

    /**
     * Boolean ayar kontrolü
     */
    public static function isEnabled(string $key): bool
    {
        $val = static::get($key, '0');
        return in_array($val, ['1', 'true', 'yes', true], true);
    }
}
