<?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('invoices') && Schema::hasColumn('invoices', 'advance_payment')) {
            Schema::table('invoices', function (Blueprint $table) {
                if (! Schema::hasColumn('invoices', 'advance_payment_method')) {
                    $table->string('advance_payment_method', 50)->nullable()->after('advance_payment');
                }
                if (! Schema::hasColumn('invoices', 'advance_payment_date')) {
                    $table->date('advance_payment_date')->nullable()->after('advance_payment_method');
                }
                if (! Schema::hasColumn('invoices', 'advance_payment_reference')) {
                    $table->string('advance_payment_reference', 100)->nullable()->after('advance_payment_date');
                }
                if (! Schema::hasColumn('invoices', 'advance_payment_memo')) {
                    $table->text('advance_payment_memo')->nullable()->after('advance_payment_reference');
                }
            });
        }

        if (Schema::hasTable('quotations') && Schema::hasColumn('quotations', 'advance_payment')) {
            Schema::table('quotations', function (Blueprint $table) {
                if (! Schema::hasColumn('quotations', 'advance_payment_method')) {
                    $table->string('advance_payment_method', 50)->nullable()->after('advance_payment');
                }
                if (! Schema::hasColumn('quotations', 'advance_payment_date')) {
                    $table->date('advance_payment_date')->nullable()->after('advance_payment_method');
                }
                if (! Schema::hasColumn('quotations', 'advance_payment_reference')) {
                    $table->string('advance_payment_reference', 100)->nullable()->after('advance_payment_date');
                }
                if (! Schema::hasColumn('quotations', 'advance_payment_memo')) {
                    $table->text('advance_payment_memo')->nullable()->after('advance_payment_reference');
                }
            });
        }
    }

    public function down(): void
    {
        Schema::table('invoices', function (Blueprint $table) {
            $table->dropColumn([
                'advance_payment_method',
                'advance_payment_date',
                'advance_payment_reference',
                'advance_payment_memo',
            ]);
        });

        if (Schema::hasTable('quotations')) {
            Schema::table('quotations', function (Blueprint $table) {
                $table->dropColumn([
                    'advance_payment_method',
                    'advance_payment_date',
                    'advance_payment_reference',
                    'advance_payment_memo',
                ]);
            });
        }
    }
};
