<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('attendance_records', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('training_session_id')->constrained('training_sessions')->cascadeOnDelete();
            $table->nullableMorphs('subject'); // participant or user (trainer)
            $table->string('status', 20)->default('expected');
            $table->timestamp('check_in_at')->nullable();
            $table->timestamp('check_out_at')->nullable();
            $table->integer('late_minutes')->nullable();
            $table->integer('duration_minutes')->nullable();
            $table->text('notes')->nullable();
            $table->string('status_reason', 255)->nullable();
            $table->foreignId('marked_by')->nullable()->constrained('users');
            $table->timestamp('marked_at')->nullable();
            $table->boolean('is_auto_generated')->default(true);
            $table->boolean('is_flagged')->default(false);
            $table->jsonb('metadata')->default('{}');
            $table->timestamps();

            $table->index(['training_session_id', 'status']);
            $table->index(['academy_id', 'subject_type', 'subject_id']);
            $table->index(['academy_id', 'status', 'created_at']);
            $table->unique(['training_session_id', 'subject_type', 'subject_id']);
        });

        DB::statement("ALTER TABLE attendance_records ADD CONSTRAINT attendance_records_status_check CHECK (status IN ('expected', 'present', 'late', 'excused', 'absent', 'no_show', 'left_early', 'partial', 'cancelled', 'exempt'))");
    }

    public function down(): void
    {
        Schema::dropIfExists('attendance_records');
    }
};
