<?php

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

/**
 * Wire prescription dispensing to ERP stock.
 *
 * Each prescription line can now record:
 *   - which purchase_lines.id (= ERP lot/batch row) it drew from (FEFO),
 *   - who dispensed it, when,
 *   - the exact qty given (separate from the original prescribed quantity).
 *
 * Stock is decremented in ERP variation_location_details via
 * ProductUtil::decreaseProductQuantity — see ClcMedicineDispenseService.
 */
class AddDispenseColumnsToClcPrescriptionItems 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', 'purchase_line_id')) {
                $table->unsignedInteger('purchase_line_id')->nullable()->after('quantity');
            }
            if (!Schema::hasColumn('clc_prescription_items', 'dispensed_qty')) {
                $table->decimal('dispensed_qty', 22, 4)->nullable()->after('purchase_line_id');
            }
            if (!Schema::hasColumn('clc_prescription_items', 'dispensed_at')) {
                $table->timestamp('dispensed_at')->nullable()->after('dispensed_qty');
            }
            if (!Schema::hasColumn('clc_prescription_items', 'dispensed_by')) {
                $table->unsignedInteger('dispensed_by')->nullable()->after('dispensed_at');
            }
            if (!Schema::hasColumn('clc_prescription_items', 'location_id')) {
                $table->unsignedInteger('location_id')->nullable()->after('dispensed_by');
            }
        });
    }

    public function down()
    {
        if (!Schema::hasTable('clc_prescription_items')) return;

        Schema::table('clc_prescription_items', function (Blueprint $table) {
            foreach (['purchase_line_id', 'dispensed_qty', 'dispensed_at', 'dispensed_by', 'location_id'] as $col) {
                if (Schema::hasColumn('clc_prescription_items', $col)) {
                    $table->dropColumn($col);
                }
            }
        });
    }
}
