<?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
    {
        Schema::table('payments', function (Blueprint $table) {
            if (!Schema::hasColumn('payments', 'payment_method')) {
                $table->string('payment_method')->nullable()->after('paid_at');
            }

            if (!Schema::hasColumn('payments', 'reference_number')) {
                $table->string('reference_number')->nullable()->after('payment_method');
            }

            if (!Schema::hasColumn('payments', 'remarks')) {
                $table->text('remarks')->nullable()->after('reference_number');
            }

            if (!Schema::hasColumn('payments', 'is_manual')) {
                $table->boolean('is_manual')->default(false)->after('remarks');
            }

            if (!Schema::hasColumn('payments', 'recorded_by')) {
                $table->foreignId('recorded_by')
                    ->nullable()
                    ->after('is_manual')
                    ->constrained('users')
                    ->nullOnDelete();
            }

            if (!Schema::hasColumn('payments', 'loan_id')) {
                $table->foreignId('loan_id')
                    ->nullable()
                    ->after('recorded_by')
                    ->constrained('loans')
                    ->nullOnDelete();
            }

            if (!Schema::hasColumn('payments', 'installment_id')) {
                $table->foreignId('installment_id')
                    ->nullable()
                    ->after('loan_id')
                    ->constrained('loan_installments')
                    ->nullOnDelete();
            }
        });
    }

    public function down(): void
    {
        Schema::table('payments', function (Blueprint $table) {
            if (Schema::hasColumn('payments', 'installment_id')) {
                $table->dropForeign(['installment_id']);
                $table->dropColumn('installment_id');
            }

            if (Schema::hasColumn('payments', 'loan_id')) {
                $table->dropForeign(['loan_id']);
                $table->dropColumn('loan_id');
            }

            if (Schema::hasColumn('payments', 'recorded_by')) {
                $table->dropForeign(['recorded_by']);
                $table->dropColumn('recorded_by');
            }

            foreach ([
                'is_manual',
                'remarks',
                'reference_number',
                'payment_method',
            ] as $column) {
                if (Schema::hasColumn('payments', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
};