<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('direct_deliveries', function (Blueprint $table) {
            $table->id();
            $table->string('delivery_number')->unique();
            $table->string('purchase_order_number')->nullable();
            $table->string('supplier_delivery_note')->nullable();

            // Supplier and Project Information
            $table->foreignId('supplier_id')->constrained('suppliers')->onDelete('restrict');
            $table->foreignId('project_id')->constrained('projects')->onDelete('restrict');
            $table->foreignId('project_division_id')->nullable()->constrained('project_divisions')->onDelete('set null');

            // Delivery Details
            $table->date('delivery_date');
            $table->date('order_date')->nullable();
            $table->string('delivered_by')->nullable(); // Driver/person name
            $table->string('vehicle_number')->nullable();

            // Status and Tracking
            $table->enum('status', ['pending', 'partially_received', 'received', 'cancelled'])->default('pending');
            $table->enum('delivery_type', ['purchase_order', 'direct_purchase', 'emergency'])->default('purchase_order');

            // Financial Information
            $table->decimal('total_amount', 15, 2)->nullable();
            $table->string('currency', 3)->default('AED');
            $table->decimal('tax_amount', 10, 2)->default(0);
            $table->decimal('discount_amount', 10, 2)->default(0);

            // Receipt Information
            $table->datetime('received_at')->nullable();
            $table->foreignId('received_by')->nullable()->constrained('users')->onDelete('set null');
            $table->text('receipt_notes')->nullable();
            $table->string('receipt_document_path')->nullable();

            // Additional Notes
            $table->text('delivery_notes')->nullable();
            $table->text('rejection_reason')->nullable();

            // Approval (for high value or restricted items)
            $table->boolean('requires_approval')->default(false);
            $table->foreignId('approved_by')->nullable()->constrained('users')->onDelete('set null');
            $table->datetime('approved_at')->nullable();
            $table->text('approval_notes')->nullable();

            $table->timestamps();

            // Indexes
            $table->index(['delivery_number']);
            $table->index(['supplier_id']);
            $table->index(['project_id']);
            $table->index(['status']);
            $table->index(['delivery_date']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('direct_deliveries');
    }
};
