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

            // FK columns (as per index list)
            $table->foreignId('company_id')
                  ->nullable()
                  ->constrained('companies')
                  ->cascadeOnUpdate()
                  ->nullOnDelete(); // rm_orders_company_id_foreign

            $table->foreignId('customer_id')
                  ->nullable()
                  ->constrained('rm_customers') // change to 'customers' if that's your parent
                  ->cascadeOnUpdate()
                  ->nullOnDelete();             // rm_orders_customer_id_foreign

            $table->foreignId('employee_id')
                  ->nullable()
                  ->constrained('rm_employees') // change if your table is named differently
                  ->cascadeOnUpdate()
                  ->nullOnDelete();             // rm_orders_employee_id_foreign

            // Data columns
            $table->string('invoice_no', 191)->nullable();
            $table->date('date')->nullable();
            $table->date('delivery_date')->nullable();

            $table->decimal('subtotal',       16, 2)->nullable();
            $table->decimal('vat',            16, 2)->nullable();
            $table->decimal('discount',       16, 2)->nullable();
            $table->decimal('shipping_cost',  16, 2)->nullable();
            $table->decimal('payable_amount', 16, 2)->nullable();
            $table->decimal('paid_amount',    16, 2)->nullable();
            $table->decimal('due_amount',     16, 2)->nullable();

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

            $table->tinyInteger('is_approved')->default(0);
            $table->tinyInteger('delivery_status')->default(0);

            $table->foreignId('created_by')
                  ->constrained('users')
                  ->cascadeOnUpdate()
                  ->restrictOnDelete();         // rm_orders_created_by_foreign

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

            $table->unsignedBigInteger('warehouse_id')->nullable(); // no FK in dump
            $table->string('cancel_reason', 191)->nullable();

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

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

