<?php
/*
Plugin Name: Import Users Plugin
Description: Adds a custom button to import predefined users and fetch user IDs.
Version: 1.1
Author: Your Name
*/

function add_import_users_button_to_nav() {
    add_menu_page(
        'Import Users',         // Page title
        'Import Users',         // Menu title
        'manage_options',       // Capability
        'import-users',         // Menu slug
        'import_users_callback', // Callback function
        'dashicons-admin-users' // Icon
    );
}
add_action('admin_menu', 'add_import_users_button_to_nav');

function import_users_callback() {
    if (isset($_POST['import_users'])) {
        import_predefined_users();
        echo '<div class="updated"><p>Users imported successfully!</p></div>';
    }

    if (isset($_POST['fetch_user_ids'])) {
        $user_ids = fetch_user_ids();
        echo '<div class="updated"><p>User IDs: ' . implode(', ', $user_ids) . '</p></div>';
    }

    echo '<div class="wrap">';
    echo '<h1>Import Users</h1>';
    echo '<form method="post" action="">';
    echo '<input type="hidden" name="import_users" value="true" />';
    echo '<p><input type="submit" value="Import Users" class="button button-primary" /></p>';
    echo '</form>';

    echo '<form method="post" action="">';
    echo '<input type="hidden" name="fetch_user_ids" value="true" />';
    echo '<p><input type="submit" value="Traer ID" class="button button-secondary" /></p>';
    echo '</form>';
    echo '</div>';
}

function import_predefined_users() {
    // Usuarios definidos en formato solicitado
    $users_data = [
['prestamito', '304390391','luisguillermoulti@instacredit.com'],
['prestamito', '186201548033','arelisulti@instacredit.com']

    ];

    foreach ($users_data as $user) {
        // $user[0] -> Contrase帽a, $user[1] -> Nombre de usuario, $user[2] -> Correo electr贸nico
        $password = $user[0];
        $username = $user[1];
        $email = $user[2];

        // Verifica si el usuario ya existe
        if (!username_exists($username) && !email_exists($email)) {
            // Crea el usuario
            $user_id = wp_create_user($username, $password, $email);

            if (!is_wp_error($user_id)) {
                // Asignar rol al usuario
                $user = get_user_by('id', $user_id);
                $user->set_role('subscriber');
            }
        }
    }
}

function fetch_user_ids() {
    global $wpdb;
    // Consulta para obtener todos los IDs de usuarios
    $user_ids = $wpdb->get_col("SELECT ID FROM {$wpdb->users} ORDER BY ID ASC");
    return $user_ids;
}
