<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Add last_login_ip to users
        if (!Schema::hasColumn('users', 'last_login_ip')) {
            Schema::table('users', function (Blueprint $table) {
                $table->string('last_login_ip', 45)->nullable()->after('last_login_at');
            });
        }

        // Add payment details to loan_repayments
        if (Schema::hasTable('loan_repayments')) {
            Schema::table('loan_repayments', function (Blueprint $table) {
                if (!Schema::hasColumn('loan_repayments', 'payment_method')) {
                    $table->string('payment_method', 50)->nullable()->after('status');
                }
                if (!Schema::hasColumn('loan_repayments', 'reference_number')) {
                    $table->string('reference_number', 255)->nullable()->after('payment_method');
                }
                if (!Schema::hasColumn('loan_repayments', 'notes')) {
                    $table->text('notes')->nullable()->after('reference_number');
                }
            });
        }
    }

    public function down(): void
    {
        if (Schema::hasColumn('users', 'last_login_ip')) {
            Schema::table('users', function (Blueprint $table) {
                $table->dropColumn('last_login_ip');
            });
        }

        if (Schema::hasTable('loan_repayments')) {
            Schema::table('loan_repayments', function (Blueprint $table) {
                $table->dropColumn(array_filter(['payment_method', 'reference_number', 'notes'], fn($col) => Schema::hasColumn('loan_repayments', $col)));
            });
        }
    }
};
