<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        $users = DB::table('iam_principal')->where('principal_type_xid', 3)->whereNull('referral_code')->orWhere('referral_code', '')->get();

        foreach ($users as $user) {
            do {
                $referral_code = \Str::random(10);
            } while (DB::table('iam_principal')->where('referral_code', $referral_code)->exists());

            DB::table('iam_principal')
                ->where('id', $user->id)
                ->update(['referral_code' => $referral_code]);
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('iam_principal', function (Blueprint $table) {
            //
        });
    }
};
