<?php

if (!defined('ABSPATH')) {
    exit;
}


function digits_show_social_login()
{
    if (is_user_logged_in()) {
        return;
    }

    $social_settings = get_option('digits_option_social_settings');

    if (empty($social_settings)) {
        return;
    }

    $social_list = digits_socials_list();
    $icon_only = !empty($social_settings['enable_social_icon']);
    $use_text = false;
    ?>
    <div class="digits-social-logins-box digits-append_last <?php if ($icon_only) echo 'digits-social-icon-only_box'; ?>">
        <div class="digits-social-logins <?php if ($icon_only) echo 'digits-social-icon-only'; ?>">
            <?php
            foreach ($social_settings as $social_key => $social_setting) {
                if (!empty($social_setting['enable']) && $social_setting['enable'] == 1) {
                    $social_info = $social_list[$social_key];
                    $loader = $social_info['loader'];
                    $class = "Digits\SocialLogin\Auths\\$loader";
                    $load = new $class($social_setting, $social_info, $icon_only);
                    $load->render();
                    $use_text = true;
                }
            }
            ?>
        </div>
        <?php
        if ($use_text) {
            ?>
            <div class="digits-use_social-logins">
                <span><?php esc_attr_e('Or Use Social', 'digits'); ?></span>
            </div>
            <?php
        }
        ?>
    </div>
    <?php
}

add_action('login_form', 'digits_show_social_login', 100);
add_action('woocommerce_login_form_end', 'digits_show_social_login', 100);


/**
 * @param string $name The user's name
 * @param string $email The user's email
 * @param string $auth login method used, ex: google
 * @throws Exception
 */
function digits_social_create_user($name, $email, $auth, $username = "", $social_id = '')
{
    $user_email = '';

    if (!isValidEmail($email)) {
        $email = '';
    }

    $auth_id_key = "auth_{$auth}_id";

    $user_id = false;

    if (!empty($social_id)) {
        global $wpdb;
        $sql = "SELECT user_id FROM {$wpdb->usermeta} where meta_value = '%s' and meta_key = '%s'";
        $user_id = $wpdb->get_row($wpdb->prepare($sql, $social_id, $auth_id_key), 'ARRAY_A');
    }

    $update_id = true;
    if (!empty($user_id)) {
        $update_id = false;
        $user_id = $user_id['user_id'];
        $user = get_user_by('ID', $user_id);
    } else {
        $update_id = true;
        if (!empty($email)) {
            $user = get_user_by('email', $email);
        }

        if (empty($user)) {
            $pass = wp_generate_password();

            $username = digsocial_get_username($username, $email, $name);

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

            if ($user_id instanceof WP_Error) {
                throw new Exception($user_id->get_error_message());
            }

            $default_userrole = get_option('defaultuserrole', "customer");
            wp_update_user(array(
                'ID' => $user_id,
                'role' => $default_userrole,
                'display_name' => $name
            ));

            do_action('register_new_user', $user_id);

        }
    }

    if ($update_id) {
        if (!empty($social_id)) {
            update_user_meta($user->ID, $auth_id_key, $social_id);
        }
    }


    if (empty($user)) {
        throw new Exception('Error');
    }

    wp_set_current_user($user->ID, $user->user_login);
    wp_set_auth_cookie($user->ID, false);
    return array('success' => true);
}


function digsocial_get_username($username, $email, $name)
{
    $useMobAsUname = get_option('dig_mobilein_uname', 0);

    if (empty($username)) {
        if ((!empty($name) || !empty($email)) && $useMobAsUname == 0) {
            if (!empty($name)) {
                $username = digits_filter_username($name);
            } else if (!empty($email)) {
                $username = strstr($email, '@', true);
            }
        } else {
            $username = apply_filters('digits_username', '');
        }
    }

    if (empty($username)) {
        $username = $name;
    }

    if (empty($username)) {
        $username = strstr($email, '@', true);
    }

    if (empty($username)) {
        throw new Exception(__('Error while generating user login!', 'digit'));
    }
    $check = username_exists($username);
    if (!empty($check)) {
        $suffix = 1;
        while (!empty($check)) {
            $username_temp = $username . $suffix;
            $check = username_exists($username_temp);
            $suffix++;
        }
        $username = $username_temp;
    }

    return $username;
}