<?php

namespace Modules\CardiologyClinic\Entities\Drivers;

use Modules\ClinicCore\Entities\Contracts\ClinicSpecialtyDriver;
use Modules\CardiologyClinic\Entities\CardiologyPatientProfile;

/** Cardiology & Vascular plugs into ClinicCore as a structural specialty (1:1 profile). */
class CardiologySpecialtyDriver implements ClinicSpecialtyDriver
{
    public function key(): string { return 'cardiology_vascular'; }
    public function label(): string { return 'Cardiology & Vascular'; }
    public function patientProfileModel(): ?string { return CardiologyPatientProfile::class; }
    public function patientFormFragment(): ?string { return 'cardiologyClinic::specialty.patient_form'; }
    public function patientShowFragment(): ?string { return 'cardiologyClinic::specialty.patient_show'; }
    public function appointmentFragment(): ?string { return 'cardiologyClinic::specialty.patient_show'; }

    /** Field metadata driving the form/show fragments. */
    public function fields(): array
    {
        return [
            ['name' => 'bp_systolic', 'type' => 'int', 'label' => 'Systolic BP', 'options' => []],
            ['name' => 'bp_diastolic', 'type' => 'int', 'label' => 'Diastolic BP', 'options' => []],
            ['name' => 'ejection_fraction', 'type' => 'int', 'label' => 'Ejection fraction (%)', 'options' => []],
            ['name' => 'rhythm', 'type' => 'select', 'label' => 'Rhythm', 'options' => ['sinus' => 'Sinus', 'af' => 'Atrial fibrillation', 'other' => 'Other arrhythmia']],
            ['name' => 'nyha', 'type' => 'select', 'label' => 'NYHA class', 'options' => ['i' => 'I', 'ii' => 'II', 'iii' => 'III', 'iv' => 'IV']],
        ];
    }

    public function persistPatientProfile($patient, array $input): void
    {
        $data = [];
        $any = false;
        foreach (['bp_systolic', 'bp_diastolic', 'ejection_fraction', 'rhythm', 'nyha'] 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 && ! CardiologyPatientProfile::where('clc_patient_id', $patient->id)->exists()) {
            return;
        }
        CardiologyPatientProfile::updateOrCreate(['clc_patient_id' => $patient->id], $data);
    }

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