<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * Creates the training_attendance table to track attendance
     * for each training session per registered participant.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('training_attendance', function (Blueprint $table) {
            $table->id();
            
            // Foreign Keys
            $table->foreignId('training_session_id')
                ->constrained('training_sessions')
                ->cascadeOnDelete();
            $table->foreignId('user_id')
                ->constrained('users')
                ->cascadeOnDelete();
            $table->foreignId('registration_id')
                ->nullable()
                ->constrained('training_registrations')
                ->nullOnDelete();
            
            // Attendance Status
            $table->enum('attendance_status', ['present', 'absent', 'late', 'excused', 'pending'])
                ->default('pending');
            
            // Check-in/Check-out Times
            $table->timestamp('check_in_time')->nullable();
            $table->timestamp('check_out_time')->nullable();
            $table->integer('duration_minutes')->nullable();
            
            // Verification
            $table->foreignId('checked_in_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('checked_out_by')->nullable()->constrained('users')->nullOnDelete();
            
            // Notes and Remarks
            $table->text('notes')->nullable();
            $table->text('absence_reason')->nullable();
            
            // Location Verification (for in-person)
            $table->decimal('latitude', 10, 8)->nullable();
            $table->decimal('longitude', 11, 8)->nullable();
            
            // Online Verification
            $table->string('ip_address', 45)->nullable();
            $table->string('user_agent')->nullable();
            
            // Timestamps
            $table->timestamps();
            
            // Unique Constraint - One attendance record per session per user
            $table->unique(['training_session_id', 'user_id'], 'unique_session_user');
            
            // Indexes
            $table->index('training_session_id');
            $table->index('user_id');
            $table->index('attendance_status');
            $table->index('check_in_time');
        });
    }

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