<?php

namespace Modules\LabCore\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class LabSetting extends Model
{
    protected $table = 'lab_settings';
    protected $guarded = ['id'];

    /**
     * Read a single per-business setting value.
     */
    public static function get(int $businessId, string $key, $default = null)
    {
        if (!Schema::hasTable('lab_settings')) {
            return $default;
        }
        $row = DB::table('lab_settings')
            ->where('business_id', $businessId)
            ->where('key', $key)
            ->first();

        return $row ? $row->value : $default;
    }

    /**
     * Write a single per-business setting value.
     */
    public static function set(int $businessId, string $key, $value): void
    {
        if (!Schema::hasTable('lab_settings')) {
            return;
        }
        DB::table('lab_settings')->updateOrInsert(
            ['business_id' => $businessId, 'key' => $key],
            [
                'value'      => is_array($value) ? json_encode($value) : (string) $value,
                'updated_at' => now(),
                'created_at' => now(),
            ]
        );
    }

    /**
     * All settings for a business as an associative array, with defaults.
     */
    public static function allFor(int $businessId): array
    {
        $defaults = [
            'vetclinic_sync'  => config('labcore.vetclinic_sync_default', true) ? '1' : '0',
            'clinic_name'     => 'Diagnostic Laboratory',
            'clinic_subtitle' => 'Clinical Chemistry & Hematology',
            'clinic_phone'    => '',
            'clinic_email'    => '',
        ];

        if (!Schema::hasTable('lab_settings')) {
            return $defaults;
        }

        $stored = DB::table('lab_settings')
            ->where('business_id', $businessId)
            ->pluck('value', 'key')
            ->toArray();

        return array_merge($defaults, $stored);
    }
}
