<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('student_promotion_records')) {
            return;
        }

        Schema::create('student_promotion_records', function (Blueprint $table) {
            $table->id('promotion_id');
            $table->unsignedInteger('student_id')->index();
            $table->unsignedInteger('parent_id')->nullable()->index();

            $table->string('current_school_year', 9);
            $table->string('next_school_year', 9);

            $table->unsignedInteger('current_level_id')->nullable();
            $table->unsignedInteger('promoted_level_id')->nullable();
            $table->string('current_level_name', 100)->nullable();
            $table->string('promoted_level_name', 100)->nullable();

            // Promotion lifecycle status (matches plan section 3)
            $table->string('promotion_status', 40)->default('not_reviewed');

            $table->boolean('passed_current_level')->nullable();
            $table->decimal('final_average', 6, 2)->nullable();
            $table->boolean('attendance_ok')->nullable();
            $table->text('eligibility_notes')->nullable();

            $table->boolean('enrollment_required')->default(true);
            $table->string('enrollment_status', 40)->default('not_started');
            $table->unsignedBigInteger('enrollment_id')->nullable()->index();

            $table->dateTime('parent_notified_at')->nullable();
            $table->date('enrollment_deadline')->nullable();
            $table->dateTime('enrollment_started_at')->nullable();
            $table->dateTime('enrollment_completed_at')->nullable();
            $table->dateTime('promotion_finalized_at')->nullable();

            $table->boolean('info_confirmed')->default(false);
            $table->boolean('documents_uploaded')->default(false);
            $table->boolean('agreement_accepted')->default(false);
            $table->boolean('payment_completed')->default(false);

            $table->unsignedInteger('updated_by')->nullable();
            $table->timestamps();

            $table->unique(['student_id', 'next_school_year'], 'uq_promotion_student_year');
            $table->index('promotion_status', 'idx_promotion_status');
            $table->index(['next_school_year', 'promotion_status'], 'idx_promotion_year_status');
        });
    }

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