<?php

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

/**
 * SIFA P4-T6 — referrals (medical_core §referrals).
 *
 * Internal (to another doctor in this clinic), external outgoing (to an outside
 * facility/provider) and external incoming (received from an outside provider).
 * The referral letter print view pulls the clinical summary, active meds and
 * allergies at render time — those live in their own tables, not duplicated here.
 */
class CreateClcReferralsTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_referrals')) return;

        Schema::create('clc_referrals', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id')->index();
            $table->string('referral_no', 40)->index();            // REF-{biz}-{seq}
            $table->unsignedInteger('patient_id')->index();
            $table->unsignedInteger('appointment_id')->nullable()->index();

            $table->enum('direction', ['internal', 'external_outgoing', 'external_incoming'])
                  ->default('internal')->index();
            $table->enum('urgency', ['routine', 'urgent', 'emergency'])->default('routine');

            // Referring side.
            $table->unsignedInteger('from_doctor_id')->nullable();     // internal referrer
            $table->string('from_provider_name', 191)->nullable();     // external incoming source

            // Referred-to side.
            $table->unsignedInteger('to_doctor_id')->nullable();       // internal target doctor
            $table->string('to_facility_name', 191)->nullable();       // external outgoing facility
            $table->string('to_provider_name', 191)->nullable();       // external outgoing provider

            $table->text('reason');
            $table->text('clinical_summary')->nullable();
            $table->json('requested_services')->nullable();

            $table->enum('status', [
                'draft', 'sent', 'received', 'accepted',
                'in_progress', 'completed', 'rejected', 'cancelled',
            ])->default('draft')->index();
            $table->text('response_notes')->nullable();

            $table->unsignedInteger('created_by')->nullable();
            $table->timestamps();
        });
    }

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