<?php

namespace Modules\GynaecologyClinic\Entities\Drivers;

use Modules\ClinicCore\Entities\Contracts\ClinicSpecialtyDriver;
use Modules\GynaecologyClinic\Entities\ObgynPatientProfile;

/**
 * Obstetrics & Gynaecology plugs into ClinicCore as a structural specialty: a
 * 1:1 obstetric profile (GPAL, menstrual cycle, current pregnancy LMP) whose
 * gestational age and EDD are computed, rendered into the shared screens.
 */
class GynaecologySpecialtyDriver implements ClinicSpecialtyDriver
{
    public function key(): string
    {
        return 'gynaecology';
    }

    public function label(): string
    {
        return 'Obstetrics & Gynaecology';
    }

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

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

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

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

    public function persistPatientProfile($patient, array $input): void
    {
        $ints = ['gravida', 'para', 'abortions', 'living', 'menarche_age', 'cycle_length_days'];
        $data = [];
        $any = false;
        foreach ($ints as $f) {
            $v = $input[$f] ?? null;
            $v = ($v === '' ? null : $v);
            $data[$f] = $v;
            if ($v !== null) $any = true;
        }

        $lmp = $input['lmp_date'] ?? null;
        $data['lmp_date']      = $lmp ?: null;
        $data['contraception'] = ($input['contraception'] ?? '') ?: null;
        $data['notes']         = ($input['notes'] ?? '') ?: null;
        $data['cycle_regular'] = ! empty($input['cycle_regular']);
        $data['is_pregnant']   = ! empty($input['is_pregnant']);
        $data['menopause']     = ! empty($input['menopause']);

        $hasFlags = $data['cycle_regular'] || $data['is_pregnant'] || $data['menopause'];
        if (! $any && ! $lmp && ! $hasFlags && empty($data['contraception']) && empty($data['notes'])
            && ! ObgynPatientProfile::where('clc_patient_id', $patient->id)->exists()) {
            return;
        }

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

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

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