<?php

namespace Modules\MedEmergency\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\MedEmergency\Entities\MderVisit;
use Modules\MedEmergency\Services\TriageService;

/**
 * ER triage (SIFA P6-T3). The triage form captures the acuity level (with a
 * live auto-suggestion from the vitals) + a set of vitals; on save the service
 * writes a real clc_vitals row, stamps the triage fields, advances the board and
 * raises a critical MedicalAlert for resuscitation / emergent. Guarded by
 * mder.triage.
 */
class TriageController extends MedEmergencyBaseController
{
    public function form($id)
    {
        $this->guard('mder.triage');

        $visit = MderVisit::forBusiness($this->businessId())->findOrFail($id);

        // Doctors for the optional assignment dropdown (fail-soft).
        $doctors = Schema::hasTable('clc_doctors')
            ? DB::table('clc_doctors')
                ->where('business_id', $this->businessId())
                ->orderBy('name')
                ->pluck('name', 'id')
                ->toArray()
            : [];

        return view('medemergency::board.triage', [
            'visit'         => $visit,
            'triageLevels'  => MderVisit::TRIAGE_LEVELS,
            'triageSystems' => MderVisit::TRIAGE_SYSTEMS,
            'triageColors'  => MderVisit::TRIAGE_COLORS,
            'doctors'       => $doctors,
        ]);
    }

    /** Live auto-suggest endpoint — returns the suggested level + reasons. */
    public function suggest(Request $request, TriageService $triage)
    {
        $this->guard('mder.triage');

        $out = $triage->suggestLevel($request->only([
            'heart_rate', 'respiratory_rate', 'spo2',
            'gcs_total', 'gcs_eye', 'gcs_verbal', 'gcs_motor',
        ]));

        return response()->json($out);
    }

    /** Save the triage decision. */
    public function store(Request $request, $id, TriageService $triage)
    {
        $this->guard('mder.triage');

        $data = $this->validate($request, [
            'triage_level'       => 'required|string|in:' . implode(',', MderVisit::TRIAGE_LEVELS),
            'triage_system'      => 'nullable|string|in:' . implode(',', MderVisit::TRIAGE_SYSTEMS),
            'assigned_doctor_id' => 'nullable|integer',
            'temperature'        => 'nullable|numeric',
            'heart_rate'         => 'nullable|integer',
            'respiratory_rate'   => 'nullable|integer',
            'bp_systolic'        => 'nullable|integer',
            'bp_diastolic'       => 'nullable|integer',
            'spo2'               => 'nullable|numeric',
            'pain_score'         => 'nullable|integer',
            'gcs_eye'            => 'nullable|integer',
            'gcs_verbal'         => 'nullable|integer',
            'gcs_motor'          => 'nullable|integer',
        ]);

        $visit = MderVisit::forBusiness($this->businessId())->findOrFail($id);

        $triage->applyTriage(
            $visit,
            $data['triage_level'],
            $data['triage_system'] ?? 'esi',
            $data,
            ! empty($data['assigned_doctor_id']) ? (int) $data['assigned_doctor_id'] : null
        );

        return redirect()->route('mder.board.index')
            ->with('status', ['success' => 1, 'msg' => __('medemergency::lang.triage_saved', ['no' => $visit->visit_no])]);
    }
}
