<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RiskSetting extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'setting_key',
        'setting_value',
        'description',
        'is_active',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'is_active' => 'boolean',
    ];

    /**
     * Get the setting value as parsed data.
     */
    public function getParsedValueAttribute()
    {
        $decoded = json_decode($this->setting_value, true);
        
        if (json_last_error() === JSON_ERROR_NONE) {
            return $decoded;
        }

        return $this->setting_value;
    }

    /**
     * Get a specific value from JSON setting.
     */
    public function getValue(string $key, $default = null)
    {
        $parsed = $this->parsed_value;

        if (is_array($parsed) && isset($parsed[$key])) {
            return $parsed[$key];
        }

        return $default;
    }

    /**
     * Update a specific value in JSON setting.
     */
    public function updateValue(string $key, $value): bool
    {
        $parsed = $this->parsed_value;

        if (!is_array($parsed)) {
            $parsed = [];
        }

        $parsed[$key] = $value;
        $this->setting_value = json_encode($parsed);

        return $this->save();
    }

    /**
     * Scope to filter by setting key.
     */
    public function scopeByKey($query, string $key)
    {
        return $query->where('setting_key', $key);
    }

    /**
     * Scope to filter active settings.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Get a setting value by key (static helper).
     */
    public static function get(string $key, $default = null)
    {
        $setting = static::byKey($key)->active()->first();

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

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

    /**
     * Set a setting value by key (static helper).
     */
    public static function set(string $key, $value, ?string $description = null): bool
    {
        $setting = static::byKey($key)->first();

        $settingValue = is_array($value) ? json_encode($value) : $value;

        if ($setting) {
            $setting->setting_value = $settingValue;
            if ($description) {
                $setting->description = $description;
            }
            return $setting->save();
        }

        static::create([
            'setting_key' => $key,
            'setting_value' => $settingValue,
            'description' => $description,
            'is_active' => true,
        ]);

        return true;
    }
}

// Made with Bob