<?php

namespace App\Models;

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

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

    /**
     * Get a setting value by key
     */
    public static function get($key, $default = null, $locale = 'en')
    {
        $cacheKey = "setting_{$key}_{$locale}";

        return Cache::remember($cacheKey, 3600, function () use ($key, $default, $locale) {
            $setting = self::where('key', $key)->first();

            if (! $setting) {
                return $default;
            }

            if ($locale === 'km' && $setting->value_km) {
                return $setting->value_km;
            }

            return $setting->value ?? $default;
        });
    }

    /**
     * Set a setting value by key
     */
    public static function set($key, $value, $locale = 'en')
    {
        $setting = self::firstOrNew(['key' => $key]);

        if ($locale === 'km') {
            $setting->value_km = $value;
        } else {
            $setting->value = $value;
        }

        $setting->save();

        // Clear cache
        Cache::forget("setting_{$key}_en");
        Cache::forget("setting_{$key}_km");

        return $setting;
    }

    /**
     * Get all settings grouped by group
     */
    public static function getGrouped()
    {
        return self::orderBy('group')
            ->orderBy('order')
            ->get()
            ->groupBy('group');
    }

    /**
     * Clear all settings cache
     */
    public static function clearCache()
    {
        $settings = self::pluck('key');
        foreach ($settings as $key) {
            Cache::forget("setting_{$key}_en");
            Cache::forget("setting_{$key}_km");
        }
    }

    /**
     * Boot method to clear cache on save/update/delete
     */
    protected static function boot()
    {
        parent::boot();

        static::saved(function ($setting) {
            Cache::forget("setting_{$setting->key}_en");
            Cache::forget("setting_{$setting->key}_km");
        });

        static::deleted(function ($setting) {
            Cache::forget("setting_{$setting->key}_en");
            Cache::forget("setting_{$setting->key}_km");
        });
    }
}
