<?php

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

/**
 * Item 1.4 - seed the system-default "Standard General Exam" template.
 *
 * Anatomical-region structured exam covering BCS, vitals, mucous membranes,
 * lymph nodes, eyes, ears, oral, cardiac, respiratory, abdomen, msk, neuro,
 * skin/coat, urogenital. Each item carries severity weights so a single
 * "abnormal" pick promotes the visit into the Medical Critical Check
 * report (item 4.1). Always-on for every new appointment Objective tab.
 */
class ClcSeedGeneralExamTemplate extends Migration
{
    public function up()
    {
        $now = now();
        $exists = DB::table('clc_exam_templates')
            ->whereNull('business_id')
            ->where('kind', 'general')
            ->where('name', 'Standard General Exam')
            ->value('id');
        if ($exists) return;

        $tplId = DB::table('clc_exam_templates')->insertGetId([
            'business_id'   => null,
            'name'          => 'Standard General Exam',
            'kind'          => 'general',
            'species_scope' => 'all',
            'display_label' => 'General Exam',
            'icon'          => 'fa-stethoscope',
            'colour'        => '2980b9',
            'description'   => 'Always-on head-to-tail physical exam template.',
            'is_active'     => true,
            'sort_order'    => 0,
            'created_at'    => $now,
            'updated_at'    => $now,
        ]);

        // Helper to build options_json entries consistently.
        $opt = function ($value, $label, $severity = 0, $critical = false) {
            return ['value' => $value, 'label' => $label, 'severity' => $severity, 'is_critical' => $critical];
        };

        // The Normal / Abnormal / Not examined trio reused by simple items.
        $simpleNormalAbnormal = function () use ($opt) {
            return [
                $opt('normal',   'Normal',          0, false),
                $opt('abnormal', 'Abnormal',        2, false),
                $opt('ne',       'Not examined',    0, false),
            ];
        };

        $items = [
            // ── GENERAL / DEMEANOUR ───────────────────────────────
            ['General','Body condition score (1-9)','grade','none',[
                $opt('1','1 - Emaciated',                3,true),
                $opt('2','2 - Very thin',                3,true),
                $opt('3','3 - Thin',                     2,false),
                $opt('4','4 - Underweight',              1,false),
                $opt('5','5 - Ideal',                    0,false),
                $opt('6','6 - Slightly overweight',      1,false),
                $opt('7','7 - Overweight',               2,false),
                $opt('8','8 - Obese',                    3,false),
                $opt('9','9 - Severely obese',           3,true),
            ]],
            ['General','Demeanour','select','none',[
                $opt('bar',       'BAR - Bright, alert, responsive', 0, false),
                $opt('qar',       'QAR - Quiet, alert, responsive',  1, false),
                $opt('dull',      'Dull / lethargic',                2, false),
                $opt('depressed', 'Depressed',                       3, true),
                $opt('collapsed', 'Collapsed / unresponsive',        3, true),
            ]],
            ['General','Hydration status','select','none',[
                $opt('hydrated',  'Hydrated (<5%)',         0, false),
                $opt('mild',      'Mild dehydration 5-7%',  2, false),
                $opt('moderate',  'Moderate 8-10%',         3, true),
                $opt('severe',    'Severe 10-12%',          3, true),
                $opt('shock',     'Shock >12%',             3, true),
            ]],

            // ── MUCOUS MEMBRANES ──────────────────────────────────
            ['Mucous Membranes','Colour','select','none',[
                $opt('pink',     'Pink',                  0, false),
                $opt('pale',     'Pale',                  3, true),
                $opt('cyanotic', 'Cyanotic',              3, true),
                $opt('icteric',  'Icteric (yellow)',      3, true),
                $opt('injected', 'Injected / hyperemic',  2, false),
                $opt('muddy',    'Muddy / grey',          3, true),
            ]],
            ['Mucous Membranes','Capillary refill time','select','none',[
                $opt('lt2',  '< 2 seconds (normal)',      0, false),
                $opt('2-3',  '2-3 seconds (borderline)',  2, false),
                $opt('gt3',  '> 3 seconds',               3, true),
            ]],

            // ── LYMPH NODES ───────────────────────────────────────
            ['Lymph Nodes','Mandibular',   'select','lr', $simpleNormalAbnormal()],
            ['Lymph Nodes','Prescapular',  'select','lr', $simpleNormalAbnormal()],
            ['Lymph Nodes','Popliteal',    'select','lr', $simpleNormalAbnormal()],
            ['Lymph Nodes','Inguinal',     'select','lr', $simpleNormalAbnormal()],
            ['Lymph Nodes','Enlarged node details','text','none',null],

            // ── EYES ──────────────────────────────────────────────
            ['Eyes','Conjunctiva',     'select','od_os', $simpleNormalAbnormal()],
            ['Eyes','Discharge',       'select','od_os',[
                $opt('none',     'None',                  0, false),
                $opt('serous',   'Serous',                1, false),
                $opt('mucoid',   'Mucoid',                2, false),
                $opt('purulent', 'Purulent',              3, true),
            ]],
            ['Eyes','Cornea',          'select','od_os',[
                $opt('clear',     'Clear',                0, false),
                $opt('opacity',   'Opacity',              2, false),
                $opt('ulcer',     'Ulcer',                3, true),
                $opt('edema',     'Edema',                2, false),
            ]],
            ['Eyes','Pupil response',  'select','od_os',[
                $opt('plr_normal', 'PLR normal',           0, false),
                $opt('miosis',     'Miosis',               2, false),
                $opt('mydriasis',  'Mydriasis',            2, false),
                $opt('anisocoria', 'Anisocoria',           3, true),
            ]],

            // ── EARS ──────────────────────────────────────────────
            ['Ears','Pinna / canal',   'select','ad_as', $simpleNormalAbnormal()],
            ['Ears','Exudate',         'select','ad_as',[
                $opt('none',        'None',                0, false),
                $opt('ceruminous',  'Ceruminous (waxy)',   1, false),
                $opt('purulent',    'Purulent',            3, false),
                $opt('hemorrhagic', 'Hemorrhagic',         3, true),
            ]],
            ['Ears','Pain on palpation','yes_no','ad_as',[
                $opt('no',  'No pain',  0, false),
                $opt('yes', 'Painful',  2, false),
            ]],

            // ── ORAL CAVITY ───────────────────────────────────────
            ['Oral Cavity','Dental grade (0-4)','grade','none',[
                $opt('0','0 - No tartar / gingivitis',           0, false),
                $opt('1','1 - Mild tartar, marginal gingivitis', 1, false),
                $opt('2','2 - Moderate tartar, gingivitis',      2, false),
                $opt('3','3 - Heavy tartar, periodontitis',      3, false),
                $opt('4','4 - Severe / loose teeth, abscess',    3, true),
            ]],
            ['Oral Cavity','Mucosa',           'select','none', $simpleNormalAbnormal()],
            ['Oral Cavity','Halitosis',        'yes_no','none',[
                $opt('no',  'None / mild',         0, false),
                $opt('yes', 'Significant',         1, false),
            ]],
            ['Oral Cavity','Mass / ulcer noted','text','none', null],

            // ── CARDIOVASCULAR ────────────────────────────────────
            ['Cardiovascular','Heart rate (bpm)','measurement','none',null,'bpm',60,140,30,300],
            ['Cardiovascular','Rhythm','select','none',[
                $opt('sinus',          'Sinus rhythm',              0, false),
                $opt('sinus_arrhyth',  'Sinus arrhythmia (normal)', 0, false),
                $opt('arrhythmia',     'Arrhythmia',                3, true),
                $opt('gallop',         'Gallop rhythm',             3, true),
            ]],
            ['Cardiovascular','Murmur grade (I-VI)','grade','none',[
                $opt('none','None',                              0, false),
                $opt('I',   'I - Faint, barely audible',         1, false),
                $opt('II',  'II - Soft but easily heard',        2, false),
                $opt('III', 'III - Moderate intensity',          2, false),
                $opt('IV',  'IV - Loud, no thrill',              3, true),
                $opt('V',   'V - Loud with palpable thrill',     3, true),
                $opt('VI',  'VI - Audible with stethoscope off chest', 3, true),
            ]],
            ['Cardiovascular','Pulse character','select','none',[
                $opt('strong_synch', 'Strong, synchronous',         0, false),
                $opt('weak',         'Weak / thready',              3, true),
                $opt('bounding',     'Bounding / water-hammer',     2, false),
                $opt('asynch',       'Asynchronous / pulse deficit',3, true),
            ]],

            // ── RESPIRATORY ───────────────────────────────────────
            ['Respiratory','Respiratory rate (/min)','measurement','none',null,'/min',10,30,5,80],
            ['Respiratory','Respiratory effort','select','none',[
                $opt('normal',     'Normal',                   0, false),
                $opt('increased',  'Increased effort',         2, false),
                $opt('dyspnea',    'Dyspnea',                  3, true),
                $opt('orthopnea',  'Orthopnea',                3, true),
            ]],
            ['Respiratory','Lung sounds','select','lr',[
                $opt('clear',       'Clear',                   0, false),
                $opt('harsh',       'Harsh',                   1, false),
                $opt('crackles',    'Crackles',                3, true),
                $opt('wheezes',     'Wheezes',                 3, false),
                $opt('absent',      'Absent / muffled',        3, true),
            ]],

            // ── ABDOMINAL PALPATION ──────────────────────────────
            ['Abdomen','Palpation','select','none',[
                $opt('soft',     'Soft, non-painful',          0, false),
                $opt('tense',    'Tense',                      2, false),
                $opt('painful',  'Painful',                    3, true),
                $opt('mass',     'Mass palpated',              3, true),
                $opt('fluid',    'Fluid wave',                 3, true),
            ]],
            ['Abdomen','Organomegaly','select','none',[
                $opt('none',           'None',                          0, false),
                $opt('hepatomegaly',   'Hepatomegaly',                  2, false),
                $opt('splenomegaly',   'Splenomegaly',                  2, false),
                $opt('renal',          'Renomegaly',                    2, false),
                $opt('bladder',        'Bladder distention / pain',     3, true),
            ]],
            ['Abdomen','Findings note','text','none',null],

            // ── MUSCULOSKELETAL ──────────────────────────────────
            ['Musculoskeletal','Gait','select','none',[
                $opt('normal',  'Normal',                     0, false),
                $opt('stiff',   'Stiff',                      1, false),
                $opt('lame',    'Lame',                       2, false),
                $opt('nwb',     'Non-weight-bearing',         3, true),
                $opt('ataxic',  'Ataxic',                     3, true),
            ]],
            ['Musculoskeletal','Lameness grade (0-4)','grade','none',[
                $opt('0','0 - Sound',                                       0, false),
                $opt('1','1 - Mild, intermittent',                          1, false),
                $opt('2','2 - Mild, consistent',                            2, false),
                $opt('3','3 - Obvious lameness',                            3, false),
                $opt('4','4 - Non-weight-bearing',                          3, true),
            ]],
            ['Musculoskeletal','Affected limb','multi_select','none',[
                $opt('lf', 'Left fore',  2, false),
                $opt('rf', 'Right fore', 2, false),
                $opt('lh', 'Left hind',  2, false),
                $opt('rh', 'Right hind', 2, false),
            ]],
            ['Musculoskeletal','Muscle mass','select','none', $simpleNormalAbnormal()],

            // ── NEUROLOGICAL (basic screen; deep screen in Phase B) ─
            ['Neurological','Mentation','select','none',[
                $opt('normal',   'Normal',                  0, false),
                $opt('dull',     'Dull',                    2, false),
                $opt('obtunded', 'Obtunded',                3, true),
                $opt('stupor',   'Stupor',                  3, true),
                $opt('coma',     'Coma',                    3, true),
            ]],
            ['Neurological','Postural reactions','select','none', $simpleNormalAbnormal()],
            ['Neurological','Spinal palpation pain','yes_no','none',[
                $opt('no',  'No',  0, false),
                $opt('yes', 'Yes', 3, true),
            ]],

            // ── SKIN / COAT ──────────────────────────────────────
            ['Skin / Coat','Coat condition','select','none',[
                $opt('normal',     'Normal',           0, false),
                $opt('dry',        'Dry / dull',       1, false),
                $opt('alopecia',   'Alopecia',         2, false),
                $opt('greasy',     'Greasy / oily',    2, false),
            ]],
            ['Skin / Coat','Pruritus 0-10','grade','none',[
                $opt('0','0 - None',                       0, false),
                $opt('2','2 - Mild',                       1, false),
                $opt('5','5 - Moderate',                   2, false),
                $opt('8','8 - Severe',                     3, false),
                $opt('10','10 - Self-mutilating',          3, true),
            ]],
            ['Skin / Coat','Parasites','multi_select','none',[
                $opt('none',  'None seen',     0, false),
                $opt('fleas', 'Fleas',         2, false),
                $opt('ticks', 'Ticks',         2, false),
                $opt('mites', 'Mites',         2, false),
                $opt('lice',  'Lice',          2, false),
            ]],
            ['Skin / Coat','Lesion description','text','none',null],

            // ── UROGENITAL ───────────────────────────────────────
            ['Urogenital','External exam','select','none', $simpleNormalAbnormal()],
            ['Urogenital','Discharge','select','none',[
                $opt('none',     'None',              0, false),
                $opt('serous',   'Serous',            1, false),
                $opt('mucoid',   'Mucoid',            2, false),
                $opt('purulent', 'Purulent',          3, true),
                $opt('bloody',   'Sanguineous',       3, true),
            ]],
            ['Urogenital','Mammary chain (F)','select','none', $simpleNormalAbnormal()],
            ['Urogenital','Prostate (M, on rectal)','select','none', $simpleNormalAbnormal()],
        ];

        $sort = 0;
        foreach ($items as $row) {
            DB::table('clc_exam_template_items')->insert([
                'template_id'    => $tplId,
                'region'         => $row[0],
                'item_label'     => $row[1],
                'response_type'  => $row[2],
                'lateralisation' => $row[3],
                'options_json'   => $row[4] ? json_encode($row[4]) : null,
                'unit'           => $row[5] ?? null,
                'normal_low'     => $row[6] ?? null,
                'normal_high'    => $row[7] ?? null,
                'critical_low'   => $row[8] ?? null,
                'critical_high'  => $row[9] ?? null,
                'is_required'    => false,
                'sort_order'     => $sort++,
                'created_at'     => $now,
                'updated_at'     => $now,
            ]);
        }
    }

    public function down()
    {
        $tplId = DB::table('clc_exam_templates')
            ->whereNull('business_id')
            ->where('kind', 'general')
            ->where('name', 'Standard General Exam')
            ->value('id');
        if (!$tplId) return;
        DB::table('clc_exam_template_items')->where('template_id', $tplId)->delete();
        DB::table('clc_exam_templates')->where('id', $tplId)->delete();
    }
}
