<?php

namespace Modules\OphthalmologyClinic\Entities\Drivers;

use Modules\ClinicCore\Entities\Contracts\ClinicSpecialtyDriver;
use Modules\OphthalmologyClinic\Entities\OphthPatientProfile;

/**
 * Ophthalmology plugs into ClinicCore as a structural specialty: a 1:1 eye
 * profile (acuity / refraction / IOP) plus the Blade fragments ClinicCore
 * renders into the shared patient and appointment screens.
 */
class OphthalmologySpecialtyDriver implements ClinicSpecialtyDriver
{
    public function key(): string
    {
        return 'ophthalmology';
    }

    public function label(): string
    {
        return 'Ophthalmology';
    }

    public function patientProfileModel(): ?string
    {
        return OphthPatientProfile::class;
    }

    public function patientFormFragment(): ?string
    {
        return 'ophthClinic::specialty.patient_form';
    }

    public function patientShowFragment(): ?string
    {
        return 'ophthClinic::specialty.patient_show';
    }

    public function appointmentFragment(): ?string
    {
        return 'ophthClinic::specialty.patient_show';
    }

    public function persistPatientProfile($patient, array $input): void
    {
        $fields = [
            'va_right', 'va_left',
            'sphere_right', 'cylinder_right', 'axis_right',
            'sphere_left', 'cylinder_left', 'axis_left',
            'iop_right', 'iop_left', 'notes',
        ];

        $data = [];
        $any = false;
        foreach ($fields as $f) {
            $v = $input[$f] ?? null;
            $v = ($v === '' ? null : $v);
            $data[$f] = $v;
            if ($v !== null) $any = true;
        }
        $data['wears_glasses'] = ! empty($input['wears_glasses']);

        if (! $any && empty($data['wears_glasses'])
            && ! OphthPatientProfile::where('clc_patient_id', $patient->id)->exists()) {
            return;
        }

        OphthPatientProfile::updateOrCreate(['clc_patient_id' => $patient->id], $data);
    }

    public function examTemplateSeeds(): array
    {
        return ['Ophthalmology Exam'];
    }

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