<?php

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

/**
 * Seed ClinicCore's specialty-neutral default exam sheet: a structured
 * General Examination (systems review) that every specialty can use out of
 * the box. Specialty-specific sheets (dermatology skin exam, dental charting,
 * etc.) are seeded by their own plugin modules via the SpecialtyDriverRegistry
 * — they must NOT live in the shared core.
 *
 * Also removes any veterinary templates inherited from the VetClinic lineage
 * (Standard General Exam / Orthopedic Exam) so a fresh core starts clean.
 *
 * Uses the existing clc_exam_templates / clc_exam_template_items engine
 * (region -> item -> options_json{value,label,severity,is_critical}).
 */
class SeedClinicExamTemplates extends Migration
{
    public function up()
    {
        if (! Schema::hasTable('clc_exam_templates')) return;
        $now = now();

        // Remove inherited veterinary + dermatology-specific system templates.
        $stale = DB::table('clc_exam_templates')
            ->whereNull('business_id')
            ->whereIn('name', [
                'Standard General Exam', 'Orthopedic Exam',
                'Clinictological Examination', 'Dermatological Examination',
                'Skin Cancer Screening (ABCDE)', 'Acne Severity Assessment',
            ])
            ->pluck('id');
        if ($stale->isNotEmpty()) {
            DB::table('clc_exam_template_items')->whereIn('template_id', $stale)->delete();
            DB::table('clc_exam_templates')->whereIn('id', $stale)->delete();
        }

        $normalAbnormal = fn () => [
            ['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],
        ];

        $seed = function (array $tpl, array $items) use ($now) {
            $exists = DB::table('clc_exam_templates')->whereNull('business_id')
                ->where('name', $tpl['name'])->value('id');
            if ($exists) {
                DB::table('clc_exam_template_items')->where('template_id', $exists)->delete();
                $tplId = $exists;
                DB::table('clc_exam_templates')->where('id', $exists)->update($tpl + ['updated_at' => $now]);
            } else {
                $tplId = DB::table('clc_exam_templates')->insertGetId($tpl + [
                    'business_id' => null, 'created_at' => $now, 'updated_at' => $now,
                ]);
            }
            $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] ?? 'none',
                    'options_json'   => !empty($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,
                ]);
            }
        };

        // ─────────────────────────────────────────────────────────────
        // GENERAL EXAMINATION (always-on, specialty-neutral systems review)
        // ─────────────────────────────────────────────────────────────
        $seed([
            'name' => 'General Examination', 'kind' => 'general', 'species_scope' => 'all',
            'display_label' => 'General Exam', 'icon' => 'fa-stethoscope', 'colour' => '0d6efd',
            'description' => 'Always-on structured general systems review.',
            'is_active' => true, 'sort_order' => 0,
        ], [
            ['General','General appearance','select','none',$normalAbnormal()],
            ['General','Level of consciousness','select','none',[
                ['value'=>'alert','label'=>'Alert','severity'=>0,'is_critical'=>false],
                ['value'=>'drowsy','label'=>'Drowsy','severity'=>2,'is_critical'=>false],
                ['value'=>'confused','label'=>'Confused','severity'=>2,'is_critical'=>false],
                ['value'=>'unresponsive','label'=>'Unresponsive','severity'=>3,'is_critical'=>true],
            ]],
            ['HEENT','Head, eyes, ears, nose & throat','select','none',$normalAbnormal()],
            ['Cardiovascular','Heart sounds / rhythm','select','none',$normalAbnormal()],
            ['Respiratory','Breath sounds','select','none',$normalAbnormal()],
            ['Abdomen','Abdominal examination','select','none',$normalAbnormal()],
            ['Musculoskeletal','Musculoskeletal system','select','none',$normalAbnormal()],
            ['Skin','Skin & integument','select','none',$normalAbnormal()],
            ['Neurological','Neurological screen','select','none',$normalAbnormal()],
            ['Notes','Examination notes','text','none',null],
        ]);
    }

    public function down()
    {
        if (! Schema::hasTable('clc_exam_templates')) return;
        $ids = DB::table('clc_exam_templates')->whereNull('business_id')
            ->where('name', 'General Examination')
            ->pluck('id');
        DB::table('clc_exam_template_items')->whereIn('template_id', $ids)->delete();
        DB::table('clc_exam_templates')->whereIn('id', $ids)->delete();
    }
}
