<?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('orders', function (Blueprint $table) {
            $table->id();
            $table->string('order_number', 50)->unique();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->enum('order_type', ['BUY', 'SELL'])->index();
            $table->datetime('order_date');
            $table->enum('status', ['DRAFT', 'CONFIRMED', 'CLOSED'])->default('DRAFT')->index();
            $table->enum('money_status', ['UNSETTLED', 'PARTIAL', 'SETTLED'])->default('UNSETTLED')->index();
            $table->decimal('money_amount', 20, 0)->default(0); // Rials (no decimals)
            $table->text('notes')->nullable();
            
            // Timestamps for status changes
            $table->datetime('confirmed_at')->nullable();
            $table->foreignId('confirmed_by')->nullable()->constrained('users')->nullOnDelete();
            $table->datetime('closed_at')->nullable();
            $table->foreignId('closed_by')->nullable()->constrained('users')->nullOnDelete();
            $table->datetime('voided_at')->nullable();
            $table->foreignId('voided_by')->nullable()->constrained('users')->nullOnDelete();
            
            $table->timestamps();
            $table->softDeletes();

            // Composite indexes
            $table->index(['user_id', 'status']);
            $table->index(['order_date', 'status']);
        });
    }

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