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

            // Required FK -> rm_orders(id)
            $table->foreignId('order_id')
                  ->constrained('rm_orders')
                  ->cascadeOnUpdate()
                  ->restrictOnDelete(); // rm_order_deliveries_order_id_foreign

            // Plain columns (no FK shown in dump)
            $table->unsignedBigInteger('warehouse_id')->nullable();
            $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();

            $table->unsignedBigInteger('payment_type')->nullable();

            // FKs to users
            $table->foreignId('created_by')
                  ->constrained('users')
                  ->cascadeOnUpdate()
                  ->restrictOnDelete(); // rm_order_deliveries_created_by_foreign

            $table->foreignId('updated_by')
                  ->nullable()
                  ->constrained('users')
                  ->cascadeOnUpdate()
                  ->nullOnDelete();     // rm_order_deliveries_updated_by_foreign

            // Timestamps nullable (per dump)
            $table->timestamp('created_at')->nullable();
            $table->timestamp('updated_at')->nullable();

            // Not-null with defaults = 0.00
            $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);

            // Other nullable fields
            $table->string('cho_no', 191)->nullable();
            $table->decimal('previous_due', 16, 2)->nullable();
            $table->decimal('delivery_cost', 16, 2)->nullable();
        });
    }

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