<?php

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

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('transactions', function (Blueprint $table) {
            $table->foreignId('loan_id')
                ->nullable()
                ->after('transfer_id')
                ->constrained()
                ->cascadeOnDelete();

            $table->index('loan_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('transactions', function (Blueprint $table) {
            // Drop index FIRST
            $table->dropIndex('loan_id');

            // Drop foreign keys individually
            $table->dropForeign('transactions_loan_id_foreign');

            // Drop columns
            $table->dropColumn('loan_id');
        });
    }
};
