<?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('work_orders', function (Blueprint $table) {
            $table->id();
            $table->string('work_order_number')->unique();
            $table->foreignId('job_card_id')->constrained()->onDelete('cascade');
            $table->foreignId('estimate_id')->constrained()->onDelete('cascade');
            $table->foreignId('assigned_technician_id')->nullable()->constrained('users')->onDelete('set null');
            $table->foreignId('supervisor_id')->nullable()->constrained('users')->onDelete('set null');
            
            // Work order details
            $table->enum('status', ['scheduled', 'in_progress', 'awaiting_parts', 'quality_check', 'completed', 'on_hold'])->default('scheduled');
            $table->enum('priority', ['low', 'medium', 'high', 'urgent'])->default('medium');
            $table->timestamp('scheduled_start_date')->nullable();
            $table->timestamp('actual_start_date')->nullable();
            $table->timestamp('estimated_completion_date')->nullable();
            $table->timestamp('actual_completion_date')->nullable();
            
            // Progress tracking
            $table->decimal('progress_percentage', 5, 2)->default(0);
            $table->text('work_description')->nullable();
            $table->text('technician_notes')->nullable();
            $table->text('supervisor_notes')->nullable();
            $table->text('quality_check_notes')->nullable();
            $table->boolean('quality_check_passed')->nullable();
            $table->foreignId('quality_checked_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamp('quality_check_date')->nullable();
            
            // Time tracking
            $table->decimal('estimated_hours', 8, 2)->nullable();
            $table->decimal('actual_hours', 8, 2)->default(0);
            
            // Costs
            $table->decimal('labor_cost', 10, 2)->default(0);
            $table->decimal('parts_cost', 10, 2)->default(0);
            $table->decimal('total_cost', 10, 2)->default(0);
            
            $table->timestamps();
            
            // Indexes
            $table->index(['status', 'assigned_technician_id']);
            $table->index(['job_card_id', 'status']);
        });
    }

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