<?php

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

/**
 * Item 1.4 - seed the system-default "Orthopedic Exam" specialist template.
 *
 * Joint-by-joint structured exam with flexion/extension/pain/instability
 * per side, plus standard ortho special tests (drawer, ortolani,
 * thigh-circumference). Opened on demand from the "+ Add specialist exam"
 * picker on the appointment.
 */
class SeedOrthopedicExamTemplate extends Migration
{
    public function up()
    {
        $now = now();
        $exists = DB::table('vc_exam_templates')
            ->whereNull('business_id')
            ->where('kind', 'specialist')
            ->where('name', 'Orthopedic Exam')
            ->value('id');
        if ($exists) return;

        $tplId = DB::table('vc_exam_templates')->insertGetId([
            'business_id'   => null,
            'name'          => 'Orthopedic Exam',
            'kind'          => 'specialist',
            'species_scope' => 'all',
            'display_label' => 'Orthopedic Exam',
            'icon'          => 'fa-bone',
            'colour'        => 'c0392b',
            'description'   => 'Joint-by-joint orthopedic assessment with special tests.',
            'is_active'     => true,
            'sort_order'    => 10,
            'created_at'    => $now,
            'updated_at'    => $now,
        ]);

        $opt = function ($value, $label, $severity = 0, $critical = false) {
            return ['value' => $value, 'label' => $label, 'severity' => $severity, 'is_critical' => $critical];
        };

        // Reusable per-joint option sets.
        $normalAbnormal = [
            $opt('normal',   'Normal',         0, false),
            $opt('reduced',  'Reduced',        1, false),
            $opt('painful',  'Painful',        2, false),
            $opt('severe',   'Severely abnormal', 3, true),
            $opt('ne',       'Not examined',   0, false),
        ];

        $painScale = [
            $opt('0', '0 - None',         0, false),
            $opt('1', '1 - Mild',         1, false),
            $opt('2', '2 - Moderate',     2, false),
            $opt('3', '3 - Severe',       3, true),
        ];

        $instability = [
            $opt('stable',          'Stable',                       0, false),
            $opt('mild_laxity',     'Mild laxity',                  1, false),
            $opt('moderate_laxity', 'Moderate laxity',              2, false),
            $opt('gross_laxity',    'Gross / pathological laxity',  3, true),
        ];

        $items = [];
        $sort = 0;

        // ── Gait + posture (no laterality) ──────────────────────────
        $items[] = ['Gait & Posture','Stance','select','none',[
            $opt('square',         'Square / symmetric',          0, false),
            $opt('shifted_weight', 'Shifted weight off limb',     2, false),
            $opt('non_weight',     'Non-weight-bearing on limb',  3, true),
        ], null,null,null,null,null, $sort++];
        $items[] = ['Gait & Posture','Gait at walk','select','none',[
            $opt('sound',   'Sound',                        0, false),
            $opt('stiff',   'Stiff / shortened stride',     1, false),
            $opt('mild',    'Mild lameness',                2, false),
            $opt('marked',  'Marked lameness',              3, false),
            $opt('nwb',     'Non-weight-bearing',           3, true),
        ], null,null,null,null,null, $sort++];
        $items[] = ['Gait & Posture','Lameness grade (0-5)','grade','none',[
            $opt('0','0 - Sound',                                0,false),
            $opt('1','1 - Visible only at trot',                 1,false),
            $opt('2','2 - Visible at walk, intermittent',        2,false),
            $opt('3','3 - Visible at walk, consistent',          2,false),
            $opt('4','4 - Severe, partial weight bearing',       3,false),
            $opt('5','5 - Non-weight-bearing',                   3,true),
        ], null,null,null,null,null, $sort++];

        // ── Per-joint blocks (each is examined left / right) ────────
        $joints = [
            'Shoulder', 'Elbow', 'Carpus',
            'Hip', 'Stifle', 'Hock',
        ];
        foreach ($joints as $joint) {
            $items[] = [$joint,'Flexion',     'select','lr', $normalAbnormal, null,null,null,null,null, $sort++];
            $items[] = [$joint,'Extension',   'select','lr', $normalAbnormal, null,null,null,null,null, $sort++];
            $items[] = [$joint,'Pain on manipulation','select','lr', $painScale, null,null,null,null,null, $sort++];
            $items[] = [$joint,'Instability', 'select','lr', $instability, null,null,null,null,null, $sort++];
            $items[] = [$joint,'Crepitus',    'yes_no','lr', [
                $opt('no',  'No',  0, false),
                $opt('yes', 'Yes', 2, false),
            ], null,null,null,null,null, $sort++];
            $items[] = [$joint,'Effusion',    'yes_no','lr', [
                $opt('no',  'No',  0, false),
                $opt('yes', 'Yes', 2, false),
            ], null,null,null,null,null, $sort++];
        }

        // ── Special tests ────────────────────────────────────────────
        $items[] = ['Special Tests','Cranial drawer (stifle)','select','lr',[
            $opt('negative', 'Negative',          0, false),
            $opt('partial',  'Partial (mild)',    2, false),
            $opt('positive', 'Positive',          3, true),
        ], null,null,null,null,null, $sort++];
        $items[] = ['Special Tests','Tibial thrust (stifle)','select','lr',[
            $opt('negative', 'Negative', 0, false),
            $opt('positive', 'Positive', 3, true),
        ], null,null,null,null,null, $sort++];
        $items[] = ['Special Tests','Ortolani sign (hip)','select','lr',[
            $opt('negative', 'Negative',                 0, false),
            $opt('positive', 'Positive (subluxation)',   3, true),
        ], null,null,null,null,null, $sort++];
        $items[] = ['Special Tests','Patellar luxation grade','grade','lr',[
            $opt('0','0 - Stable',                           0,false),
            $opt('1','1 - Manual luxation, spontaneous reduction',  1,false),
            $opt('2','2 - Spontaneous luxation, manual reduction',  2,false),
            $opt('3','3 - Permanently luxated, manually reducible', 3,false),
            $opt('4','4 - Permanently luxated, not reducible',      3,true),
        ], null,null,null,null,null, $sort++];

        // ── Measurements ────────────────────────────────────────────
        $items[] = ['Measurements','Thigh circumference (cm)','measurement','lr',
            null, 'cm', null, null, null, null, $sort++];
        $items[] = ['Measurements','Range of motion (degrees)','measurement','lr',
            null, 'deg', null, null, null, null, $sort++];

        // ── Imaging / notes ─────────────────────────────────────────
        $items[] = ['Notes','Radiographs reviewed','select','none',[
            $opt('not_done',    'Not done',          0, false),
            $opt('normal',      'Normal',            0, false),
            $opt('abnormal',    'Abnormal',          2, false),
            $opt('fracture',    'Fracture',          3, true),
        ], null,null,null,null,null, $sort++];
        $items[] = ['Notes','Findings summary','text','none', null, null,null,null,null,null, $sort++];

        foreach ($items as $row) {
            DB::table('vc_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'     => $row[10] ?? 0,
                'created_at'     => $now,
                'updated_at'     => $now,
            ]);
        }
    }

    public function down()
    {
        $tplId = DB::table('vc_exam_templates')
            ->whereNull('business_id')
            ->where('kind', 'specialist')
            ->where('name', 'Orthopedic Exam')
            ->value('id');
        if (!$tplId) return;
        DB::table('vc_exam_template_items')->where('template_id', $tplId)->delete();
        DB::table('vc_exam_templates')->where('id', $tplId)->delete();
    }
}
