<?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('enrollments', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('participant_id')->constrained('participants');
            $table->foreignId('training_group_id')->constrained('training_groups');
            $table->foreignId('training_program_id')->constrained('training_programs');
            $table->date('enrollment_date');
            $table->date('start_date');
            $table->date('end_date')->nullable();
            $table->string('status', 20)->default('pending');
            $table->foreignId('enrolled_by')->constrained('users');
            $table->foreignId('invoice_id')->nullable()->constrained('invoices');
            $table->string('payment_status', 20)->default('pending');
            $table->integer('sessions_attended')->default(0);
            $table->integer('sessions_total')->nullable();
            $table->decimal('attendance_percentage', 5, 2)->nullable();
            $table->decimal('completion_percentage', 5, 2)->nullable();
            $table->date('withdrawal_date')->nullable();
            $table->string('withdrawal_reason')->nullable();
            $table->foreignId('transferred_to_id')->nullable()->constrained('training_groups');
            $table->text('notes')->nullable();
            $table->jsonb('metadata')->default('{}');
            $table->timestamps();

            $table->unique(['participant_id', 'training_group_id']);
            $table->index(['academy_id', 'status']);
            $table->index(['training_group_id', 'status']);
            $table->index('participant_id');
        });

        DB::statement("ALTER TABLE enrollments ADD CONSTRAINT enrollments_status_check CHECK (status IN ('pending', 'active', 'completed', 'cancelled', 'expired', 'waitlisted'))");
        DB::statement("ALTER TABLE enrollments ADD CONSTRAINT enrollments_payment_status_check CHECK (payment_status IN ('paid', 'pending', 'partial', 'overdue', 'waived'))");
    }

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