<?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 self_paced_enrollments table — tracks a Trainee's paid
     * registration for a Course including payment details and lifecycle status.
     */
    public function up(): void
    {
        Schema::create('self_paced_enrollments', function (Blueprint $table) {
            $table->id();

            $table->foreignId('user_id')
                ->constrained('users')
                ->cascadeOnDelete();
            $table->foreignId('course_id')
                ->constrained('self_paced_courses')
                ->cascadeOnDelete();

            $table->enum('status', [
                'pending_payment',
                'active',
                'completed',
                'payment_failed',
                'cancelled',
            ])->default('pending_payment');

            // Payment Details
            $table->string('payment_reference', 191)->nullable();
            $table->string('payment_method', 50)->default('mtn_momo');
            $table->decimal('amount_paid', 10, 2)->default(0.00);
            $table->timestamp('payment_date')->nullable();

            // Lifecycle timestamps
            $table->timestamp('enrolled_at')->nullable();
            $table->timestamp('completed_at')->nullable();

            // Audit
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();

            $table->timestamps();

            // A user can only have one enrollment per course
            $table->unique(['user_id', 'course_id'], 'unique_user_course_enrollment');

            $table->index('user_id');
            $table->index('course_id');
            $table->index('status');
        });
    }

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