<?php

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

/**
 * SIFA P3-T6 — unified clinical orders (spec §7 orders). A thin order header
 * that fronts and routes to the existing imaging (clc_imaging_requests) and lab
 * (lab_worklist) flows, plus internal procedure / consultation order types.
 * Business-scoped; the appointment is the encounter (decision D3).
 */
class CreateClcOrdersTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_orders')) return;

        Schema::create('clc_orders', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id');
            $table->string('order_no', 30)->unique();
            $table->unsignedInteger('appointment_id')->nullable();
            $table->unsignedInteger('patient_id');
            $table->unsignedInteger('ordering_doctor_id')->nullable();
            $table->enum('order_type', ['lab', 'imaging', 'procedure', 'consultation']);
            $table->enum('priority', ['routine', 'urgent', 'stat'])->default('routine');
            $table->text('clinical_indication')->nullable();
            $table->enum('status', ['ordered', 'collected', 'in_progress', 'resulted', 'verified', 'cancelled'])->default('ordered');
            $table->unsignedInteger('verified_by')->nullable();     // users.id
            $table->timestamp('verified_at')->nullable();
            $table->timestamps();

            $table->foreign('business_id')->references('id')->on('business')->onDelete('cascade');
            $table->foreign('appointment_id')->references('id')->on('clc_appointments')->onDelete('set null');
            $table->foreign('patient_id')->references('id')->on('clc_patients')->onDelete('cascade');
            $table->index(['business_id', 'patient_id']);
            $table->index(['business_id', 'appointment_id']);
            $table->index(['business_id', 'order_type', 'status']);
        });
    }

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