<?php

namespace Modules\OrthopedicsClinic\Entities\Drivers;

use Modules\ClinicCore\Entities\Contracts\ClinicSpecialtyDriver;
use Modules\OrthopedicsClinic\Entities\OrthopedicsPatientProfile;

/** Orthopedics plugs into ClinicCore as a structural specialty (1:1 profile). */
class OrthopedicsSpecialtyDriver implements ClinicSpecialtyDriver
{
    public function key(): string { return 'orthopedics'; }
    public function label(): string { return 'Orthopedics'; }
    public function patientProfileModel(): ?string { return OrthopedicsPatientProfile::class; }
    public function patientFormFragment(): ?string { return 'orthopedicsClinic::specialty.patient_form'; }
    public function patientShowFragment(): ?string { return 'orthopedicsClinic::specialty.patient_show'; }
    public function appointmentFragment(): ?string { return 'orthopedicsClinic::specialty.patient_show'; }

    /** Field metadata driving the form/show fragments. */
    public function fields(): array
    {
        return [
            ['name' => 'affected_joint', 'type' => 'string', 'label' => 'Affected joint', 'options' => []],
            ['name' => 'rom', 'type' => 'select', 'label' => 'Range of motion', 'options' => ['full' => 'Full', 'reduced' => 'Reduced', 'fixed' => 'Fixed']],
            ['name' => 'neurovascular', 'type' => 'select', 'label' => 'Neurovascular', 'options' => ['intact' => 'Intact', 'impaired' => 'Impaired']],
            ['name' => 'imaging', 'type' => 'string', 'label' => 'Imaging', 'options' => []],
        ];
    }

    public function persistPatientProfile($patient, array $input): void
    {
        $data = [];
        $any = false;
        foreach (['affected_joint', 'rom', 'neurovascular', 'imaging'] 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 && ! OrthopedicsPatientProfile::where('clc_patient_id', $patient->id)->exists()) {
            return;
        }
        OrthopedicsPatientProfile::updateOrCreate(['clc_patient_id' => $patient->id], $data);
    }

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