<?php

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

class CreateClcExamNotDoneReasonsTable extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('clc_exam_not_done_reasons')) {
            Schema::create('clc_exam_not_done_reasons', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->nullable()->index(); // null = system default
                $table->string('name', 150);
                $table->unsignedSmallInteger('sort_order')->default(0);
                $table->enum('status', ['active', 'inactive'])->default('active');
                $table->timestamps();
            });
        }

        // Seed default reasons (only on fresh install — uses firstOrCreate by name+null business)
        $defaults = [
            ['Owner refused',         10],
            ['Pet uncooperative',     20],
            ['Equipment unavailable', 30],
            ['Cost concern',          40],
            ['Rescheduled',           50],
            ['Already done elsewhere', 60],
            ['Not clinically needed', 70],
            ['Other',                 999],
        ];
        foreach ($defaults as [$name, $sort]) {
            \DB::table('clc_exam_not_done_reasons')->updateOrInsert(
                ['business_id' => null, 'name' => $name],
                ['sort_order' => $sort, 'status' => 'active', 'created_at' => now(), 'updated_at' => now()]
            );
        }
    }

    public function down()
    {
        Schema::dropIfExists('clc_exam_not_done_reasons');
    }
}
