<?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('subscription_fees', function (Blueprint $table) {
            $table->id();
            $table->foreignId('membership_category_id')->constrained()->onDelete('cascade');
            $table->string('name', 191);
            $table->text('description')->nullable();
            $table->decimal('amount', 15, 2);
            $table->enum('currency', ['USD', 'SSP', 'KES', 'UGX'])->default('SSP');
            $table->enum('billing_cycle', ['one_time', 'monthly', 'quarterly', 'biannual', 'annual'])->default('annual');
            $table->boolean('is_active')->default(true);
            $table->boolean('is_default')->default(false);
            $table->date('effective_from')->nullable();
            $table->date('effective_until')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamps();
            $table->softDeletes();
            
            $table->index('membership_category_id');
            $table->index('is_active');
            $table->index('currency');
        });

        // Subscription fee history for audit purposes
        Schema::create('subscription_fee_history', function (Blueprint $table) {
            $table->id();
            $table->foreignId('subscription_fee_id')->constrained()->onDelete('cascade');
            $table->decimal('previous_amount', 15, 2);
            $table->decimal('new_amount', 15, 2);
            $table->string('previous_currency', 10);
            $table->string('new_currency', 10);
            $table->foreignId('changed_by')->constrained('users')->onDelete('cascade');
            $table->text('change_reason')->nullable();
            $table->timestamps();
            
            $table->index('subscription_fee_id');
            $table->index('changed_by');
        });
    }

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