<?php

namespace Modules\GeneralPracticeClinic\Entities\Drivers;

use Modules\ClinicCore\Entities\Contracts\ClinicSpecialtyDriver;
use Modules\GeneralPracticeClinic\Entities\GeneralPracticePatientProfile;

/** General Practice plugs into ClinicCore as a structural specialty (1:1 profile). */
class GeneralPracticeSpecialtyDriver implements ClinicSpecialtyDriver
{
    public function key(): string { return 'general_practice'; }
    public function label(): string { return 'General Practice'; }
    public function patientProfileModel(): ?string { return GeneralPracticePatientProfile::class; }
    public function patientFormFragment(): ?string { return 'generalPracticeClinic::specialty.patient_form'; }
    public function patientShowFragment(): ?string { return 'generalPracticeClinic::specialty.patient_show'; }
    public function appointmentFragment(): ?string { return 'generalPracticeClinic::specialty.patient_show'; }

    /** Field metadata driving the form/show fragments. */
    public function fields(): array
    {
        return [
            ['name' => 'bmi', 'type' => 'decimal', 'label' => 'BMI', 'options' => []],
            ['name' => 'smoking', 'type' => 'select', 'label' => 'Smoking', 'options' => ['never' => 'Never', 'ex' => 'Ex-smoker', 'current' => 'Current']],
            ['name' => 'alcohol', 'type' => 'select', 'label' => 'Alcohol', 'options' => ['none' => 'None', 'occasional' => 'Occasional', 'regular' => 'Regular']],
            ['name' => 'risk_factors', 'type' => 'text', 'label' => 'Risk factors', 'options' => []],
        ];
    }

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

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