<?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::table('users', function (Blueprint $table) {
            // Add referral fields
            $table->string('referral_code', 20)->nullable()->unique()->after('cus_id');
            $table->unsignedBigInteger('referred_by')->nullable()->after('referral_code'); // Referral user ID
            $table->string('referral_code_used', 20)->nullable()->after('referred_by'); // Code used during signup
            $table->enum('status', ['pending', 'active', 'suspended'])->default('pending')->after('referral_code_used');
            
            // Add indexes
            $table->index('referral_code');
            $table->index('referred_by');
            $table->index('referral_code_used');
            
            // Foreign key constraint
            $table->foreign('referred_by')->references('id')->on('users')->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropForeign(['referred_by']);
            $table->dropIndex(['referral_code']);
            $table->dropIndex(['referred_by']);
            $table->dropIndex(['referral_code_used']);
            $table->dropColumn([
                'referral_code',
                'referred_by',
                'referral_code_used',
                'status'
            ]);
        });
    }
};
