<?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
    {
        if (!Schema::hasTable('rm_deliveries')) {
            Schema::create('rm_deliveries', function (Blueprint $table) {
                $table->id(); // BIGINT UNSIGNED AI

                // FK columns now as plain columns (FKs will be added later)
                $table->unsignedBigInteger('sale_id');          // NOT NULL (dump)
                $table->unsignedBigInteger('created_by');       // NOT NULL (dump)
                $table->unsignedBigInteger('updated_by')->nullable();

                // Data columns (exact per dump)
                $table->string('challan_no', 191)->nullable();
                $table->date('date')->nullable();
                $table->string('delivery_address', 191)->nullable();
                $table->string('vehicle_no', 191)->nullable();
                $table->string('driver_name', 191)->nullable();
                $table->string('driver_phone', 191)->nullable();
                $table->string('remarks', 191)->nullable();

                $table->decimal('total_kg',          16, 2)->nullable();
                $table->decimal('total_bag',         16, 2)->nullable();
                $table->decimal('total_mon',         16, 2)->nullable();
                $table->decimal('grand_total_price', 16, 2)->nullable();

                // NOT NULL defaults
                $table->decimal('paid_amount',       16, 2)->default(0.00);
                $table->decimal('due_amount',        16, 2)->default(0.00);
                $table->decimal('vehicle_fare',      16, 2)->default(0.00);
                $table->decimal('vehicle_fare_paid', 16, 2)->default(0.00);
                $table->decimal('vehicle_fare_due',  16, 2)->default(0.00);

                $table->string('cho_no', 191)->nullable();

                // timestamps nullable (to match dump)
                $table->timestamp('created_at')->nullable();
                $table->timestamp('updated_at')->nullable();

                // helpful indexes
                $table->index('sale_id',    'rm_deliveries_sale_id_index');
                $table->index('created_by', 'rm_deliveries_created_by_index');
                $table->index('updated_by', 'rm_deliveries_updated_by_index');
            });
        }
    }

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


