<?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_resit_payments table — records each payment made
     * by a learner to sit a re-sit exam on the self-paced learning portal.
     * Tracks which enrollment, user, and course the payment belongs to, the
     * payment method and reference, and optionally links to an uploaded proof.
     */
    public function up(): void
    {
        Schema::create('self_paced_resit_payments', function (Blueprint $table) {
            $table->bigIncrements('id');

            // Owning enrollment
            $table->unsignedBigInteger('enrollment_id');
            $table->foreign('enrollment_id')
                  ->references('id')->on('self_paced_enrollments')
                  ->cascadeOnDelete();

            // Learner
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')
                  ->references('id')->on('users')
                  ->cascadeOnDelete();

            // Course
            $table->unsignedBigInteger('course_id');
            $table->foreign('course_id')
                  ->references('id')->on('self_paced_courses')
                  ->cascadeOnDelete();

            // Payment details
            $table->string('payment_reference', 100);
            $table->enum('payment_method', ['paystack', 'cash'])->default('paystack');
            $table->decimal('amount_paid', 12, 2);
            $table->string('currency', 10)->default('KES');

            // Which re-sit this payment covers (1 = first re-sit, 2 = second, …)
            $table->unsignedInteger('resit_number')->default(1)
                  ->comment('Which re-sit this payment is for');

            // Optional uploaded proof of payment
            $table->unsignedBigInteger('proof_id')->nullable();
            $table->foreign('proof_id')
                  ->references('id')->on('self_paced_payment_proofs')
                  ->nullOnDelete();

            $table->timestamp('payment_date')->nullable();

            $table->timestamps();

            // Indexes
            $table->index('enrollment_id', 'idx_sp_resit_enrollment');
            $table->index('payment_reference', 'idx_sp_resit_reference');
        });
    }

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