<?php

namespace Modules\NX600Lab\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\NX600Lab\Entities\NxModuleSetting;
use Modules\NX600Lab\Entities\Services\VetClinicSyncService;

class NxSettingsController extends Controller
{
    /** Settings keys that the form is allowed to write. */
    private array $keys = [
        'tcp_host', 'tcp_port', 'hl7_port', 'comm_type',
        'clinic_name', 'clinic_subtitle', 'clinic_phone', 'clinic_email',
        'vetclinic_sync',
    ];

    public function index(Request $request)
    {
        if (!auth()->user()->can('nx600_lab.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = (int) $request->session()->get('user.business_id');

        return view('nx600Lab::settings.index', [
            'settings'         => NxModuleSetting::allFor($businessId),
            'speciesMap'       => NxModuleSetting::speciesMap($businessId),
            'vetClinicPresent' => VetClinicSyncService::vetClinicInstalled(),
        ]);
    }

    public function update(Request $request)
    {
        if (!auth()->user()->can('nx600_lab.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = (int) $request->session()->get('user.business_id');

        foreach ($this->keys as $key) {
            if ($key === 'vetclinic_sync') {
                NxModuleSetting::set($businessId, $key, $request->boolean('vetclinic_sync') ? '1' : '0');
                continue;
            }
            NxModuleSetting::set($businessId, $key, (string) $request->input($key, ''));
        }

        // Species map: lines of "code=Label"
        if ($request->filled('species_map')) {
            $map = [];
            foreach (preg_split('/[\r\n]+/', $request->species_map) as $line) {
                $line = trim($line);
                if ($line === '' || !str_contains($line, '=')) {
                    continue;
                }
                [$code, $label] = explode('=', $line, 2);
                if (is_numeric(trim($code))) {
                    $map[(int) trim($code)] = trim($label);
                }
            }
            NxModuleSetting::set($businessId, 'species_map', json_encode($map));
        }

        return back()->with('status', ['success' => 1, 'msg' => 'NX600 Lab settings saved.']);
    }
}
