<?php

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

/**
 * SIFA P3-T5 — prescription-item upgrade (spec §7 prescriptions.items[]):
 * refills, PRN and substitution flags. Additive with sensible defaults so
 * existing dispense tracking and print views keep working unchanged.
 *
 *   refills_allowed        - how many refills the prescriber authorised
 *   refills_used           - how many have been consumed (refill action)
 *   prn                    - "pro re nata" — take as needed
 *   prn_reason             - the indication for a PRN item
 *   substitutions_allowed  - may the pharmacist substitute a generic/brand
 */
class AddRxUpgradeColumnsToClcPrescriptionItems extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('clc_prescription_items')) return;

        Schema::table('clc_prescription_items', function (Blueprint $table) {
            if (!Schema::hasColumn('clc_prescription_items', 'refills_allowed')) {
                $table->unsignedSmallInteger('refills_allowed')->default(0)->after('quantity');
            }
            if (!Schema::hasColumn('clc_prescription_items', 'refills_used')) {
                $table->unsignedSmallInteger('refills_used')->default(0)->after('refills_allowed');
            }
            if (!Schema::hasColumn('clc_prescription_items', 'prn')) {
                $table->boolean('prn')->default(false)->after('refills_used');
            }
            if (!Schema::hasColumn('clc_prescription_items', 'prn_reason')) {
                $table->string('prn_reason', 255)->nullable()->after('prn');
            }
            if (!Schema::hasColumn('clc_prescription_items', 'substitutions_allowed')) {
                $table->boolean('substitutions_allowed')->default(true)->after('prn_reason');
            }
        });
    }

    public function down()
    {
        foreach (['refills_allowed', 'refills_used', 'prn', 'prn_reason', 'substitutions_allowed'] as $col) {
            if (Schema::hasColumn('clc_prescription_items', $col)) {
                Schema::table('clc_prescription_items', function (Blueprint $table) use ($col) {
                    $table->dropColumn($col);
                });
            }
        }
    }
}
