<?php

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

/**
 * Seed a focused, structured default exam sheet for every config-only
 * specialty (those without a code plugin), tagged with the specialty so it
 * surfaces only on appointments booked under it. Dermatology and Dental are
 * skipped — their plugins own richer sheets. Idempotent on (specialty_id, name).
 *
 * Each sheet is a sensible starting point a clinic can clone/edit per business;
 * the generic "General Examination" remains available to every specialty.
 */
class SeedSpecialtyExamTemplates extends Migration
{
    public function up()
    {
        if (! Schema::hasTable('clc_exam_templates')) return;
        if (! Schema::hasColumn('clc_exam_templates', 'specialty_id')) return;

        $now = now();
        $specialties = DB::table('clc_specialties')->whereNull('business_id')->pluck('id', 'code');

        // option helpers -------------------------------------------------
        $o  = fn ($v, $l, $s = 0, $c = false) => ['value' => $v, 'label' => $l, 'severity' => $s, 'is_critical' => $c];
        $NA = [['value'=>'normal','label'=>'Normal','severity'=>0,'is_critical'=>false],
               ['value'=>'abnormal','label'=>'Abnormal','severity'=>2,'is_critical'=>false],
               ['value'=>'ne','label'=>'Not examined','severity'=>0,'is_critical'=>false]];
        $YN = [['value'=>'no','label'=>'No','severity'=>0,'is_critical'=>false],
               ['value'=>'yes','label'=>'Yes','severity'=>2,'is_critical'=>false]];
        // item builder: [region, label, type, options|null]
        $sel = fn ($region, $label, $opts = null) => [$region, $label, $opts === null ? 'select' : 'select', $opts ?? $NA];
        $txt = fn ($region, $label) => [$region, $label, 'text', null];
        $yn  = fn ($region, $label) => [$region, $label, 'yes_no', $YN];

        // ── Sheet definitions: code => [name, icon, colour, items[]] ─────
        $sheets = [
            'emergency_icu' => ['Emergency Triage (ABCDE)', 'fa-truck-medical', 'dc3545', [
                ['Triage','Triage category','select',[$o('green','Non-urgent'),$o('yellow','Urgent',1),$o('orange','Very urgent',2),$o('red','Immediate',3,true)]],
                $sel('A','Airway'), $sel('B','Breathing'), $sel('C','Circulation'),
                ['D','Disability (GCS)','select',[$o('15','GCS 15'),$o('13','GCS 13-14',1),$o('9','GCS 9-12',2),$o('8','GCS ≤8',3,true)]],
                $sel('E','Exposure / other'), $txt('Notes','Presenting problem'),
            ]],
            'general_practice'  => ['General Consultation', 'fa-user-doctor', '0d6efd', null],
            'family_medicine'   => ['Family Medicine Consultation', 'fa-house-medical', '0d6efd', null],
            'primary_care'      => ['Primary Care Consultation', 'fa-notes-medical', '0d6efd', null],
            'internal_medicine' => ['Internal Medicine Review', 'fa-stethoscope', '0d6efd', null],
            'services'          => ['Service Intake', 'fa-hand-holding-medical', '6c757d', [
                $txt('Service','Service requested'), $sel('Assessment','Patient suitability'), $txt('Notes','Notes'),
            ]],
            'geriatrics' => ['Geriatric Assessment', 'fa-person-cane', '0d6efd', [
                $sel('Cognition','Cognitive screen (e.g. MMSE)'),
                ['Function','Activities of daily living','select',[$o('independent','Independent'),$o('partial','Partial dependence',1),$o('dependent','Dependent',2)]],
                $yn('Falls','Falls in last 6 months'), $yn('Frailty','Frailty present'),
                $sel('Mood','Mood / depression screen'), $sel('Continence','Continence'), $sel('Nutrition','Nutritional status'),
            ]],
            'pediatrics_newborn' => ['Paediatric / Newborn Exam', 'fa-baby', '20c997', [
                ['Growth','Weight percentile','measurement','none'], ['Growth','Length/Height percentile','measurement','none'],
                ['Growth','Head circumference percentile','measurement','none'],
                $sel('Development','Developmental milestones'), $sel('Feeding','Feeding / nutrition'),
                ['Immunisation','Immunisation status','select',[$o('uptodate','Up to date'),$o('behind','Behind schedule',2)]],
                $sel('Exam','General newborn examination'),
            ]],
            'ophthalmology' => ['Ophthalmology Exam', 'fa-eye', '6610f2', [
                ['Acuity','Visual acuity — Right','text','none'], ['Acuity','Visual acuity — Left','text','none'],
                ['Pressure','Intraocular pressure (mmHg)','measurement','none','mmHg',10,21,null,30],
                $sel('Anterior','Anterior segment'), $sel('Fundus','Fundus / retina'), $sel('Pupils','Pupil reactions'),
            ]],
            'ent' => ['ENT Examination', 'fa-ear-listen', '6610f2', [
                $sel('Ear','Otoscopy (ears)'), $sel('Hearing','Hearing'), $sel('Nose','Nasal cavity'),
                $sel('Throat','Oropharynx / throat'), $sel('Neck','Neck / lymph nodes'),
            ]],
            'orthopedics' => ['Orthopaedic Exam', 'fa-bone', 'fd7e14', [
                $txt('Site','Affected joint / region'), $sel('ROM','Range of motion'), $sel('Stability','Joint stability'),
                $sel('Neurovascular','Distal neurovascular status'), $sel('Gait','Gait'), $yn('Imaging','Imaging requested'),
            ]],
            'urology' => ['Urology Exam', 'fa-droplet', 'fd7e14', [
                $sel('Symptoms','Lower urinary tract symptoms'), $sel('Flank','Renal angle / flank'),
                $sel('Genitalia','External genitalia'), $sel('Prostate','Prostate (DRE)'), $sel('Urinalysis','Urinalysis'),
            ]],
            'andrology' => ['Andrology Assessment', 'fa-mars', 'fd7e14', [
                $sel('Function','Erectile / sexual function'), $sel('Testes','Testicular examination'),
                $sel('Varicocele','Varicocele'), $yn('Hormonal','Hormonal symptoms'), $txt('Notes','Semen analysis / notes'),
            ]],
            'cardiology_vascular' => ['Cardiovascular Exam', 'fa-heart-pulse', 'dc3545', [
                $sel('Heart','Heart sounds'), $yn('Murmur','Murmur present'),
                ['BP','Blood pressure','text','none'], $sel('Pulses','Peripheral pulses'),
                $sel('Oedema','Peripheral oedema'), $yn('ECG','ECG performed'),
            ]],
            'endocrinology' => ['Endocrine / Diabetes Review', 'fa-vials', '198754', [
                $sel('Thyroid','Thyroid examination'), ['BMI','BMI','measurement','none','kg/m²',18.5,25,null,40],
                $sel('Glycaemic','Glycaemic control'), $sel('Foot','Diabetic foot screen'), $sel('Signs','Endocrine signs'),
            ]],
            'gastroenterology' => ['GI Examination', 'fa-stomach', '198754', [
                $sel('Abdomen','Abdominal examination'), $yn('Hepatomegaly','Hepatomegaly'),
                $sel('Bowel','Bowel habit'), $sel('PR','Per-rectal examination'), $yn('Endoscopy','Endoscopy indicated'),
            ]],
            'hematology' => ['Haematology Review', 'fa-droplet', 'dc3545', [
                $sel('Pallor','Pallor'), $yn('Lymphadenopathy','Lymphadenopathy'), $yn('Splenomegaly','Splenomegaly'),
                $yn('Bruising','Bruising / bleeding'), $txt('Labs','CBC / film notes'),
            ]],
            'hepatology' => ['Hepatology Exam', 'fa-disease', '198754', [
                $yn('Jaundice','Jaundice'), $yn('Ascites','Ascites'), $yn('Hepatomegaly','Hepatomegaly'),
                $sel('Encephalopathy','Encephalopathy signs'), $txt('Labs','LFT / notes'),
            ]],
            'nephrology' => ['Nephrology Review', 'fa-kidneys', '0dcaf0', [
                ['BP','Blood pressure','text','none'], $sel('Oedema','Oedema'), $sel('Fluid','Fluid status'),
                $sel('Urinalysis','Urinalysis'), $txt('Labs','eGFR / creatinine'),
            ]],
            'neurology' => ['Neurological Exam', 'fa-brain', '6f42c1', [
                ['Consciousness','GCS','select',[$o('15','GCS 15'),$o('13','GCS 13-14',1),$o('9','GCS 9-12',2),$o('8','GCS ≤8',3,true)]],
                $sel('Cranial','Cranial nerves'), $sel('Motor','Motor system'), $sel('Sensory','Sensory system'),
                $sel('Reflexes','Reflexes'), $sel('Gait','Gait & coordination'),
            ]],
            'oncology' => ['Oncology Assessment', 'fa-ribbon', 'd63384', [
                ['ECOG','Performance status (ECOG)','select',[$o('0','0 — Fully active'),$o('1','1 — Restricted',1),$o('2','2 — Ambulatory',2),$o('3','3 — Limited',2),$o('4','4 — Disabled',3,true)]],
                $txt('Tumour','Primary site'), $yn('Nodes','Lymphadenopathy'), $yn('WeightLoss','Significant weight loss'),
                $txt('Staging','Staging / notes'),
            ]],
            'pain_management' => ['Pain Assessment', 'fa-hand-holding-medical', 'fd7e14', [
                ['Score','Pain score 0–10','grade','none',[$o('0','0'),$o('3','3',1),$o('6','6',2),$o('9','9',3),$o('10','10',3,true)]],
                $txt('Site','Pain site'), $sel('Character','Pain character'), $yn('Neuropathic','Neuropathic features'),
                $sel('Function','Functional impact'),
            ]],
            'rheumatology' => ['Rheumatology Exam', 'fa-hand', 'fd7e14', [
                $txt('Joints','Affected joints'), $sel('Swelling','Joint swelling'), $sel('Tenderness','Joint tenderness'),
                $yn('Deformity','Deformity'), $sel('Function','Functional status'),
            ]],
            'chest_respiratory' => ['Respiratory Exam', 'fa-lungs', '0dcaf0', [
                $sel('Breath','Breath sounds'), ['SpO2','SpO₂ (%)','measurement','none','%',94,100,90,null],
                ['Dyspnoea','Dyspnoea (mMRC)','select',[$o('0','0 — Strenuous only'),$o('1','1 — Hurrying',1),$o('2','2 — Slower than peers',2),$o('3','3 — Stops after 100m',2),$o('4','4 — At rest',3,true)]],
                $yn('Cough','Cough'), $yn('Spirometry','Spirometry done'),
            ]],
            'allergy_immunology' => ['Allergy / Immunology Review', 'fa-shield-virus', '198754', [
                $sel('Symptoms','Allergic symptoms'), $txt('Triggers','Suspected triggers'),
                $yn('SkinTest','Skin prick test done'), $yn('Anaphylaxis','History of anaphylaxis'),
            ]],
            'general_surgery' => ['Surgical Assessment', 'fa-scalpel', '6c757d', [
                $txt('Site','Surgical site / complaint'), $sel('Mass','Mass / swelling'), $yn('Hernia','Hernia'),
                $sel('Wound','Wound (if post-op)'), $sel('Fitness','Pre-operative fitness'),
            ]],
            'neurosurgery' => ['Neurosurgical Assessment', 'fa-brain', '6f42c1', [
                ['Consciousness','GCS','select',[$o('15','GCS 15'),$o('13','GCS 13-14',1),$o('9','GCS 9-12',2),$o('8','GCS ≤8',3,true)]],
                $yn('Deficit','Focal neurological deficit'), $txt('Region','Spine / cranial region'), $yn('Imaging','Imaging available'),
            ]],
            'oncology_surgery' => ['Surgical Oncology Assessment', 'fa-ribbon', 'd63384', [
                $txt('Tumour','Tumour site'), $sel('Resectability','Resectability'), $yn('Nodes','Nodal involvement'), $txt('Staging','Staging'),
            ]],
            'pediatric_surgery' => ['Paediatric Surgical Exam', 'fa-baby', '20c997', [
                $txt('Complaint','Surgical complaint'), $yn('Congenital','Congenital anomaly'),
                $sel('Abdomen','Abdominal examination'), $sel('Hydration','Hydration status'),
            ]],
            'plastic_surgery' => ['Plastic Surgery Assessment', 'fa-wand-magic-sparkles', 'e83e8c', [
                $txt('Site','Defect / site'), $sel('Tissue','Tissue / flap viability'), $txt('Aesthetic','Aesthetic assessment'), $sel('Wound','Wound status'),
            ]],
            'spinal_surgery' => ['Spinal Assessment', 'fa-bone', 'fd7e14', [
                $txt('Level','Spinal level'), $yn('Deficit','Neurological deficit'), $sel('ROM','Spinal range of motion'),
                $yn('RedFlags','Red flag symptoms'),
            ]],
            'vascular_surgery' => ['Vascular Exam', 'fa-heart-circle-bolt', 'dc3545', [
                $sel('Pulses','Peripheral pulses'), ['ABI','Ankle-brachial index','measurement','none',null,0.9,1.3,0.5,null],
                $yn('Ulcers','Ulcers'), $yn('Varicose','Varicose veins'), $yn('Claudication','Claudication'),
            ]],
            'cardiothoracic_surgery' => ['Cardiothoracic Assessment', 'fa-heart-pulse', 'dc3545', [
                $sel('Cardiac','Cardiac examination'), $sel('Chest','Chest / lungs'), $sel('Sternum','Sternum (if post-op)'),
                $sel('Fitness','Pre-operative fitness'),
            ]],
            'obesity_laparoscopic' => ['Bariatric Assessment', 'fa-weight-scale', '6c757d', [
                ['BMI','BMI','measurement','none','kg/m²',18.5,25,40,null], $txt('Comorbid','Comorbidities'),
                $sel('Abdomen','Abdominal examination'), $sel('Eligibility','Bariatric eligibility'),
            ]],
            'gynaecology' => ['Gynaecology Exam', 'fa-venus', 'e83e8c', [
                $txt('Menstrual','Menstrual history'), $sel('Pelvic','Pelvic examination'), $sel('PV','Per-vaginal examination'),
                $yn('Smear','Cervical smear taken'), $yn('Pregnant','Pregnancy suspected'),
            ]],
            'ivf' => ['Fertility / IVF Assessment', 'fa-dna', 'e83e8c', [
                $txt('Cycle','Cycle day'), $sel('Reserve','Ovarian reserve'), $txt('Follicles','Follicle scan'), $txt('Hormones','Hormonal profile'),
            ]],
            'diagnostic_radiology' => ['Imaging Request', 'fa-x-ray', '6c757d', [
                ['Modality','Modality','select',[$o('xray','X-ray'),$o('us','Ultrasound'),$o('ct','CT'),$o('mri','MRI')]],
                $txt('Region','Region'), $txt('Indication','Clinical indication'), $yn('Contrast','Contrast required'),
            ]],
            'audiology' => ['Audiology Assessment', 'fa-ear-deaf', '6610f2', [
                $sel('Otoscopy','Otoscopy'), $txt('Audiogram','Audiogram summary'), $sel('Tympanometry','Tympanometry'), $yn('HearingAid','Hearing aid fitted'),
            ]],
            'nutrition' => ['Nutrition Assessment', 'fa-apple-whole', '198754', [
                ['BMI','BMI','measurement','none','kg/m²',18.5,25,null,null], $txt('Diet','Dietary recall'),
                $txt('Anthropometry','Anthropometry'), $txt('Goals','Goals / plan'),
            ]],
            'phoniatrics' => ['Phoniatrics Assessment', 'fa-comment-medical', '6610f2', [
                $sel('Voice','Voice quality'), $sel('Laryngoscopy','Laryngoscopy'), $sel('Speech','Speech'), $sel('Swallowing','Swallowing'),
            ]],
            'physiotherapy' => ['Physiotherapy Assessment', 'fa-person-running', 'fd7e14', [
                $txt('Region','Region / injury'), $sel('ROM','Range of motion'),
                ['Strength','Muscle strength (MRC)','select',[$o('5','5/5'),$o('4','4/5',1),$o('3','3/5',2),$o('2','≤2/5',3)]],
                $sel('Pain','Pain on movement'), $txt('Goal','Functional goal'),
            ]],
            'osteopathy' => ['Osteopathy Assessment', 'fa-hands', 'fd7e14', [
                $sel('Posture','Posture / alignment'), $sel('Mobility','Joint mobility'), $sel('SoftTissue','Soft tissue'), $txt('Notes','Findings'),
            ]],
            'psychiatry' => ['Mental State Examination', 'fa-head-side-virus', '6f42c1', [
                $sel('Appearance','Appearance & behaviour'), $txt('Mood','Mood / affect'), $sel('Thought','Thought form & content'),
                $sel('Perception','Perception'), ['Risk','Suicide / self-harm risk','select',[$o('none','None'),$o('low','Low',1),$o('moderate','Moderate',2),$o('high','High',3,true)]],
                $sel('Cognition','Cognition & insight'),
            ]],
        ];

        // Default "General Consultation" body reused by the primary-care family.
        $generalBody = [
            $txt('Presentation','Chief complaint'), $sel('CVS','Cardiovascular'), $sel('Resp','Respiratory'),
            $sel('Abdo','Abdomen'), $sel('Neuro','Neurological screen'), $txt('Plan','Assessment & plan'),
        ];

        foreach ($sheets as $code => [$name, $icon, $colour, $items]) {
            $specialtyId = $specialties[$code] ?? null;
            if (! $specialtyId) continue;
            $items = $items ?? $generalBody;

            $existing = DB::table('clc_exam_templates')->whereNull('business_id')
                ->where('specialty_id', $specialtyId)->where('name', $name)->value('id');
            $row = [
                'name' => $name, 'specialty_id' => $specialtyId, 'kind' => 'specialist',
                'species_scope' => 'all', 'display_label' => $name, 'icon' => $icon, 'colour' => $colour,
                'description' => 'Default ' . $name . ' sheet.', 'is_active' => true, 'sort_order' => 0,
                'business_id' => null, 'updated_at' => $now,
            ];
            if ($existing) {
                DB::table('clc_exam_template_items')->where('template_id', $existing)->delete();
                DB::table('clc_exam_templates')->where('id', $existing)->update($row);
                $tplId = $existing;
            } else {
                $tplId = DB::table('clc_exam_templates')->insertGetId($row + ['created_at' => $now]);
            }

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

    public function down()
    {
        if (! Schema::hasTable('clc_exam_templates')) return;
        // Remove only the global specialist sheets this migration owns (those tied
        // to a specialty_id and not the derma/dental plugin sheets).
        $pluginNames = ['Dermatological Examination','Skin Cancer Screening (ABCDE)','Acne Severity Assessment','Dental Examination'];
        $ids = DB::table('clc_exam_templates')->whereNull('business_id')
            ->whereNotNull('specialty_id')->whereNotIn('name', $pluginNames)->pluck('id');
        DB::table('clc_exam_template_items')->whereIn('template_id', $ids)->delete();
        DB::table('clc_exam_templates')->whereIn('id', $ids)->delete();
    }
}
