<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

/**
 * Specialty-specific vital sets. Extra vitals are stored as a JSON map on the
 * appointment (clc_appointments.extra_vitals) so we never add a column per
 * specialty. The field definitions live either on the specialty's
 * clc_specialties.config['vital_fields'] (config-only specialties) or in a
 * structural driver's vitalFields() method.
 */
class AddSpecialtyVitalFields extends Migration
{
    /** code => [ [key,label,unit,type], … ] */
    private array $seed = [
        'pediatrics_newborn' => [
            ['key' => 'head_circumference', 'label' => 'Head circumference', 'unit' => 'cm',  'type' => 'number'],
            ['key' => 'muac',              'label' => 'MUAC',               'unit' => 'cm',  'type' => 'number'],
        ],
        'cardiology_vascular' => [
            ['key' => 'ecg_rhythm', 'label' => 'ECG rhythm', 'unit' => '',    'type' => 'text'],
            ['key' => 'map',        'label' => 'Mean arterial pressure', 'unit' => 'mmHg', 'type' => 'number'],
        ],
        'chest_respiratory' => [
            ['key' => 'peak_flow', 'label' => 'Peak flow', 'unit' => 'L/min', 'type' => 'number'],
        ],
        'endocrinology' => [
            ['key' => 'hba1c',  'label' => 'HbA1c',  'unit' => '%',  'type' => 'number'],
            ['key' => 'waist',  'label' => 'Waist',  'unit' => 'cm', 'type' => 'number'],
        ],
    ];

    public function up()
    {
        if (!Schema::hasColumn('clc_appointments', 'extra_vitals')) {
            Schema::table('clc_appointments', function (Blueprint $table) {
                $table->json('extra_vitals')->nullable()->after('bmi');
            });
        }

        foreach ($this->seed as $code => $fields) {
            $row = DB::table('clc_specialties')->whereNull('business_id')->where('code', $code)->first();
            if (!$row) continue;
            $config = $row->config ? json_decode($row->config, true) : [];
            if (!is_array($config)) $config = [];
            $config['vital_fields'] = $fields;   // overwrite/refresh
            DB::table('clc_specialties')->where('id', $row->id)
                ->update(['config' => json_encode($config)]);
        }
    }

    public function down()
    {
        if (Schema::hasColumn('clc_appointments', 'extra_vitals')) {
            Schema::table('clc_appointments', function (Blueprint $table) {
                $table->dropColumn('extra_vitals');
            });
        }
        foreach (array_keys($this->seed) as $code) {
            $row = DB::table('clc_specialties')->whereNull('business_id')->where('code', $code)->first();
            if (!$row || !$row->config) continue;
            $config = json_decode($row->config, true);
            if (is_array($config)) { unset($config['vital_fields']); }
            DB::table('clc_specialties')->where('id', $row->id)->update(['config' => json_encode($config)]);
        }
    }
}
