<?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('attendance_corrections', 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();

            // Target date for correction
            $table->date('target_date');

            // Correction type: check_in, check_out, both, duration
            $table->string('correction_type')->default('duration');

            // Original values (stored for audit comparison)
            $table->time('original_check_in')->nullable();
            $table->time('original_check_out')->nullable();
            $table->integer('original_duration')->nullable(); // in minutes

            // Requested correction values
            $table->time('corrected_check_in')->nullable();
            $table->time('corrected_check_out')->nullable();
            $table->integer('corrected_duration')->nullable(); // in minutes

            // Reason for correction
            $table->text('reason')->nullable();

            // Status: pending, approved, rejected, auto_approved
            $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();

            // For tracking "simulated" request date (when backdate mode is enabled)
            $table->timestamp('simulated_request_at')->nullable();

            // Flag to indicate if this was auto-approved (for backdate mode)
            $table->boolean('is_auto_approved')->default(false);

            $table->timestamps();

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

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

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