<?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
    {
        // Enhanced Incoming Operations Table
        Schema::create('incoming_operations', function (Blueprint $table) {
            $table->id();
            $table->string('operation_number')->unique();
            $table->enum('operation_type', ['supplier_delivery', 'site_return', 'inter_division_transfer', 'emergency_procurement']);
            $table->date('operation_date');
            $table->enum('status', ['draft', 'pending_inspection', 'approved', 'rejected', 'completed'])->default('draft');

            // Reference Information
            $table->foreignId('supplier_id')->nullable()->constrained()->cascadeOnDelete();
            $table->foreignId('project_id')->nullable()->constrained()->cascadeOnDelete();
            $table->string('project_phase')->nullable();
            $table->foreignId('division_id')->constrained('departments')->cascadeOnDelete();
            $table->string('site_location')->nullable();
            $table->json('gps_coordinates')->nullable();

            // LPO Management
            $table->string('lpo_number')->nullable();
            $table->enum('lpo_status', ['pending', 'approved', 'partially_delivered', 'completed', 'cancelled'])->nullable();
            $table->decimal('lpo_budget_amount', 15, 2)->nullable();
            $table->enum('currency', ['AED', 'USD', 'EUR'])->default('AED');
            $table->decimal('exchange_rate', 10, 4)->default(1.0000);

            // Delivery Information
            $table->string('delivery_note_number')->nullable();
            $table->string('vehicle_number')->nullable();
            $table->string('driver_name')->nullable();
            $table->string('driver_contact')->nullable();
            $table->dateTime('delivery_datetime')->nullable();
            $table->text('delivery_instructions')->nullable();

            // Quality Control
            $table->boolean('requires_inspection')->default(true);
            $table->foreignId('inspector_id')->nullable()->constrained('users')->nullOnDelete();
            $table->dateTime('inspection_datetime')->nullable();
            $table->enum('inspection_result', ['passed', 'failed', 'conditional', 'pending'])->nullable();
            $table->text('inspection_notes')->nullable();
            $table->json('inspection_checklist')->nullable();

            // Financial Information
            $table->decimal('total_amount', 15, 2)->default(0);
            $table->decimal('total_amount_aed', 15, 2)->default(0);
            $table->decimal('vat_amount', 15, 2)->default(0);
            $table->decimal('vat_rate', 5, 2)->default(5.00); // UAE VAT rate

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

            // Workflow
            $table->foreignId('received_by')->constrained('users')->cascadeOnDelete();
            $table->string('received_by_name')->nullable();
            $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete();
            $table->dateTime('approved_at')->nullable();
            $table->text('approval_notes')->nullable();

            // Compliance & Audit
            $table->boolean('regulatory_compliant')->default(false);
            $table->json('compliance_checklist')->nullable();
            $table->text('notes')->nullable();
            $table->text('rejection_reason')->nullable();

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

            // Indexes
            $table->index(['operation_type', 'status']);
            $table->index(['operation_date']);
            $table->index(['lpo_number']);
            $table->index(['project_id', 'division_id']);
        });

        // Enhanced Incoming Items Table
        Schema::create('incoming_operation_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('incoming_operation_id')->constrained()->cascadeOnDelete();
            $table->foreignId('item_id')->constrained()->cascadeOnDelete();

            // Quantity Information
            $table->decimal('quantity_ordered', 10, 2)->nullable();
            $table->decimal('quantity_delivered', 10, 2);
            $table->decimal('quantity_accepted', 10, 2)->default(0);
            $table->decimal('quantity_rejected', 10, 2)->default(0);
            $table->string('unit_of_measure')->nullable();

            // Pricing in original currency
            $table->decimal('unit_price', 10, 2);
            $table->decimal('total_price', 15, 2);
            $table->enum('currency', ['AED', 'USD', 'EUR'])->default('AED');

            // Pricing in AED (base currency)
            $table->decimal('unit_price_aed', 10, 2);
            $table->decimal('total_price_aed', 15, 2);

            // Quality & Batch Information
            $table->string('batch_number')->nullable();
            $table->string('serial_number')->nullable();
            $table->date('manufacturing_date')->nullable();
            $table->date('expiry_date')->nullable();
            $table->string('manufacturer')->nullable();
            $table->string('country_of_origin')->nullable();

            // Quality Control
            $table->enum('quality_status', ['pending', 'passed', 'failed', 'conditional'])->default('pending');
            $table->text('quality_notes')->nullable();
            $table->json('quality_checklist')->nullable();
            $table->text('rejection_reason')->nullable();

            // Storage & Location
            $table->string('storage_location')->nullable();
            $table->string('storage_conditions')->nullable();
            $table->boolean('hazardous_material')->default(false);
            $table->json('hazard_classifications')->nullable();

            // Warranty & Maintenance
            $table->integer('warranty_period_months')->nullable();
            $table->date('warranty_expiry')->nullable();
            $table->boolean('requires_maintenance')->default(false);
            $table->integer('maintenance_interval_days')->nullable();

            // Project Allocation
            $table->foreignId('allocated_project_id')->nullable()->constrained('projects')->nullOnDelete();
            $table->string('project_phase')->nullable();
            $table->string('work_area')->nullable();

            $table->timestamps();

            // Indexes
            $table->index(['quality_status']);
            $table->index(['expiry_date']);
            $table->index(['allocated_project_id']);
        });

        // Quality Inspection Checklists Table
        Schema::create('quality_inspection_checklists', function (Blueprint $table) {
            $table->id();
            $table->string('checklist_name');
            $table->string('material_category');
            $table->json('inspection_criteria');
            $table->boolean('is_active')->default(true);
            $table->boolean('is_mandatory')->default(false);
            $table->text('instructions')->nullable();
            $table->timestamps();
        });

        // LPO Management Table
        Schema::create('lpo_management', function (Blueprint $table) {
            $table->id();
            $table->string('lpo_number')->unique();
            $table->foreignId('supplier_id')->constrained()->cascadeOnDelete();
            $table->foreignId('project_id')->nullable()->constrained()->cascadeOnDelete();
            $table->foreignId('division_id')->constrained('departments')->cascadeOnDelete();

            $table->date('lpo_date');
            $table->date('expected_delivery_date');
            $table->enum('status', ['draft', 'pending_approval', 'approved', 'sent_to_supplier', 'partially_delivered', 'completed', 'cancelled'])->default('draft');
            $table->enum('priority', ['low', 'medium', 'high', 'urgent'])->default('medium');

            // Financial Information
            $table->decimal('total_amount', 15, 2);
            $table->enum('currency', ['AED', 'USD', 'EUR'])->default('AED');
            $table->decimal('exchange_rate', 10, 4)->default(1.0000);
            $table->decimal('total_amount_aed', 15, 2);

            // Budget Validation
            $table->decimal('budget_allocated', 15, 2)->nullable();
            $table->decimal('budget_consumed', 15, 2)->default(0);
            $table->boolean('budget_approved')->default(false);
            $table->foreignId('budget_approved_by')->nullable()->constrained('users')->nullOnDelete();

            // Approval Workflow
            $table->foreignId('created_by')->constrained('users')->cascadeOnDelete();
            $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete();
            $table->dateTime('approved_at')->nullable();
            $table->text('approval_notes')->nullable();

            // Delivery Tracking
            $table->integer('total_items')->default(0);
            $table->integer('delivered_items')->default(0);
            $table->decimal('delivery_percentage', 5, 2)->default(0);

            $table->text('terms_and_conditions')->nullable();
            $table->text('notes')->nullable();

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

            // Indexes
            $table->index(['status', 'priority']);
            $table->index(['expected_delivery_date']);
            $table->index(['project_id', 'division_id']);
        });

        // LPO Items Table
        Schema::create('lpo_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('lpo_id')->constrained('lpo_management')->cascadeOnDelete();
            $table->foreignId('item_id')->constrained()->cascadeOnDelete();

            $table->decimal('quantity_ordered', 10, 2);
            $table->decimal('quantity_delivered', 10, 2)->default(0);
            $table->decimal('quantity_remaining', 10, 2);
            $table->string('unit_of_measure')->nullable();

            $table->decimal('unit_price', 10, 2);
            $table->decimal('total_price', 15, 2);
            $table->enum('currency', ['AED', 'USD', 'EUR'])->default('AED');

            $table->date('expected_delivery_date')->nullable();
            $table->enum('status', ['pending', 'partially_delivered', 'fully_delivered', 'cancelled'])->default('pending');

            $table->text('specifications')->nullable();
            $table->text('notes')->nullable();

            $table->timestamps();

            // Indexes
            $table->index(['status']);
            $table->index(['expected_delivery_date']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('lpo_items');
        Schema::dropIfExists('lpo_management');
        Schema::dropIfExists('quality_inspection_checklists');
        Schema::dropIfExists('incoming_operation_items');
        Schema::dropIfExists('incoming_operations');
    }
};