<?php

namespace Modules\EmergencyClinic\Entities\Drivers;

use Modules\ClinicCore\Entities\Contracts\ClinicSpecialtyDriver;
use Modules\EmergencyClinic\Entities\EmergencyPatientProfile;

/** Emergency & ICU plugs into ClinicCore as a structural specialty (1:1 profile). */
class EmergencySpecialtyDriver implements ClinicSpecialtyDriver
{
    public function key(): string { return 'emergency_icu'; }
    public function label(): string { return 'Emergency & ICU'; }
    public function patientProfileModel(): ?string { return EmergencyPatientProfile::class; }
    public function patientFormFragment(): ?string { return 'emergencyClinic::specialty.patient_form'; }
    public function patientShowFragment(): ?string { return 'emergencyClinic::specialty.patient_show'; }
    public function appointmentFragment(): ?string { return 'emergencyClinic::specialty.patient_show'; }

    /** Field metadata driving the form/show fragments. */
    public function fields(): array
    {
        return [
            ['name' => 'triage_category', 'type' => 'select', 'label' => 'Triage category', 'options' => ['green' => 'Non-urgent', 'yellow' => 'Urgent', 'orange' => 'Very urgent', 'red' => 'Immediate']],
            ['name' => 'gcs', 'type' => 'int', 'label' => 'GCS (3-15)', 'options' => []],
            ['name' => 'ward', 'type' => 'string', 'label' => 'Ward / bed', 'options' => []],
            ['name' => 'admission_status', 'type' => 'select', 'label' => 'Admission status', 'options' => ['er' => 'In ER', 'admitted' => 'Admitted', 'icu' => 'ICU', 'discharged' => 'Discharged']],
            ['name' => 'spo2', 'type' => 'int', 'label' => 'SpO₂ (%)', 'options' => []],
            ['name' => 'notes', 'type' => 'text', 'label' => 'Notes', 'options' => []],
        ];
    }

    public function persistPatientProfile($patient, array $input): void
    {
        $data = [];
        $any = false;
        foreach (['triage_category', 'gcs', 'ward', 'admission_status', 'spo2', 'notes'] as $f) {
            $v = $input[$f] ?? null;
            $v = ($v === '' ? null : $v);
            $data[$f] = $v;
            if ($v !== null) $any = true;
        }
        foreach ([] as $f) {
            $data[$f] = ! empty($input[$f]);
            if ($data[$f]) $any = true;
        }
        if (! $any && ! EmergencyPatientProfile::where('clc_patient_id', $patient->id)->exists()) {
            return;
        }
        EmergencyPatientProfile::updateOrCreate(['clc_patient_id' => $patient->id], $data);
    }

    public function examTemplateSeeds(): array { return []; }
    public function terminology(): array { return []; }
}
