<?php

namespace Modules\Vrc\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * Per-business repair-specific settings under the vrc.* namespace (labor
 * rates, default inspection template, comms matrix, estimate validity, ...).
 * Currency / VAT / timezone / document numbering come from the ERP business
 * settings and are NOT stored here. Mirrors Modules\Bms\Entities\BmsSetting.
 */
class VrcSetting extends Model
{
    protected $table = 'vrc_settings';

    protected $fillable = ['business_id', 'key', 'value'];

    /** Read a setting (JSON-decoded if possible), with a default fallback. */
    public static function get(int $businessId, string $key, $default = null)
    {
        $row = static::where('business_id', $businessId)->where('key', $key)->first();
        if (! $row) {
            return $default;
        }
        $decoded = json_decode($row->value, true);
        return json_last_error() === JSON_ERROR_NONE ? $decoded : $row->value;
    }

    /** Write a setting, JSON-encoding arrays/objects. */
    public static function put(int $businessId, string $key, $value): void
    {
        static::updateOrCreate(
            ['business_id' => $businessId, 'key' => $key],
            ['value' => is_scalar($value) ? (string) $value : json_encode($value)]
        );
    }
}
