<?php

namespace App\Models;

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

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

    // ── Static Helpers ────────────────────────────────────────────────────

    /**
     * Ambil nilai setting berdasarkan key.
     * Di-cache selamanya (di-bust saat save/update).
     *
     * @param  string $key     Key setting
     * @param  mixed  $default Nilai default jika key tidak ditemukan
     */
    public static function get(string $key, mixed $default = null): mixed
    {
        return Cache::rememberForever("setting.{$key}", function () use ($key, $default) {
            $setting = static::where('key', $key)->first();
            return $setting?->value ?? $default;
        });
    }

    /**
     * Simpan atau update nilai setting, hapus cache yang terkait.
     */
    public static function set(string $key, mixed $value, string $group = 'general'): void
    {
        static::updateOrCreate(
            ['key'   => $key],
            ['value' => $value, 'group' => $group]
        );

        Cache::forget("setting.{$key}");
    }

    /**
     * Hapus seluruh cache setting.
     * Digunakan saat melakukan bulk update di halaman Setting.
     */
    public static function flushCache(): void
    {
        $keys = static::pluck('key');
        foreach ($keys as $key) {
            Cache::forget("setting.{$key}");
        }
    }

    /**
     * Ambil semua setting dalam satu group sebagai array key => value.
     */
    public static function getGroup(string $group): array
    {
        return static::where('group', $group)
            ->pluck('value', 'key')
            ->toArray();
    }
}
