<?php

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

/**
 * medward_mar_entries — the Medication Administration Record (SIFA P6-T2 MAR).
 * MarService generates `scheduled` rows from the active inpatient ClinicCore
 * prescription items (prescription_item_id → clc_prescription_items.id) by parsing
 * the frequency (OD/BD/TID/QID) into per-day slots, then nurses administer / hold
 * each row. witness_user_id records the second signer required for controlled
 * meds (clc_medicines.controlled_schedule set). business_id-scoped.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('medward_mar_entries')) {
            return;
        }

        Schema::create('medward_mar_entries', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedBigInteger('admission_id');
            $t->unsignedInteger('prescription_item_id')->nullable(); // clc_prescription_items.id (source)
            $t->string('medicine_name', 191);
            $t->timestamp('scheduled_at')->nullable();
            $t->timestamp('administered_at')->nullable();
            $t->unsignedInteger('administered_by')->nullable();      // users.id
            $t->enum('status', ['scheduled', 'given', 'held', 'refused', 'missed'])->default('scheduled');
            $t->string('dose', 100)->nullable();
            $t->string('route', 60)->nullable();
            $t->string('reason_if_held', 255)->nullable();
            $t->unsignedInteger('witness_user_id')->nullable();      // controlled-med second signer
            $t->timestamps();

            $t->index(['business_id', 'admission_id', 'scheduled_at'], 'medward_mar_biz_adm_sched_idx');
            $t->index(['admission_id', 'status'], 'medward_mar_adm_status_idx');
            $t->index('prescription_item_id', 'medward_mar_rxitem_idx');
        });
    }

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