<?php

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

/**
 * P5-T2 dental deep-dive — dental procedures log. A chronological record of
 * clinical procedures performed on a ClinicCore patient (optionally tied to a
 * clc appointment). procedure_name is deliberately a plain string so that,
 * when named to match an ERP product, MedBilling's ChargeCaptureService can
 * resolve it into a billable charge (note only — no coupling here).
 */
class CreateDentalProceduresTable extends Migration
{
    public function up()
    {
        if (! Schema::hasTable('clc_patients')) {
            return; // requires ClinicCore
        }

        if (! Schema::hasTable('dental_procedures')) {
            Schema::create('dental_procedures', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id');
                $table->unsignedInteger('patient_id');            // clc_patients.id
                $table->unsignedInteger('appointment_id')->nullable(); // clc_appointments.id
                $table->unsignedTinyInteger('tooth_number')->nullable(); // universal 1-32
                $table->string('surfaces', 20)->nullable();       // M,O,D,B,L combinations
                $table->string('cdt_code', 20)->nullable();
                $table->string('procedure_name', 191);
                $table->string('anesthesia_type', 100)->nullable();
                $table->json('materials')->nullable();            // [{name, lot, qty}]
                $table->text('complications')->nullable();
                $table->text('post_op_instructions')->nullable();
                $table->unsignedInteger('performed_by')->nullable(); // clc_doctors.id
                $table->timestamp('performed_at')->nullable();
                $table->timestamps();

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

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