<?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_payment_proofs table — stores cash payment proof
     * uploads (M-Pesa screenshots, bank slips, institution receipts) submitted
     * by Trainees and pending manager verification.
     */
    public function up(): void
    {
        Schema::create('self_paced_payment_proofs', function (Blueprint $table) {
            $table->id();

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

            $table->enum('fee_type', ['enrollment', 'certificate', 'book', 'resit']);
            $table->enum('proof_type', ['mpesa', 'bank_slip', 'institution_receipt']);

            // Uploaded file details
            $table->string('file_path', 500);
            $table->string('file_name', 255);
            $table->unsignedInteger('file_size')->comment('File size in bytes');
            $table->string('file_mime', 100);

            // Payment amount
            $table->decimal('amount', 12, 2)->default(0.00);
            $table->string('currency', 10)->default('KES');

            // Review workflow
            $table->enum('status', ['pending', 'approved', 'rejected'])->default('pending');
            $table->text('rejection_reason')->nullable();
            $table->unsignedBigInteger('reviewed_by')->nullable();
            $table->timestamp('reviewed_at')->nullable();

            $table->timestamps();

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

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

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

            $table->foreign('reviewed_by', 'fk_sp_proofs_reviewer')
                ->references('id')->on('users')
                ->nullOnDelete();

            // Indexes
            $table->index('enrollment_id', 'idx_sp_proofs_enrollment');
            $table->index('status', 'idx_sp_proofs_status');
        });
    }

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