<?php

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

/**
 * SIFA P3-T1 — current medications the patient is taking OUTSIDE our own Rx
 * (spec §7 patient > clinical_baseline > current_medications). This is the
 * "home med list" for reconciliation; prescriptions we issue live in
 * clc_prescriptions and are unaffected.
 */
class CreateClcPatientMedicationsTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_patient_medications')) {
            return;
        }

        Schema::create('clc_patient_medications', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id');
            $table->unsignedInteger('patient_id');
            $table->string('medication_name');
            $table->string('dosage')->nullable();
            $table->string('frequency')->nullable();
            $table->string('route')->nullable();
            $table->string('prescriber')->nullable();     // free text (external prescriber)
            $table->date('start_date')->nullable();
            $table->date('end_date')->nullable();
            $table->boolean('ongoing')->default(true);
            $table->text('notes')->nullable();
            $table->unsignedInteger('created_by')->nullable();  // users.id
            $table->timestamps();

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

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