<?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('qr_attendance_logs', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->foreignId('scanned_user_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('scanner_user_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('company_id')->constrained()->onDelete('cascade');
            $table->uuid('attendance_id')->nullable();
            $table->enum('scan_type', ['check_in', 'check_out']);
            $table->decimal('latitude', 10, 8)->nullable();
            $table->decimal('longitude', 11, 8)->nullable();
            $table->enum('scan_status', ['success', 'failed']);
            $table->string('failure_reason')->nullable();
            $table->json('device_info')->nullable();
            $table->timestamp('scanned_at');
            $table->timestamps();

            $table->index(['scanned_user_id', 'scanned_at']);
            $table->index(['scanner_user_id', 'scanned_at']);
            $table->index(['company_id', 'scanned_at']);

            $table->foreign('attendance_id')->references('id')->on('attendances')->onDelete('set null');
        });
    }

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