<?php

namespace Modules\ClinicCore\Entities;

use Illuminate\Database\Eloquent\Model;

class ClcRoleSetting extends Model
{
    protected $table = 'clc_role_settings';
    protected $guarded = ['id'];

    /** Read a per-role value, or $default if unset. */
    public static function get(int $businessId, int $roleId, string $key, $default = null)
    {
        $val = static::where('business_id', $businessId)
            ->where('role_id', $roleId)
            ->where('key', $key)
            ->value('value');
        return $val ?? $default;
    }

    /** Save (or unset when empty) a per-role value. */
    public static function set(int $businessId, int $roleId, string $key, ?string $value): void
    {
        if ($value === null || $value === '') {
            static::where('business_id', $businessId)
                ->where('role_id', $roleId)
                ->where('key', $key)
                ->delete();
            return;
        }
        static::updateOrCreate(
            ['business_id' => $businessId, 'role_id' => $roleId, 'key' => $key],
            ['value' => $value]
        );
    }
}
