<?php

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

/**
 * P5-T2 dental deep-dive — treatment-plan builder rows. A dentist assembles a
 * proposed plan (one row per procedure) with urgency + estimated cost, prints a
 * patient-friendly copy, and can convert the plan into a shared ClinicCore
 * treatment plan (clc_patient_treatment_plans + sessions). The converted plan's
 * id is written back to clc_treatment_plan_id so the link is one-way traceable.
 */
class CreateDentalTreatmentPlanItemsTable extends Migration
{
    public function up()
    {
        if (! Schema::hasTable('clc_patients')) {
            return; // requires ClinicCore
        }

        if (! Schema::hasTable('dental_treatment_plan_items')) {
            Schema::create('dental_treatment_plan_items', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id');
                $table->unsignedInteger('patient_id');            // clc_patients.id
                $table->string('plan_name', 150)->default('Treatment plan');
                $table->unsignedTinyInteger('tooth_number')->nullable(); // universal 1-32
                $table->string('cdt_code', 20)->nullable();
                $table->string('procedure_name', 191);
                $table->enum('urgency', ['elective', 'soon', 'urgent', 'emergency'])->default('elective');
                $table->decimal('estimated_cost', 22, 4)->nullable();
                $table->enum('status', ['planned', 'scheduled', 'completed', 'cancelled'])->default('planned');
                $table->unsignedInteger('sort_order')->default(0);
                $table->unsignedInteger('clc_treatment_plan_id')->nullable(); // set on conversion
                $table->unsignedInteger('created_by')->nullable();
                $table->timestamps();

                $table->index(['business_id', 'patient_id', 'plan_name'], 'dental_tpi_biz_pat_plan_idx');
                $table->foreign('patient_id')->references('id')->on('clc_patients')->onDelete('cascade');
            });
        }
    }

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