<?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('audit_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->foreignId('attendance_id')->nullable()->constrained()->onDelete('cascade');
            $table->string('action'); // create, update, delete, check_in, check_out
            $table->string('entity_type'); // attendance, leave, overtime, etc
            $table->unsignedBigInteger('entity_id')->nullable();
            $table->date('target_date')->nullable(); // tanggal absen yang dituju
            $table->json('old_values')->nullable();
            $table->json('new_values')->nullable();
            $table->boolean('is_backdate')->default(false); // anomaly flag
            $table->integer('backdate_days')->nullable(); // berapa hari backdate
            $table->string('ip_address')->nullable();
            $table->string('user_agent')->nullable();
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->index(['user_id', 'target_date']);
            $table->index(['entity_type', 'entity_id']);
            $table->index('is_backdate');
            $table->index('created_at');
        });
    }

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