<?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('early_leave_requests', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->foreignId('company_id')->constrained()->onDelete('cascade');
            $table->uuid('attendance_id')->nullable();

            // Request date (the day they want to leave early)
            $table->date('request_date');

            // Planned leave time
            $table->time('planned_leave_time');

            // Reason for early leave
            $table->string('reason_type'); // sick, family, appointment, emergency, other
            $table->text('reason_detail')->nullable();

            // Status: pending, approved, rejected, used, expired
            $table->string('status')->default('pending');

            // Approval info
            $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('approved_at')->nullable();
            $table->text('rejection_reason')->nullable();

            // Actual checkout info (filled when used)
            $table->timestamp('actual_checkout_at')->nullable();

            // For backdate mode - simulated timestamps
            $table->timestamp('simulated_request_at')->nullable();
            $table->boolean('is_auto_approved')->default(false);

            $table->timestamps();

            // Indexes
            $table->index('user_id');
            $table->index('company_id');
            $table->index('request_date');
            $table->index('status');

            // Foreign key for attendance (UUID)
            $table->foreign('attendance_id')
                ->references('id')
                ->on('attendances')
                ->nullOnDelete();
        });
    }

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