<?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
    {
        if (Schema::hasTable('income_histories')) {
            Schema::table('income_histories', function (Blueprint $table) {
                if (!Schema::hasColumn('income_histories', 'previous_balance')) {
                    $table->decimal('previous_balance', 16, 2)->nullable()->after('amount');
                }

                if (!Schema::hasColumn('income_histories', 'new_balance')) {
                    $table->decimal('new_balance', 16, 2)->nullable()->after('previous_balance');
                }
            });
        }

        if (Schema::hasTable('balance_logs')) {
            Schema::table('balance_logs', function (Blueprint $table) {
                if (!Schema::hasColumn('balance_logs', 'previous_balance')) {
                    $table->decimal('previous_balance', 16, 2)->nullable()->after('amount');
                }

                if (!Schema::hasColumn('balance_logs', 'new_balance')) {
                    $table->decimal('new_balance', 16, 2)->nullable()->after('previous_balance');
                }
            });
        }
    }

    public function down(): void
    {
        if (Schema::hasTable('income_histories')) {
            Schema::table('income_histories', function (Blueprint $table) {
                $columns = [];

                if (Schema::hasColumn('income_histories', 'previous_balance')) {
                    $columns[] = 'previous_balance';
                }

                if (Schema::hasColumn('income_histories', 'new_balance')) {
                    $columns[] = 'new_balance';
                }

                if ($columns !== []) {
                    $table->dropColumn($columns);
                }
            });
        }

        if (Schema::hasTable('balance_logs')) {
            Schema::table('balance_logs', function (Blueprint $table) {
                $columns = [];

                if (Schema::hasColumn('balance_logs', 'previous_balance')) {
                    $columns[] = 'previous_balance';
                }

                if (Schema::hasColumn('balance_logs', 'new_balance')) {
                    $columns[] = 'new_balance';
                }

                if ($columns !== []) {
                    $table->dropColumn($columns);
                }
            });
        }
    }
};
