<?php

namespace Modules\NX600Lab\Entities;

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

class NxModuleSetting extends Model
{
    protected $table = 'nx_module_settings';
    protected $guarded = ['id'];

    /**
     * Read a single per-business setting value.
     */
    public static function get(int $businessId, string $key, $default = null)
    {
        if (!Schema::hasTable('nx_module_settings')) {
            return $default;
        }
        $row = DB::table('nx_module_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('nx_module_settings')) {
            return;
        }
        DB::table('nx_module_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 config fallbacks).
     *
     * Note: deliberately NOT named all() — that would clash with the inherited
     * Eloquent Model::all() and break class loading.
     */
    public static function allFor(int $businessId): array
    {
        $defaults = [
            'tcp_host'        => config('nx600lab.tcp_host', '0.0.0.0'),
            'tcp_port'        => config('nx600lab.tcp_port', 65535),
            'hl7_port'        => config('nx600lab.hl7_port', 2575),
            'comm_type'       => config('nx600lab.comm_type', '1'),
            'clinic_name'     => 'Diagnostic Laboratory',
            'clinic_subtitle' => 'Clinical Chemistry & Hematology',
            'clinic_phone'    => '',
            'clinic_email'    => '',
            'vetclinic_sync'  => '1',
            'species_map'     => json_encode(config('nx600lab.species', [])),
        ];

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

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

        return array_merge($defaults, $stored);
    }

    /**
     * Numeric NX600 species code => label map, config defaults overlaid with
     * the per-business override stored under the "species_map" key.
     */
    public static function speciesMap(?int $businessId = null): array
    {
        $map = config('nx600lab.species', []);

        if ($businessId && Schema::hasTable('nx_module_settings')) {
            $raw = static::get($businessId, 'species_map');
            if (!empty($raw)) {
                $decoded = json_decode($raw, true);
                if (is_array($decoded)) {
                    $map = $decoded;
                }
            }
        }

        return $map;
    }
}
