<?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('members', function (Blueprint $table) {
            $table->id();
            $table->string('membership_code', 50)->unique();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->enum('status', ['active', 'inactive', 'suspended', 'pending'])->default('pending');
            $table->date('approval_date')->nullable();
            $table->foreignId('approved_by')->nullable()->constrained('users')->onDelete('set null');
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null');
            $table->date('membership_start_date')->nullable();
            $table->date('membership_end_date')->nullable();
            $table->enum('renewal_type', ['manual', 'automatic'])->default('manual');
            $table->boolean('auto_renewal_enabled')->default(false);
            $table->timestamp('last_renewal_date')->nullable();
            $table->timestamp('next_renewal_date')->nullable();
            $table->text('notes')->nullable();
            $table->timestamps();
            $table->softDeletes();
            
            $table->index('membership_code');
            $table->index('status');
            $table->index('user_id');
            $table->index('approval_date');
        });

        // Pivot table for member_membership_category relationship
        Schema::create('member_membership_category', function (Blueprint $table) {
            $table->id();
            $table->foreignId('member_id')->constrained()->onDelete('cascade');
            $table->foreignId('membership_category_id')->constrained()->onDelete('cascade');
            $table->date('assigned_date');
            $table->foreignId('assigned_by')->nullable()->constrained('users')->onDelete('set null');
            $table->boolean('is_primary')->default(false);
            $table->timestamps();
            
            $table->unique(['member_id', 'membership_category_id'], 'mem_cat_unique');
            $table->index('is_primary');
        });
    }

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