<?php

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

/**
 * SIFA P3-T5 — prescriptions upgrade (spec §7 prescriptions). Additive + nullable
 * columns on the existing clc_prescriptions header so legacy Rx keep working:
 *
 *   rx_type    - outpatient / discharge (spec type enum; inpatient is Phase 6)
 *   signed_at  - when the prescriber signed / finalised the Rx
 *
 * Guarded with Schema::hasColumn so the migration is safe to re-run.
 */
class AddRxUpgradeColumnsToClcPrescriptions extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('clc_prescriptions')) return;

        Schema::table('clc_prescriptions', function (Blueprint $table) {
            if (!Schema::hasColumn('clc_prescriptions', 'rx_type')) {
                $table->enum('rx_type', ['outpatient', 'discharge'])->nullable()->after('status');
            }
            if (!Schema::hasColumn('clc_prescriptions', 'signed_at')) {
                $table->timestamp('signed_at')->nullable()->after('rx_type');
            }
        });
    }

    public function down()
    {
        foreach (['rx_type', 'signed_at'] as $col) {
            if (Schema::hasColumn('clc_prescriptions', $col)) {
                Schema::table('clc_prescriptions', function (Blueprint $table) use ($col) {
                    $table->dropColumn($col);
                });
            }
        }
    }
}
