<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('order_items', function (Blueprint $table) {
            if (!Schema::hasColumn('order_items', 'system_subtotal')) {
                $table->decimal('system_subtotal', 15, 2)->nullable()->after('calculated_price');
            }

            if (!Schema::hasColumn('order_items', 'manual_price')) {
                $table->decimal('manual_price', 15, 2)->nullable()->after('system_subtotal');
            }

            if (!Schema::hasColumn('order_items', 'minimum_order_applied')) {
                $table->boolean('minimum_order_applied')->default(false)->after('manual_price');
            }
        });

        if (Schema::hasColumn('order_items', 'system_subtotal')) {
            DB::table('order_items')
                ->whereNull('system_subtotal')
                ->update(['system_subtotal' => DB::raw('subtotal')]);
        }
    }

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

            if (Schema::hasColumn('order_items', 'manual_price')) {
                $table->dropColumn('manual_price');
            }

            if (Schema::hasColumn('order_items', 'system_subtotal')) {
                $table->dropColumn('system_subtotal');
            }
        });
    }
};
