<?php

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

/**
 * Seed Dental's exam sheet into ClinicCore's shared exam engine
 * (clc_exam_templates), tagged with the dental specialty so it only surfaces
 * on appointments booked under Dental. Plugin half of per-specialty exam
 * sheets; the per-tooth chart itself lives in dental_tooth_findings.
 */
class SeedDentalExamTemplates extends Migration
{
    public function up()
    {
        if (! Schema::hasTable('clc_exam_templates')) return; // requires ClinicCore
        $hasSpecialtyCol = Schema::hasColumn('clc_exam_templates', 'specialty_id');
        $specialtyId = $hasSpecialtyCol
            ? DB::table('clc_specialties')->whereNull('business_id')->where('code', 'dental')->value('id')
            : null;
        $now = now();

        $opt = fn ($value, $label, $severity = 0, $critical = false) =>
            ['value' => $value, 'label' => $label, 'severity' => $severity, 'is_critical' => $critical];

        $name = 'Dental Examination';
        $q = DB::table('clc_exam_templates')->whereNull('business_id')->where('name', $name);
        if ($hasSpecialtyCol) $q->where('specialty_id', $specialtyId);
        $existing = $q->value('id');

        $tplRow = [
            'name' => $name, 'kind' => 'specialist', 'species_scope' => 'all',
            'display_label' => 'Dental Exam', 'icon' => 'fa-tooth', 'colour' => '17a2b8',
            'description' => 'Oral / dental examination and charting summary.',
            'is_active' => true, 'sort_order' => 0,
            'business_id' => null, 'updated_at' => $now,
        ];
        if ($hasSpecialtyCol) $tplRow['specialty_id'] = $specialtyId;

        if ($existing) {
            DB::table('clc_exam_template_items')->where('template_id', $existing)->delete();
            DB::table('clc_exam_templates')->where('id', $existing)->update($tplRow);
            $tplId = $existing;
        } else {
            $tplId = DB::table('clc_exam_templates')->insertGetId($tplRow + ['created_at' => $now]);
        }

        $items = [
            ['Soft Tissue', 'Oral mucosa', 'select', [$opt('normal', 'Normal'), $opt('lesion', 'Lesion present', 2), $opt('ulcer', 'Ulceration', 3, true)]],
            ['Gingiva', 'Gingival condition', 'select', [
                $opt('healthy', 'Healthy'), $opt('gingivitis', 'Gingivitis', 1),
                $opt('periodontitis', 'Periodontitis', 2), $opt('recession', 'Recession', 2),
            ]],
            ['Gingiva', 'Bleeding on probing', 'select', [$opt('none', 'None'), $opt('localized', 'Localized', 1), $opt('generalized', 'Generalized', 2)]],
            ['Hygiene', 'Oral hygiene', 'select', [$opt('good', 'Good'), $opt('fair', 'Fair', 1), $opt('poor', 'Poor', 2)]],
            ['Hygiene', 'Calculus / plaque', 'select', [$opt('none', 'None'), $opt('light', 'Light', 1), $opt('moderate', 'Moderate', 2), $opt('heavy', 'Heavy', 2)]],
            ['Caries', 'Caries risk', 'select', [$opt('low', 'Low'), $opt('moderate', 'Moderate', 1), $opt('high', 'High', 2)]],
            ['Occlusion', 'Occlusion class', 'select', [$opt('i', 'Class I'), $opt('ii', 'Class II', 1), $opt('iii', 'Class III', 1)]],
            ['Occlusion', 'TMJ / bite issues', 'select', [$opt('none', 'None'), $opt('clicking', 'Clicking', 1), $opt('pain', 'Pain / dysfunction', 2)]],
            ['Findings', 'Notes', 'text', null],
        ];
        $sort = 0;
        foreach ($items as $r) {
            DB::table('clc_exam_template_items')->insert([
                'template_id'    => $tplId,
                'region'         => $r[0],
                'item_label'     => $r[1],
                'response_type'  => $r[2],
                'lateralisation' => 'none',
                'options_json'   => !empty($r[3]) ? json_encode($r[3]) : null,
                'is_required'    => false,
                'sort_order'     => $sort++,
                'created_at'     => $now,
                'updated_at'     => $now,
            ]);
        }
    }

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