<?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
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('delivery_men', function (Blueprint $table) {
            if (!Schema::hasColumn('delivery_men', 'is_online')) {
                $table->boolean('is_online')->default(false)->after('status');
            }
            if (!Schema::hasColumn('delivery_men', 'password')) {
                $table->string('password')->nullable()->after('photo');
            }
        });

        // Insert new order statuses if they don't exist
        $statuses = [
            [
                'name' => 'Assigned to Delivery Man',
                'slug' => 'assigned-to-delivery-man',
                'status' => '1',
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'name' => 'Rider Accepted',
                'slug' => 'rider-accepted',
                'status' => '1',
                'created_at' => now(),
                'updated_at' => now(),
            ]
        ];

        foreach ($statuses as $status) {
            $exists = DB::table('order_statuses')->where('slug', $status['slug'])->exists();
            if (!$exists) {
                DB::table('order_statuses')->insert($status);
            }
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('delivery_men', function (Blueprint $table) {
            if (Schema::hasColumn('delivery_men', 'is_online')) {
                $table->dropColumn('is_online');
            }
            if (Schema::hasColumn('delivery_men', 'password')) {
                $table->dropColumn('password');
            }
        });

        DB::table('order_statuses')->whereIn('slug', ['assigned-to-delivery-man', 'rider-accepted'])->delete();
    }
};
