<?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('delivery_men', function (Blueprint $table) {
            if (!Schema::hasColumn('delivery_men', 'due_product_amount')) {
                $table->decimal('due_product_amount', 12, 2)->default(0)->after('platform_commission_percent');
            }
            if (!Schema::hasColumn('delivery_men', 'due_commission_amount')) {
                $table->decimal('due_commission_amount', 12, 2)->default(0)->after('due_product_amount');
            }
            if (!Schema::hasColumn('delivery_men', 'forgot')) {
                $table->string('forgot')->nullable()->after('verify');
            }
        });

        if (!Schema::hasTable('rider_revenue_collections')) {
            Schema::create('rider_revenue_collections', function (Blueprint $table) {
                $table->id();
                $table->unsignedBigInteger('delivery_man_id');
                $table->decimal('product_amount', 12, 2)->default(0);
                $table->decimal('commission_amount', 12, 2)->default(0);
                $table->decimal('total_amount', 12, 2)->default(0);
                $table->string('status')->default('pending'); // pending, completed, cancelled
                $table->string('otp')->nullable();
                $table->timestamp('otp_expires_at')->nullable();
                $table->unsignedBigInteger('collected_by')->nullable();
                $table->timestamp('collected_at')->nullable();
                $table->text('note')->nullable();
                $table->timestamps();

                $table->foreign('delivery_man_id')->references('id')->on('delivery_men')->cascadeOnDelete();
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('rider_revenue_collections');

        Schema::table('delivery_men', function (Blueprint $table) {
            foreach (['due_product_amount', 'due_commission_amount', 'forgot'] as $col) {
                if (Schema::hasColumn('delivery_men', $col)) {
                    $table->dropColumn($col);
                }
            }
        });
    }
};
