<?php

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

/**
 * Item 1.4 Phases B-D — adds Neurological as a body-system option so it
 * appears on the appointment Objective panel's body-systems toggle.
 * The JS finding catalogue (in show.blade.php) already includes a deep
 * neurological set; this just ensures the SYSTEM ROW exists so the
 * checklist can be reached.
 *
 * Skipped if a "Neurological" or "Nervous System" row already exists
 * for the business (system or business-scoped). business_id NULL = the
 * default available to every clinic.
 */
class ClcSeedNeurologicalBodySystem extends Migration
{
    public function up()
    {
        if (!\Schema::hasTable('clc_soap_options')) return;

        $existing = DB::table('clc_soap_options')
            ->where('section', 'body_system')
            ->where(function ($q) {
                $q->whereRaw('LOWER(label) LIKE ?', ['neurolog%'])
                  ->orWhereRaw('LOWER(label) LIKE ?', ['%nervous system%']);
            })
            ->whereNull('business_id')
            ->exists();
        if ($existing) return;

        $now = now();
        $maxOrder = (int) DB::table('clc_soap_options')
            ->where('section', 'body_system')
            ->max('sort_order');

        DB::table('clc_soap_options')->insert([
            'business_id' => null,
            'section'     => 'body_system',
            'species'     => 'all',
            'label'       => 'Neurological',
            'group_name'  => 'Nervous System',
            'group_icon'  => 'fa-brain',
            'group_color' => '#7c3aed',
            'group_bg'    => '#f5f3ff',
            'status'      => 'active',
            'sort_order'  => $maxOrder + 1,
            'created_at'  => $now,
            'updated_at'  => $now,
        ]);
    }

    public function down()
    {
        if (!\Schema::hasTable('clc_soap_options')) return;
        DB::table('clc_soap_options')
            ->where('section', 'body_system')
            ->whereNull('business_id')
            ->where('label', 'Neurological')
            ->delete();
    }
}
