<?php

namespace Modules\PrimaryCareClinic\Entities\Drivers;

use Modules\ClinicCore\Entities\Contracts\ClinicSpecialtyDriver;
use Modules\PrimaryCareClinic\Entities\PrimaryCarePatientProfile;

/** Primary Care plugs into ClinicCore as a structural specialty (1:1 profile). */
class PrimaryCareSpecialtyDriver implements ClinicSpecialtyDriver
{
    public function key(): string { return 'primary_care'; }
    public function label(): string { return 'Primary Care'; }
    public function patientProfileModel(): ?string { return PrimaryCarePatientProfile::class; }
    public function patientFormFragment(): ?string { return 'primaryCareClinic::specialty.patient_form'; }
    public function patientShowFragment(): ?string { return 'primaryCareClinic::specialty.patient_show'; }
    public function appointmentFragment(): ?string { return 'primaryCareClinic::specialty.patient_show'; }

    /** Field metadata driving the form/show fragments. */
    public function fields(): array
    {
        return [
            ['name' => 'bmi', 'type' => 'decimal', 'label' => 'BMI', 'options' => []],
            ['name' => 'chronic_problems', 'type' => 'text', 'label' => 'Chronic problems', 'options' => []],
            ['name' => 'screening_due', 'type' => 'string', 'label' => 'Screening due', 'options' => []],
        ];
    }

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

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