<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('contributions', function (Blueprint $table) {
            $table->id();
            $table->string('reference_number', 50)->unique();
            $table->foreignId('member_id')->constrained()->onDelete('cascade');
            $table->foreignId('membership_category_id')->constrained()->onDelete('cascade');
            $table->foreignId('contribution_fee_id')->nullable()->constrained()->onDelete('set null');
            
            // Amount details
            $table->decimal('amount', 15, 2);
            $table->decimal('penalty_amount', 15, 2)->default(0);
            $table->decimal('total_amount', 15, 2);
            $table->enum('currency', ['USD', 'SSP', 'KES', 'UGX'])->default('SSP');
            
            // Dates
            $table->date('due_date');
            $table->date('paid_date')->nullable();
            $table->string('period', 20)->nullable(); // e.g., '2024-01', 'Q1-2024'
            
            // Status
            $table->enum('status', ['pending', 'paid', 'overdue', 'cancelled', 'refunded'])->default('pending');
            $table->boolean('is_penalty_applied')->default(false);
            $table->timestamp('penalty_applied_at')->nullable();
            
            // Payment Information
            $table->string('payment_method')->nullable();
            $table->string('payment_reference')->nullable();
            $table->string('transaction_id')->nullable();
            $table->json('payment_details')->nullable();
            
            // Notes
            $table->text('notes')->nullable();
            $table->text('admin_notes')->nullable();
            
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamps();
            $table->softDeletes();
            
            $table->index('reference_number');
            $table->index('member_id');
            $table->index('membership_category_id');
            $table->index('status');
            $table->index('due_date');
            $table->index('period');
            $table->index(['member_id', 'status']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('contributions');
    }
};
