<?php

namespace Modules\PediatricsClinic\Entities\Drivers;

use Modules\ClinicCore\Entities\Contracts\ClinicSpecialtyDriver;
use Modules\PediatricsClinic\Entities\PediatricsPatientProfile;

/** Pediatrics & New Born plugs into ClinicCore as a structural specialty (1:1 profile). */
class PediatricsSpecialtyDriver implements ClinicSpecialtyDriver
{
    public function key(): string { return 'pediatrics_newborn'; }
    public function label(): string { return 'Pediatrics & New Born'; }
    public function patientProfileModel(): ?string { return PediatricsPatientProfile::class; }
    public function patientFormFragment(): ?string { return 'pediatricsClinic::specialty.patient_form'; }
    public function patientShowFragment(): ?string { return 'pediatricsClinic::specialty.patient_show'; }
    public function appointmentFragment(): ?string { return 'pediatricsClinic::specialty.patient_show'; }

    /** Field metadata driving the form/show fragments. */
    public function fields(): array
    {
        return [
            ['name' => 'weight_percentile', 'type' => 'int', 'label' => 'Weight percentile', 'options' => []],
            ['name' => 'height_percentile', 'type' => 'int', 'label' => 'Height percentile', 'options' => []],
            ['name' => 'head_circ_percentile', 'type' => 'int', 'label' => 'Head circ. percentile', 'options' => []],
            ['name' => 'milestones', 'type' => 'select', 'label' => 'Development', 'options' => ['ontrack' => 'On track', 'delayed' => 'Delayed']],
            ['name' => 'immunisation', 'type' => 'select', 'label' => 'Immunisation', 'options' => ['uptodate' => 'Up to date', 'behind' => 'Behind']],
        ];
    }

    public function persistPatientProfile($patient, array $input): void
    {
        $data = [];
        $any = false;
        foreach (['weight_percentile', 'height_percentile', 'head_circ_percentile', 'milestones', 'immunisation'] 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 && ! PediatricsPatientProfile::where('clc_patient_id', $patient->id)->exists()) {
            return;
        }
        PediatricsPatientProfile::updateOrCreate(['clc_patient_id' => $patient->id], $data);
    }

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