<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (!Schema::hasTable('products')) {
            return;
        }

        Schema::table('products', function (Blueprint $table) {
            if (!Schema::hasColumn('products', 'delivery_charge_dhaka_city')) {
                $table->decimal('delivery_charge_dhaka_city', 10, 2)->default(0)->after('delivery_charge');
            }

            if (!Schema::hasColumn('products', 'delivery_charge_sub_dhaka')) {
                $table->decimal('delivery_charge_sub_dhaka', 10, 2)->default(0)->after('delivery_charge_dhaka_city');
            }

            if (!Schema::hasColumn('products', 'delivery_charge_outside_dhaka')) {
                $table->decimal('delivery_charge_outside_dhaka', 10, 2)->default(0)->after('delivery_charge_sub_dhaka');
            }
        });

        DB::table('products')->update([
            'delivery_charge_dhaka_city' => DB::raw('delivery_charge'),
            'delivery_charge_sub_dhaka' => DB::raw('delivery_charge'),
            'delivery_charge_outside_dhaka' => DB::raw('delivery_charge'),
        ]);
    }

    public function down(): void
    {
        if (!Schema::hasTable('products')) {
            return;
        }

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

            foreach (['delivery_charge_dhaka_city', 'delivery_charge_sub_dhaka', 'delivery_charge_outside_dhaka'] as $column) {
                if (Schema::hasColumn('products', $column)) {
                    $columns[] = $column;
                }
            }

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