<?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('indirect_goods_incoming', function (Blueprint $table) {
            $table->id();
            $table->string('receipt_number')->unique();
            $table->date('receipt_date');
            $table->enum('status', ['draft', 'approved', 'completed'])->default('draft');

            // Supplier & Invoice
            $table->foreignId('supplier_id')->nullable()
                  ->constrained('suppliers')->onDelete('set null');
            $table->string('invoice_number', 100)->nullable();
            $table->date('invoice_date')->nullable();
            $table->string('delivery_note_number')->nullable();

            // Project (optional - if delivering direct to project)
            $table->foreignId('project_id')->nullable()
                  ->constrained('projects')->onDelete('set null');
            $table->foreignId('division_id')->nullable()
                  ->constrained('project_divisions')->onDelete('set null');

            // Financial
            $table->decimal('total_amount', 15, 2)->default(0);
            $table->decimal('vat_amount', 15, 2)->default(0);
            $table->decimal('vat_rate', 5, 2)->default(5.00);
            $table->enum('currency', ['AED', 'USD', 'EUR'])->default('AED');

            // Documents
            $table->string('delivery_file')->nullable();
            $table->json('attached_documents')->nullable();

            // Workflow
            $table->foreignId('received_by')
                  ->constrained('users')->onDelete('cascade');
            $table->foreignId('approved_by')->nullable()
                  ->constrained('users')->onDelete('set null');
            $table->dateTime('approved_at')->nullable();
            $table->text('notes')->nullable();

            $table->timestamps();
            $table->softDeletes();

            $table->index(['status', 'receipt_date']);
            $table->index('invoice_number');
            $table->index('supplier_id');
        });
    }

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