<?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('event_registrations', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('event_id')->constrained('events')->cascadeOnDelete();
            $table->foreignId('person_id')->nullable()->constrained('people')->nullOnDelete();
            $table->string('registration_number', 30);
            $table->string('status', 20)->default('pending');
            $table->jsonb('form_data')->default('{}');
            $table->string('registrant_name');
            $table->string('registrant_phone', 20);
            $table->string('registrant_email')->nullable();
            $table->text('admin_notes')->nullable();
            $table->timestamp('confirmed_at')->nullable();
            $table->timestamp('cancelled_at')->nullable();
            $table->timestamp('attended_at')->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->unique(['academy_id', 'registration_number']);
            $table->index(['event_id', 'status']);
            $table->index(['event_id', 'created_at']);
            $table->index(['academy_id', 'registrant_phone']);
        });

        DB::statement("ALTER TABLE event_registrations ADD CONSTRAINT event_registrations_status_check CHECK (status IN ('pending', 'confirmed', 'cancelled', 'attended', 'no_show'))");
    }

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