<?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('material_transfer_issues', function (Blueprint $table) {
            $table->id();
            $table->string('transfer_issue_number')->unique();
            $table->foreignId('transfer_request_id')->constrained('material_transfer_requests')->onDelete('restrict');
            $table->date('issue_date');

            // Transfer Details
            $table->enum('transfer_type', ['direct_transfer', 'staged_transfer'])->default('direct_transfer');
            $table->text('transfer_instructions')->nullable();

            // Dispatch Information
            $table->foreignId('dispatched_by')->constrained('users')->onDelete('restrict');
            $table->timestamp('dispatched_at')->nullable();
            $table->string('dispatch_vehicle')->nullable();
            $table->string('driver_name')->nullable();
            $table->string('driver_contact')->nullable();

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

            // Status Tracking
            $table->enum('status', ['draft', 'dispatched', 'in_transit', 'delivered', 'partially_received', 'completed', 'cancelled'])->default('draft');

            // Quality Control
            $table->boolean('requires_inspection')->default(false);
            $table->foreignId('inspected_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamp('inspected_at')->nullable();
            $table->enum('inspection_status', ['pending', 'passed', 'failed', 'conditional'])->nullable();
            $table->text('inspection_notes')->nullable();

            // Documentation
            $table->string('delivery_note_path')->nullable();
            $table->json('attached_documents')->nullable();

            // Total Values
            $table->decimal('total_transferred_value', 15, 2)->default(0);
            $table->integer('total_items_transferred')->default(0);

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

            // Indexes
            $table->index(['transfer_request_id']);
            $table->index(['status']);
            $table->index(['issue_date']);
            $table->index(['dispatched_at']);
            $table->index(['received_at']);
        });
    }

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