<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

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

    protected function casts(): array
    {
        return ['is_public' => 'boolean'];
    }

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    /** Decode value según type. */
    public function getTypedValueAttribute()
    {
        return match ($this->type) {
            'integer' => (int) $this->value,
            'boolean' => filter_var($this->value, FILTER_VALIDATE_BOOLEAN),
            'json'    => json_decode($this->value, true),
            default   => $this->value,
        };
    }

    public static function get(string $key, mixed $default = null, ?int $companyId = null): mixed
    {
        $setting = static::where('key', $key)
            ->where('company_id', $companyId)
            ->first();

        return $setting?->typed_value ?? $default;
    }

    public static function set(string $key, mixed $value, ?int $companyId = null, string $group = 'general', string $type = 'string'): self
    {
        return static::updateOrCreate(
            ['company_id' => $companyId, 'key' => $key],
            [
                'group' => $group,
                'type'  => $type,
                'value' => is_array($value) ? json_encode($value) : (string) $value,
            ]
        );
    }
}
