<?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('timesheets', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->foreignId('job_card_id')->nullable()->constrained()->onDelete('cascade');
            $table->foreignId('work_order_id')->nullable()->constrained()->onDelete('cascade');
            $table->foreignId('work_order_task_id')->nullable()->constrained()->onDelete('cascade');
            $table->foreignId('diagnosis_id')->nullable()->constrained()->onDelete('cascade');
            
            // Time tracking
            $table->date('date');
            $table->time('start_time');
            $table->time('end_time')->nullable();
            $table->decimal('hours_worked', 8, 2)->nullable();
            $table->decimal('break_hours', 8, 2)->default(0);
            $table->decimal('billable_hours', 8, 2)->nullable();
            
            // Entry details
            $table->enum('entry_type', ['clock_in', 'clock_out', 'break_start', 'break_end', 'manual'])->default('manual');
            $table->enum('status', ['draft', 'submitted', 'approved', 'rejected'])->default('draft');
            $table->text('description')->nullable();
            $table->text('work_performed')->nullable();
            $table->text('notes')->nullable();
            
            // Approval workflow
            $table->foreignId('approved_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamp('approved_at')->nullable();
            $table->text('approval_notes')->nullable();
            
            // Rate and billing
            $table->decimal('hourly_rate', 10, 2)->nullable();
            $table->decimal('total_amount', 10, 2)->nullable();
            $table->boolean('is_overtime')->default(false);
            $table->decimal('overtime_multiplier', 3, 2)->default(1.5);
            
            $table->timestamps();
            
            // Indexes
            $table->index(['user_id', 'date']);
            $table->index(['job_card_id', 'date']);
            $table->index(['status', 'date']);
        });
    }

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