<?php

namespace App\Domain\Shared\Models;

use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use Illuminate\Database\Eloquent\Model;

class SystemSetting extends Model
{
    use BelongsToAcademy, Auditable;

    protected $fillable = [
        'academy_id',
        'group',
        'key',
        'value',
        'type',
        'label_ar',
        'description_ar',
        'is_public',
    ];

    protected $casts = [
        'is_public' => 'boolean',
    ];

    public static function get(string $key, $default = null)
    {
        $academyId = app()->has('current_academy') ? app('current_academy')->id : null;
        if (!$academyId) {
            return $default;
        }

        $setting = static::withoutGlobalScope('academy')
            ->where('academy_id', $academyId)
            ->where('key', $key)
            ->first();

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

        return $setting->castValue();
    }

    public static function set(string $key, $value, string $group = 'general', ?string $type = null): void
    {
        $academyId = app()->has('current_academy') ? app('current_academy')->id : null;
        if (!$academyId) {
            return;
        }

        static::withoutGlobalScope('academy')->updateOrCreate(
            ['academy_id' => $academyId, 'key' => $key],
            [
                'value' => is_array($value) ? json_encode($value) : (string) $value,
                'group' => $group,
                'type' => $type ?? 'string',
            ]
        );
    }

    public function castValue()
    {
        return match ($this->type) {
            'integer' => (int) $this->value,
            'float' => (float) $this->value,
            'boolean' => filter_var($this->value, FILTER_VALIDATE_BOOLEAN),
            'json' => json_decode($this->value, true),
            default => $this->value,
        };
    }
}
