<?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',
        'type',
        'group',
        'description',
    ];

    public static function get(string $key, $default = null)
    {
        // Use database cache if available, otherwise use array cache
        try {
            return Cache::store('database')->remember("setting.{$key}", 3600, function () use ($key, $default) {
                $setting = static::where('key', $key)->first();
                return $setting ? static::castValue($setting->value, $setting->type) : $default;
            });
        } catch (\Exception $e) {
            // Fallback to array cache if database cache not available
            return Cache::store('array')->remember("setting.{$key}", 3600, function () use ($key, $default) {
                $setting = static::where('key', $key)->first();
                return $setting ? static::castValue($setting->value, $setting->type) : $default;
            });
        }
    }

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

        try {
            Cache::store('database')->forget("setting.{$key}");
        } catch (\Exception $e) {
            Cache::store('array')->forget("setting.{$key}");
        }
    }

    protected static function castValue($value, string $type)
    {
        return match ($type) {
            'boolean' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
            'number', 'integer' => (int) $value,
            'float' => (float) $value,
            'json' => json_decode($value, true),
            default => $value,
        };
    }

    public function getValueAttribute($value)
    {
        return static::castValue($value, $this->type);
    }
}
