<?php
function generateUniqueId($length = 16) {
    return bin2hex(random_bytes($length / 2));
}

function ensureUniqueId($wpdb, $length = 16) {
    $table_name = $wpdb->prefix . 'users';
    
    do {
        $unique_id = generateUniqueId($length);
        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name WHERE unique_id = %s",
            $unique_id
        ));
    } while ($exists > 0);

    return $unique_id;
}
?>