<?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('late_arrival_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 details
            $table->date('request_date');
            $table->time('planned_arrival_time'); // Jam rencana datang

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

            // Status & Approval
            $table->string('status')->default('pending'); // pending, approved, rejected, used, expired
            $table->foreignId('approved_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamp('approved_at')->nullable();
            $table->text('rejection_reason')->nullable();

            // Actual check-in (filled when used)
            $table->timestamp('actual_checkin_at')->nullable();

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

            $table->timestamps();

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

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

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