<?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_delivery_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('direct_delivery_id')->constrained('direct_deliveries')->onDelete('cascade');
            $table->foreignId('item_id')->constrained('items')->onDelete('restrict');

            // Quantities
            $table->decimal('ordered_quantity', 10, 2);
            $table->decimal('delivered_quantity', 10, 2);
            $table->decimal('received_quantity', 10, 2)->default(0);
            $table->decimal('rejected_quantity', 10, 2)->default(0);
            $table->string('unit_of_measure')->nullable();

            // Pricing
            $table->decimal('unit_price', 10, 2);
            $table->decimal('total_price', 15, 2);
            $table->decimal('tax_rate', 5, 2)->default(0);
            $table->decimal('tax_amount', 10, 2)->default(0);
            $table->decimal('discount_rate', 5, 2)->default(0);
            $table->decimal('discount_amount', 10, 2)->default(0);

            // Item Details
            $table->string('batch_number')->nullable();
            $table->date('expiry_date')->nullable();
            $table->string('manufacturer')->nullable();
            $table->text('item_description')->nullable();
            $table->text('specifications')->nullable();

            // Quality Check
            $table->enum('quality_status', ['pending', 'passed', 'failed', 'partial'])->default('pending');
            $table->text('quality_notes')->nullable();
            $table->datetime('quality_checked_at')->nullable();
            $table->foreignId('quality_checked_by')->nullable()->constrained('users')->onDelete('set null');

            // Storage Location at Project
            $table->string('storage_location')->nullable();
            $table->string('rack_number')->nullable();
            $table->string('bin_number')->nullable();

            // Receipt Details
            $table->text('receipt_notes')->nullable();
            $table->text('rejection_reason')->nullable();

            $table->timestamps();

            // Indexes
            $table->index(['direct_delivery_id']);
            $table->index(['item_id']);
            $table->index(['batch_number']);
        });
    }

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