<?php
/*!
* Details how to use users in a similar fashion to Hybridauth 2. Note that while Hybridauth 3 provides
* a similar interface to Hybridauth 2, both versions are not fully compatible with each other.
*/

include_once(ABSPATH . 'wp-includes/pluggable.php');
include 'library/hybridauth-master/src/autoload.php';

use Hybridauth\Hybridauth;
use Hybridauth\HttpClient;

$nbtSetting = get_option(NBT_SETTINGS);
$nbtFid = (isset($nbtSetting['nbt_facebook_setting']['nbt_facebook_app_id'])) ? $nbtSetting['nbt_facebook_setting']['nbt_facebook_app_id'] : '';
$nbtFsc = (isset($nbtSetting['nbt_facebook_setting']['nbt_facebook_app_secret'])) ? $nbtSetting['nbt_facebook_setting']['nbt_facebook_app_secret'] : '';
$nbtGid = (isset($nbtSetting['nbt_google_setting']['nbt_google_app_id'])) ? $nbtSetting['nbt_google_setting']['nbt_google_app_id'] : '';
$nbtGsc = (isset($nbtSetting['nbt_google_setting']['nbt_google_app_secret'])) ? $nbtSetting['nbt_google_setting']['nbt_google_app_secret'] : '';



class Check_Login
{
    public $config = [];
    public $adapter = null;
    public $tockens;
    public $providers;
    public $userProfile = null;

    public function __construct($login = 'Facebook')
    {
        $nbtSetting = get_option(NBT_SETTINGS);
        $nbtFid = (isset($nbtSetting['nbt_facebook_setting']['nbt_facebook_app_id'])) ? $nbtSetting['nbt_facebook_setting']['nbt_facebook_app_id'] : '';
        $nbtFsc = (isset($nbtSetting['nbt_facebook_setting']['nbt_facebook_app_secret'])) ? $nbtSetting['nbt_facebook_setting']['nbt_facebook_app_secret'] : '';
        $nbtGid = (isset($nbtSetting['nbt_google_setting']['nbt_google_app_id'])) ? $nbtSetting['nbt_google_setting']['nbt_google_app_id'] : '';
        $nbtGsc = (isset($nbtSetting['nbt_google_setting']['nbt_google_app_secret'])) ? $nbtSetting['nbt_google_setting']['nbt_google_app_secret'] : '';

        $this->config = [
            'callback' => HttpClient\Util::getCurrentUrl().'?login='.$login,
//            'callback' =>'http://192.168.9.175.xip.io/functional-food/index.php?login='.$login,

            'providers' => [
                'GitHub' => [
                    'enabled' => true,
                    'keys'    => [ 'id' => '', 'secret' => '319556071740553' ],
                ],

                'Google' => [
                    'enabled' => true,
                    'keys'    => [ 'id' => $nbtGid, 'secret' => $nbtGsc ],
                ],

                'Facebook' => [
                    'enabled' => true,
                    'keys'    => [ 'id' => $nbtFid, 'secret' => $nbtFsc ],
                ],

                'Twitter' => [
                    'enabled' => true,
                    'keys'    => [ 'key' => '', 'secret' => '' ],
                ]
            ],


        ];
        $arrMatch = [
            'facebook' => 'Facebook',
            'google'   => 'Google'
        ];

        if (array_key_exists($login, $arrMatch)) {
            $this->providers = $arrMatch[$login];
            $this->hybridAuth();
        }else{
            exit();
        }

    }


    public function hybridAuth()
    {
        try {
            $hybridauth = new Hybridauth($this->config);

            // $adapter = $hybridauth->authenticate( 'GitHub' );
            // $adapter = $hybridauth->authenticate( 'Google' );
            $adapter = $hybridauth->authenticate($this->providers);
            // $adapter = $hybridauth->authenticate( 'Twitter' );

            $tokens = $adapter->getAccessToken();
            $userProfile = $adapter->getUserProfile();

            $this->adapter = $adapter;
            $this->userProfile = $userProfile;
            $this->tockens = $tokens;

            $adapter->disconnect();

        }
        catch (\Exception $e) {
            echo $e->getMessage();
            die();
        }
    }

    public function nbt_check_login()
    {
        if (isset($this->userProfile)) {
            global $wpdb;

            $identifier = $this->userProfile->identifier;
            $sql = "SELECT *  FROM  `{$wpdb->prefix}nbt_users_social_profile_details` WHERE  `provider_name` LIKE  '$this->providers' AND `identifier` LIKE '$identifier'";
            $row = $wpdb->get_row($sql);

//            echo '<pre>'; print_r($row); echo '</pre>'; die();
            if (!$row) {
                $userDetailByEmail = null;

                // Get user in table user of wp
                if (isset($this->userProfile->email)) {
                    $userDetailByEmail = get_user_by('email', $this->userProfile->email);
                }

                /**
                 * @desc: check user have in table user  wordpress
                 *          + if have user then check user have in table nbt_user.
                 */
                if (isset($userDetailByEmail)) {

                    $id = $userDetailByEmail->ID;
                    $sql = "SELECT *  FROM  `{$wpdb->prefix}nbt_users_social_profile_details` WHERE  `user_id` LIKE  '$id'; ";
                    $row = $wpdb->get_row($sql);

                    /**
                     * desc : check if use not in table nbt_user then updete
                     */
                    if (!$row) {
                        $this->nbt_link_user_facebook($id);
                    }
                    $this->nbt_login_user($id);
                }

                // if not user in table user wp then create new
                $newUserId = $this->nbt_create_user();
                $this->update_user_meta($newUserId);
                $this->nbt_login_user($newUserId);
                exit();
            }

            $this->nbt_login_user($row->id);

        }
    }

    public function update_user_meta($id)
    {
        $firstName = (isset($this->userProfile->firstName)) ? sanitize_text_field($this->userProfile->firstName) : '';
        $lastName = (isset($this->userProfile->lastName)) ? sanitize_text_field($this->userProfile->lastName) : '';
        $description = (isset($this->userProfile->description)) ? sanitize_text_field($this->userProfile->description) : '';
        $email = (isset($this->userProfile->email)) ? sanitize_text_field($this->userProfile->email) : '';
        $gender = (isset($this->userProfile->gender)) ? sanitize_text_field($this->userProfile->gender) : '';
        $profileUrl = (isset($this->userProfile->profileURL)) ? sanitize_text_field($this->userProfile->profileURL) : '';
        $displayName = (isset($this->userProfile->displayName)) ? sanitize_text_field($this->userProfile->displayName) : $firstName . ' ' . $lastName;


        update_user_meta( $id, 'email', $email );
        update_user_meta( $id, 'first_name', $firstName );
        update_user_meta( $id, 'last_name', $lastName);
        update_user_meta( $id, 'billing_first_name', $firstName );
        update_user_meta( $id, 'billing_last_name', $lastName );
        update_user_meta( $id, 'description', $description );
        update_user_meta( $id, 'sex', $gender );
        wp_update_user( array(
            'ID' => $id,
            'display_name' => $displayName,
            // 'role' => $role,
            'user_url' => $profileUrl
        ) );

        $this->nbt_link_user_facebook($id);
        return;

    }

    public function nbt_create_user()
    {
        $username = $this->get_username($this->userProfile->displayName);
        $random_password = wp_generate_password( 12, false );
        $email = $this->userProfile->email;
        require_once WP_PLUGIN_DIR . '/woocommerce/includes/wc-user-functions.php';
        $user_id = wc_create_new_customer($email, $username, $random_password);

        return $user_id;
    }

    public function get_username($user_name){
        $username = $user_name;
        $i = 1;
        while(username_exists( $username )){
            $username = $user_name.'_'.$i;
            $i++;
        }
        return $username;
    }

    public function nbt_link_user_facebook($id)
    {
        global $wpdb;
        $nbtUserdetails = "{$wpdb->prefix}nbt_users_social_profile_details";

        $firstName = (isset($this->userProfile->firstName)) ? sanitize_text_field($this->userProfile->firstName) : '';
        $lastName = (isset($this->userProfile->lastName)) ? sanitize_text_field($this->userProfile->lastName) : '';
        $profileUrl = (isset($this->userProfile->profileURL)) ? sanitize_text_field($this->userProfile->profileURL) : '';
        $photoUrl = (isset($this->userProfile->photoURL)) ? sanitize_text_field($this->userProfile->photoURL) : '';
        $displayName = (isset($this->userProfile->displayName)) ? sanitize_text_field($this->userProfile->displayName) : '';
        $description = (isset($this->userProfile->description)) ? sanitize_text_field($this->userProfile->description) : '';
        $email = (isset($this->userProfile->email)) ? sanitize_text_field($this->userProfile->email) : '';
        $identifier = (isset($this->userProfile->identifier)) ? sanitize_text_field($this->userProfile->identifier) : '';
        $gender = (isset($this->userProfile->gender)) ? sanitize_text_field($this->userProfile->gender) : '';

        $tableName = $nbtUserdetails;
        $submitArr = array(
            "user_id"        => $id,
            "provider_name"  => $this->providers,
            "identifier"     => $identifier,
            "email"          => $email,
            "first_name"     => $firstName,
            "last_name"      => $lastName,
            "profile_url"    =>$profileUrl,
            "photo_url"      =>$photoUrl,
            "display_name"   =>$displayName,
            "description"    =>$description,
            "gender"         =>$gender
        );

        $wpdb->insert($tableName, $submitArr);

        return;

    }


    public function nbt_login_user($id = null)
    {
        $urlHome = get_home_url();
        wp_redirect($urlHome);
        exit();
    }

}


$checkLogin = new Check_Login($login);

if (isset($checkLogin->adapter)) {
    $checkLogin->nbt_check_login();

}


