<?php

/**
 * register user
 */
function salesloo_user_register()
{
    if (!isset($_POST['user'])) {
        return new WP_Error('failed', __('Missing User fields', 'salesloo'));
    }

    $user = $_POST['user'];

    $required_fields = [
        'name'  => 'Full Name',
        'email' => 'Email',
        'pass'  => 'Password'
    ];

    foreach ((array)$required_fields as $field => $label) {
        if (!isset($user[$field]) || isset($user[$field]) && !$user[$field]) {
            return new WP_Error('failed', sprintf(__('Field "%s" is required and can\'t be empty', 'salesloo'), $label));
        }
    }

    $fullname = explode(' ', sanitize_text_field($user['name']));
    $fname    = $fullname[0];
    $lname    = str_replace($fname . ' ', '', sanitize_text_field($user['name']));
    $email    = sanitize_email($user['email']);
    $pass     = sanitize_text_field($user['pass']);

    $email = salesloo_user_check_email($email);

    if (is_wp_error($email)) {
        return $email;
    }

    $username = isset($user['username']) ? sanitize_user($user['username']) : false;
    if (false === $username || !$username) {
        $exploded_email = explode('@', $email);
        $email_domain   = array_pop($exploded_email);
        $username       = str_replace('@' . $email_domain, '', $email);
        $username       = sanitize_user($username);

        $is_exists = true;
        $i = 0;
        while ($is_exists) {
            if ($i > 0) {
                $username = $username . $i;
            }
            $is_exists = username_exists($username);
            $i++;
        }
    }

    if (username_exists($username)) {
        return new WP_Error('failed', __('This username already exists, please choose another username', 'salesloo'));
    }

    $user_id = wp_create_user($username, $pass, $email);

    if (!is_wp_error($user_id)) {
        foreach ((array)$required_fields as $field => $label) {
            unset($user[$field]);
        }

        $userdata = [
            'ID' => $user_id
        ];
        $userdata['first_name'] = $fname;
        $userdata['last_name']  = $lname;

        if (isset($user['phone'])) {
            $userdata['phone'] = $user['phone'];
        }
        wp_update_user($userdata);

        foreach ((array)$user as $key => $value) {
            $value = is_array($value) ? $value : sanitize_text_field($value);
            update_user_meta($user_id, sanitize_text_field($key), $value);
        }

        $data = [
            'user_id' => $user_id
        ];

        salesloo_add_notification('register', $data);
        salesloo_add_event('register', $data);
    }

    return $user_id;
}

/**
 * add phone contact method
 */
function salesloo_add_contact_methods($methods, $user)
{
    $methods['phone'] = __('Phone', 'salesloo');

    return $methods;
}
add_filter('user_contactmethods', 'salesloo_add_contact_methods', 10, 2);


/**
 * Check email
 *
 * @param  string $email
 * @return mixed
 */
function salesloo_user_check_email($email)
{
    $email = sanitize_text_field($email);
    if (!is_email($email)) {
        return new WP_Error('error', __('Email fields must be filled with a valid email', 'salesloo'));
    }

    if (email_exists($email)) {
        return new WP_Error('error', sprintf(__('"%s" has been registered, please loggedin with this email address or use another email address', 'salesloo'), $email));
    }

    return sanitize_email($email);
}

/**
 * get user full name
 *
 * @param  mixed $user
 * @return string
 */
function salesloo_user_get_name($user)
{
    if (is_int($user) || is_string($user)) :
        $user_id = intval($user);
        $user = get_userdata($user_id);
    endif;

    if (empty($user)) return '';

    $full_name = $user->first_name . ' ' . $user->last_name;
    if (empty($full_name)) {
        $full_name = $user->display_name;
    }

    return $full_name;
}

/**
 * prevent user to choose unallowed username
 *
 * @param  mixed $user_id
 * @param  string $username
 * @return mixed
 */
function salesloo_filter_username($user_id, $username)
{
    if ($user_id) return $user_id;

    $unallowed_username = ['guest', 'admin'];

    foreach ($unallowed_username as $key => $val) :
        if (strpos($username, $val) !== false)
            return true;
    endforeach;

    return $user_id;
}
add_filter('username_exists', 'salesloo_filter_username', 10, 2);

/**
 * salesloo_generate_guest_username
 *
 * @return string
 */
function salesloo_generate_guest_username()
{
    $guest_number = get_option('salesloo_guest_user_number', 0);
    $guest_number = intval($guest_number) + 1;

    $username = 'guest' . $guest_number;
    $username = apply_filters('salesloo/generate/guest/username', $username);
    update_option('salesloo_guest_user_number', $username);

    return $username;
}


/**
 * salesloo_get_guest_checkout_user
 *
 * @return bool
 */
function salesloo_get_guest_checkout_user()
{
    $cookie_name = 'salesloo_guest_checkout_id';

    if (isset($_COOKIE[$cookie_name]) && $_COOKIE[$cookie_name]) {
        return sanitize_text_field($_COOKIE[$cookie_name]);
    }

    return false;
}


function salesloo_get_current_checkout_username()
{
    $username = salesloo_get_guest_checkout_user();
    if (is_user_logged_in()) {
        $username = wp_get_current_user()->user_login;
    }

    return $username;
}
