<?php

namespace Modules\RadiologyClinic\Entities\Drivers;

use Modules\ClinicCore\Entities\Contracts\ClinicSpecialtyDriver;
use Modules\RadiologyClinic\Entities\RadiologyPatientProfile;

/** Diagnostic Radiology plugs into ClinicCore as a structural specialty (1:1 profile). */
class RadiologySpecialtyDriver implements ClinicSpecialtyDriver
{
    public function key(): string { return 'diagnostic_radiology'; }
    public function label(): string { return 'Diagnostic Radiology'; }
    public function patientProfileModel(): ?string { return RadiologyPatientProfile::class; }
    public function patientFormFragment(): ?string { return 'radiologyClinic::specialty.patient_form'; }
    public function patientShowFragment(): ?string { return 'radiologyClinic::specialty.patient_show'; }
    public function appointmentFragment(): ?string { return 'radiologyClinic::specialty.patient_show'; }

    /** Field metadata driving the form/show fragments. */
    public function fields(): array
    {
        return [
            ['name' => 'modality', 'type' => 'select', 'label' => 'Modality', 'options' => ['xray' => 'X-ray', 'us' => 'Ultrasound', 'ct' => 'CT', 'mri' => 'MRI']],
            ['name' => 'region', 'type' => 'string', 'label' => 'Region', 'options' => []],
            ['name' => 'contrast', 'type' => 'bool', 'label' => 'Contrast', 'options' => []],
            ['name' => 'findings', 'type' => 'text', 'label' => 'Findings', 'options' => []],
        ];
    }

    public function persistPatientProfile($patient, array $input): void
    {
        $data = [];
        $any = false;
        foreach (['modality', 'region', 'findings'] as $f) {
            $v = $input[$f] ?? null;
            $v = ($v === '' ? null : $v);
            $data[$f] = $v;
            if ($v !== null) $any = true;
        }
        foreach (['contrast'] as $f) {
            $data[$f] = ! empty($input[$f]);
            if ($data[$f]) $any = true;
        }
        if (! $any && ! RadiologyPatientProfile::where('clc_patient_id', $patient->id)->exists()) {
            return;
        }
        RadiologyPatientProfile::updateOrCreate(['clc_patient_id' => $patient->id], $data);
    }

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