<?php

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

/**
 * Item #4a — promote the in-JS body-system finding catalogue
 * (systemFindings object in appointments/show.blade.php) to a real DB
 * table so clinics can edit findings via an admin UI instead of needing
 * a code change.
 *
 * Schema:
 *   business_id        null = system default, otherwise per-clinic override
 *   system_key         alias used to match a body-system row
 *                      (heart, lungs, eyes, ears, nose_throat, mouth_teeth_gums,
 *                       abdomen, musculoskeletal, skin_hair_coat, neurological)
 *   value              machine key for the finding (persisted in systemStates)
 *   label              display text
 *   supports_severity  show Mild/Moderate/Severe radio
 *   supports_lr        show L/R toggles
 *   is_critical        any positive selection flags the visit into the
 *                      Medical Critical Check report
 *   sort_order         display order within the system catalogue
 *   status             active|inactive (soft-disable without deleting)
 *
 * Lookup pattern in code mirrors clc_soap_options: business-scoped row
 * shadows the same-keyed system row.
 *
 * Same migration also seeds the full system-default catalogue so a fresh
 * install gets identical UX to today (no regression on upgrade).
 */
class CreateClcSystemFindingsTable extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('clc_system_findings')) {
            Schema::create('clc_system_findings', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->nullable()->index();
                $table->string('system_key', 40)->index();
                $table->string('value', 60);
                $table->string('label', 160);
                $table->boolean('supports_severity')->default(false);
                $table->boolean('supports_lr')->default(false);
                $table->boolean('is_critical')->default(false)->index();
                $table->unsignedSmallInteger('sort_order')->default(0);
                $table->enum('status', ['active','inactive'])->default('active')->index();
                $table->timestamps();
                $table->unique(['business_id','system_key','value'], 'clc_sysf_uniq');
            });
        }

        // Seed system defaults (business_id = null). Idempotent — skips if
        // any system-default row already exists (e.g. from a re-run).
        if (DB::table('clc_system_findings')->whereNull('business_id')->exists()) {
            return;
        }

        $now = now();
        $seed = $this->systemFindingsSeed();
        $rows = [];
        foreach ($seed as $key => $items) {
            $order = 0;
            foreach ($items as $it) {
                $rows[] = [
                    'business_id'       => null,
                    'system_key'        => $key,
                    'value'             => $it['value'],
                    'label'             => $it['label'],
                    'supports_severity' => !empty($it['severity']),
                    'supports_lr'       => !empty($it['lr']),
                    'is_critical'       => !empty($it['critical']),
                    'sort_order'        => $order++,
                    'status'            => 'active',
                    'created_at'        => $now,
                    'updated_at'        => $now,
                ];
            }
        }
        foreach (array_chunk($rows, 100) as $chunk) {
            DB::table('clc_system_findings')->insert($chunk);
        }
    }

    public function down()
    {
        Schema::dropIfExists('clc_system_findings');
    }

    /** Mirror of the systemFindings JS object — kept ordering identical. */
    private function systemFindingsSeed(): array
    {
        return [
            'heart' => [
                ['value'=>'bradycardia',    'label'=>'Bradycardia (slow)',                    'critical'=>true],
                ['value'=>'tachycardia',    'label'=>'Tachycardia (fast)',                    'critical'=>true],
                ['value'=>'murmur',         'label'=>'Murmur',          'severity'=>true,'lr'=>true,'critical'=>true],
                ['value'=>'murmur_grade1',  'label'=>'Murmur grade I/VI (faint)'],
                ['value'=>'murmur_grade3',  'label'=>'Murmur grade III/VI (moderate)', 'severity'=>true],
                ['value'=>'murmur_grade5',  'label'=>'Murmur grade V/VI (palpable thrill)',  'critical'=>true],
                ['value'=>'arrhythmia',     'label'=>'Arrhythmia',                            'critical'=>true],
                ['value'=>'gallop',         'label'=>'Gallop rhythm',                         'critical'=>true],
                ['value'=>'pulse_weak',     'label'=>'Weak / thready pulse',                  'critical'=>true],
                ['value'=>'pulse_async',    'label'=>'Asynchronous pulse / deficit',          'critical'=>true],
                ['value'=>'pulse_bounding', 'label'=>'Bounding / water-hammer pulse'],
                ['value'=>'jugular_dist',   'label'=>'Jugular distention',                    'critical'=>true],
                ['value'=>'hepato_jug',     'label'=>'Hepatojugular reflux positive',         'critical'=>true],
                ['value'=>'pmi_shifted',    'label'=>'Point of maximal intensity shifted'],
            ],
            'lungs' => [
                ['value'=>'crackles',     'label'=>'Crackles',                              'critical'=>true],
                ['value'=>'wheezes',      'label'=>'Wheezes'],
                ['value'=>'rapid_breath', 'label'=>'Rapid breathing'],
                ['value'=>'coughing',     'label'=>'Coughing'],
                ['value'=>'tracheitis',   'label'=>'Tracheitis'],
                ['value'=>'congestion',   'label'=>'Congestion'],
                ['value'=>'labored',      'label'=>'Laboured breathing / dyspnea',          'critical'=>true],
                ['value'=>'discharge',    'label'=>'Discharge'],
                ['value'=>'lung_absent',  'label'=>'Absent / muffled sounds',               'critical'=>true],
            ],
            'eyes' => [
                ['value'=>'discharge',      'label'=>'Discharge',     'severity'=>true,'lr'=>true],
                ['value'=>'entropion',      'label'=>'Entropion',                  'lr'=>true],
                ['value'=>'ectropion',      'label'=>'Ectropion',                  'lr'=>true],
                ['value'=>'corneal_ulcer',  'label'=>'Corneal ulcer',              'lr'=>true,'critical'=>true],
                ['value'=>'corneal_edema',  'label'=>'Corneal edema','severity'=>true,'lr'=>true],
                ['value'=>'cataracts',      'label'=>'Cataracts',    'severity'=>true,'lr'=>true],
                ['value'=>'lid_growth',     'label'=>'Lid growth / mass',          'lr'=>true],
                ['value'=>'conjunctivitis', 'label'=>'Conjunctivitis','severity'=>true,'lr'=>true],
                ['value'=>'kcs_dry_eye',    'label'=>'Dry eye (KCS suspect)',      'lr'=>true],
                ['value'=>'schirmer_low',   'label'=>'Schirmer < 10 mm/min',       'lr'=>true,'critical'=>true],
                ['value'=>'iop_high',       'label'=>'IOP elevated (>25 mmHg)',    'lr'=>true,'critical'=>true],
                ['value'=>'iop_low',        'label'=>'IOP low (<10 mmHg)',         'lr'=>true,'critical'=>true],
                ['value'=>'fluorescein_pos','label'=>'Fluorescein stain positive', 'lr'=>true,'critical'=>true],
                ['value'=>'lens_lux',       'label'=>'Lens luxation / subluxation','lr'=>true,'critical'=>true],
                ['value'=>'fundic_abnorm',  'label'=>'Fundic exam abnormal',       'lr'=>true],
                ['value'=>'retinal_detach', 'label'=>'Retinal detachment',         'lr'=>true,'critical'=>true],
                ['value'=>'third_eyelid',   'label'=>'Third eyelid prominence',    'lr'=>true],
                ['value'=>'plr_abnormal',   'label'=>'PLR abnormal',               'lr'=>true,'critical'=>true],
                ['value'=>'anisocoria',     'label'=>'Anisocoria',                            'critical'=>true],
            ],
            'ears' => [
                ['value'=>'scaly_border','label'=>'Scaly border',              'lr'=>true],
                ['value'=>'ear_mites',   'label'=>'Ear mites',                 'lr'=>true],
                ['value'=>'excess_hair', 'label'=>'Excess hair',               'lr'=>true],
                ['value'=>'excess_wax',  'label'=>'Excess wax',                'lr'=>true],
                ['value'=>'exudate',     'label'=>'Exudate',  'severity'=>true,'lr'=>true],
                ['value'=>'inflamed',    'label'=>'Inflamed', 'severity'=>true,'lr'=>true],
                ['value'=>'pus',         'label'=>'Pus / purulent',           'lr'=>true,'critical'=>true],
                ['value'=>'pain',        'label'=>'Pain on palpation','severity'=>true,'lr'=>true],
                ['value'=>'mass',        'label'=>'Mass / growth',            'lr'=>true],
            ],
            'nose_throat' => [
                ['value'=>'dry_crusty',     'label'=>'Dry / crusty'],
                ['value'=>'enl_tonsils',    'label'=>'Enlarged tonsils'],
                ['value'=>'enl_lymph',      'label'=>'Enlarged lymph glands','critical'=>true],
                ['value'=>'nose_discharge', 'label'=>'Nasal discharge','severity'=>true,'lr'=>true],
                ['value'=>'mass',           'label'=>'Mass / growth','critical'=>true],
            ],
            'mouth_teeth_gums' => [
                ['value'=>'loose_tooth',    'label'=>'Loose tooth','severity'=>true],
                ['value'=>'broken_tooth',   'label'=>'Broken tooth'],
                ['value'=>'stained_tooth',  'label'=>'Stained tooth'],
                ['value'=>'pale_membranes', 'label'=>'Pale mucous membranes','critical'=>true],
                ['value'=>'cyanotic_mm',    'label'=>'Cyanotic mucous membranes','critical'=>true],
                ['value'=>'icteric_mm',     'label'=>'Icteric mucous membranes','critical'=>true],
                ['value'=>'tartar',         'label'=>'Tartar','severity'=>true],
                ['value'=>'gingivitis',     'label'=>'Gingivitis','severity'=>true],
                ['value'=>'periodontitis',  'label'=>'Periodontitis (pocket >3mm)','critical'=>true],
                ['value'=>'furcation',      'label'=>'Furcation exposure'],
                ['value'=>'tooth_mobility', 'label'=>'Tooth mobility grade 2-3','critical'=>true],
                ['value'=>'missing_teeth',  'label'=>'Missing teeth (record numbers in notes)'],
                ['value'=>'malocclusion',   'label'=>'Malocclusion'],
                ['value'=>'halitosis',      'label'=>'Halitosis','severity'=>true],
                ['value'=>'mass_ulcer',     'label'=>'Mass / ulcer','critical'=>true],
                ['value'=>'feline_resorp',  'label'=>'Feline tooth resorption lesion','critical'=>true],
                ['value'=>'recommend_dental','label'=>'Dental cleaning recommended'],
            ],
            'abdomen' => [
                ['value'=>'mass',         'label'=>'Abdominal mass','critical'=>true],
                ['value'=>'ascites',      'label'=>'Ascites (fluid)','critical'=>true],
                ['value'=>'tense',        'label'=>'Tense / painful'],
                ['value'=>'hernia_umb',   'label'=>'Umbilical hernia'],
                ['value'=>'hernia_ing',   'label'=>'Inguinal hernia'],
                ['value'=>'hepatomegaly', 'label'=>'Hepatomegaly'],
                ['value'=>'splenomegaly', 'label'=>'Splenomegaly'],
                ['value'=>'bladder_pain', 'label'=>'Bladder pain / distention','critical'=>true],
            ],
            'musculoskeletal' => [
                ['value'=>'pain',          'label'=>'Pain','severity'=>true,'lr'=>true],
                ['value'=>'lameness',      'label'=>'Lameness','severity'=>true,'lr'=>true],
                ['value'=>'nwb',           'label'=>'Non-weight-bearing','critical'=>true,'lr'=>true],
                ['value'=>'nail_problem',  'label'=>'Nail problem','lr'=>true],
                ['value'=>'joint_problem', 'label'=>'Joint problem(s)','lr'=>true],
                ['value'=>'muscle_atrophy','label'=>'Muscle atrophy','lr'=>true],
                ['value'=>'swelling',      'label'=>'Swelling','lr'=>true],
            ],
            'skin_hair_coat' => [
                ['value'=>'dull_dry',       'label'=>'Dull / dry coat'],
                ['value'=>'shedding',       'label'=>'Excess shedding'],
                ['value'=>'scaly',          'label'=>'Scaly'],
                ['value'=>'scabs',          'label'=>'Scabs'],
                ['value'=>'hair_loss',      'label'=>'Hair loss / alopecia','severity'=>true,'lr'=>true],
                ['value'=>'matted',         'label'=>'Matted'],
                ['value'=>'hot_spot',       'label'=>'Hot spot','lr'=>true],
                ['value'=>'staph',          'label'=>'Staph infection (pyoderma)','severity'=>true],
                ['value'=>'abscess',        'label'=>'Abscess','critical'=>true,'lr'=>true],
                ['value'=>'cyst',           'label'=>'Cyst','lr'=>true],
                ['value'=>'fleas',          'label'=>'Fleas'],
                ['value'=>'ticks',          'label'=>'Ticks'],
                ['value'=>'mange',          'label'=>'Mange / mites'],
                ['value'=>'tumor',          'label'=>'Tumor / mass','critical'=>true,'lr'=>true],
                ['value'=>'wart',           'label'=>'Wart','lr'=>true],
                ['value'=>'pruritus',       'label'=>'Excessive licking / pruritus','severity'=>true],
                ['value'=>'papules',        'label'=>'Papules / pustules','severity'=>true],
                ['value'=>'erythema',       'label'=>'Erythema','severity'=>true],
                ['value'=>'lichenification','label'=>'Lichenification'],
                ['value'=>'hyperpigment',   'label'=>'Hyperpigmentation'],
                ['value'=>'malasezzia',     'label'=>'Suspect Malassezia (greasy / odour)'],
                ['value'=>'ringworm_susp',  'label'=>'Suspect dermatophytosis'],
                ['value'=>'woods_lamp_pos', 'label'=>"Wood's lamp positive"],
                ['value'=>'cytology_done',  'label'=>'Cytology performed'],
                ['value'=>'scrape_done',    'label'=>'Skin scrape performed'],
            ],
            'neurological' => [
                ['value'=>'mentation_dull',     'label'=>'Mentation: dull','severity'=>true],
                ['value'=>'mentation_obtunded', 'label'=>'Mentation: obtunded','critical'=>true],
                ['value'=>'mentation_stupor',   'label'=>'Mentation: stupor','critical'=>true],
                ['value'=>'mentation_coma',     'label'=>'Mentation: coma','critical'=>true],
                ['value'=>'gait_ataxic',        'label'=>'Ataxic gait','severity'=>true],
                ['value'=>'gait_circling',      'label'=>'Circling','lr'=>true],
                ['value'=>'head_tilt',          'label'=>'Head tilt','lr'=>true],
                ['value'=>'nystagmus',          'label'=>'Nystagmus','severity'=>true],
                ['value'=>'tremors',            'label'=>'Tremors','severity'=>true],
                ['value'=>'seizure_observed',   'label'=>'Seizure activity observed','critical'=>true],
                ['value'=>'pr_deficit',         'label'=>'Postural reaction deficit','severity'=>true,'lr'=>true],
                ['value'=>'hopping_abnormal',   'label'=>'Hopping response abnormal','lr'=>true],
                ['value'=>'pp_deficit',         'label'=>'Proprioception deficit','severity'=>true,'lr'=>true],
                ['value'=>'reflex_hyper',       'label'=>'Hyperreflexia (UMN sign)','severity'=>true,'lr'=>true],
                ['value'=>'reflex_hypo',        'label'=>'Hyporeflexia (LMN sign)','severity'=>true,'lr'=>true],
                ['value'=>'crossed_extensor',   'label'=>'Crossed-extensor reflex','lr'=>true,'critical'=>true],
                ['value'=>'cn_facial_paresis',  'label'=>'Facial paresis (CN VII)','lr'=>true],
                ['value'=>'cn_horners',         'label'=>'Horner syndrome','lr'=>true],
                ['value'=>'cn_menace_absent',   'label'=>'Menace response absent (CN II/VII)','lr'=>true],
                ['value'=>'cn_corneal_absent',  'label'=>'Corneal reflex absent (CN V/VII)','lr'=>true],
                ['value'=>'dp_intact',          'label'=>'Deep pain intact (all limbs)'],
                ['value'=>'dp_absent',          'label'=>'Deep pain ABSENT','critical'=>true,'lr'=>true],
                ['value'=>'spinal_pain',        'label'=>'Spinal palpation pain','severity'=>true,'critical'=>true],
                ['value'=>'anal_tone_absent',   'label'=>'Anal tone absent','critical'=>true],
                ['value'=>'incontinent',        'label'=>'Urinary / faecal incontinence','critical'=>true],
            ],
        ];
    }
}
