<?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('orders', function (Blueprint $table) {
            if (!Schema::hasColumn('orders', 'spk_printed')) {
                $table->boolean('spk_printed')->default(false)->after('updated_at');
            }

            if (!Schema::hasColumn('orders', 'spk_printed_at')) {
                $table->timestamp('spk_printed_at')->nullable()->after('spk_printed');
            }

            if (!Schema::hasColumn('orders', 'remaining_balance')) {
                $table->decimal('remaining_balance', 15, 2)->default(0)->after('spk_printed_at');
            }

            if (!Schema::hasColumn('orders', 'report_total_price')) {
                $table->decimal('report_total_price', 15, 2)->default(0)->after('remaining_balance');
            }

            if (!Schema::hasColumn('orders', 'report_total_qty')) {
                $table->integer('report_total_qty')->default(0)->after('report_total_price');
            }

            if (!Schema::hasColumn('orders', 'report_remaining_balance')) {
                $table->decimal('report_remaining_balance', 15, 2)->default(0)->after('report_total_qty');
            }
        });
    }

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

            foreach ([
                'spk_printed',
                'spk_printed_at',
                'remaining_balance',
                'report_total_price',
                'report_total_qty',
                'report_remaining_balance',
            ] as $column) {
                if (Schema::hasColumn('orders', $column)) {
                    $columns[] = $column;
                }
            }

            if (!empty($columns)) {
                $table->dropColumn($columns);
            }
        });
    }
};