<?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_certificate_payments table — records payments made
     * by enrolled users to obtain their course completion certificate.
     * One payment per enrollment (enforced by unique key on enrollment_id).
     */
    public function up(): void
    {
        Schema::create('self_paced_certificate_payments', function (Blueprint $table) {
            $table->id();

            $table->unsignedBigInteger('enrollment_id');
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('course_id');

            $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');
            $table->timestamp('payment_date')->nullable();

            $table->unsignedBigInteger('proof_id')->nullable();

            $table->timestamps();

            // Foreign keys
            $table->foreign('enrollment_id')
                ->references('id')->on('self_paced_enrollments')
                ->cascadeOnDelete();

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

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

            $table->foreign('proof_id')
                ->references('id')->on('self_paced_payment_proofs')
                ->nullOnDelete();

            // One certificate payment per enrollment
            $table->unique('enrollment_id', 'uq_sp_cert_payment_enrollment');

            // Fast lookup by payment reference
            $table->index('payment_reference', 'idx_sp_cert_payment_reference');
        });
    }

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