<?php
class javo_Addons_Google_Login
{
	private static $path;

	public static $instance;

	public function __construct()
	{
		self::$path		= dirname( __FILE__ ) . '/google-sign-in/';

		/* googleplus_oauth_redirect */{
			add_action(
				'wp_ajax_googleplus_oauth_redirect'
				, 'googleplus_oauth_redirect'
			);
			add_action(
				'wp_ajax_nopriv_googleplus_oauth_redirect'
				, 'googleplus_oauth_redirect'
			);
		}

		/* google_login_oauth */{
			add_action(
				'wp_ajax_nopriv_javo_ajax_google_login_oauth'
				, Array( __CLASS__, 'google_login_oauth' )
			);
			add_action(
				'wp_ajax_javo_ajax_google_login_oauth'
				, Array( __CLASS__, 'google_login_oauth' )
			);
		}

		/**/{
			add_action(
				'wp_ajax_googleplus_oauth_callback'
				, Array( __CLASS__, 'googleplus_oauth_callback' )
			);
			add_action(
				'wp_ajax_nopriv_googleplus_oauth_callback'
				, Array( __CLASS__, 'googleplus_oauth_callback' )
			);
		}
	}

	public static function get_google_element()
	{
		global $javo_tso;

		require_once self::$path . 'Google_Client.php';
		require_once self::$path . 'contrib/Google_Oauth2Service.php';

		$google_redirect_url		= add_query_arg( 'action', 'googleplus_oauth_callback', admin_url( 'admin-ajax.php' ) );
		$google_client_id			= $javo_tso->get( 'google_login_client_id' );
		$google_client_secret		= $javo_tso->get( 'google_login_client_secret' );
		$google_developer_key		= $javo_tso->get( 'google_login_api_key' );

		$gClient = new Google_Client();
		$gClient->setApplicationName('Login to Javo Theme');
		$gClient->setClientId($google_client_id);
		$gClient->setClientSecret($google_client_secret);
		$gClient->setRedirectUri($google_redirect_url);
		$gClient->setDeveloperKey($google_developer_key);
		$gClient->setScopes('email');

		return $gClient;
	}

	public static function google_login_oauth()
	{
		$gClient			= self::get_google_element();
		$google_oauthV2		= new Google_Oauth2Service( $gClient );
		print $authUrl = $gClient->createAuthUrl();
		die();
	}

	public static function googleplus_oauth_callback()
	{
		if( isset( $_GET['code'] ) ){
			self::jv_google_oauth_login($_GET);
		}else{
			if ( !is_user_logged_in() ) {
			 // wp_redirect(  home_url() );
			}
		}
	}

	public function exist_google_account( $google_id=0 ) {
		global $wpdb;
		$boolOutput = $wpdb->get_var(
			$wpdb->prepare("
				SELECT
					user_id
				FROM
					{$wpdb->usermeta}
				WHERE
					meta_key='_gaid'
				AND
					meta_value='%s'
				LIMIT 1;",
				$google_id
			)
		);
		return empty( $boolOutput ) ? false : intVal( $boolOutput );
	}

	public function login_trigger( $user_id ){
		$curUser	= new WP_User( $user_id );
		wp_set_current_user( $user_id );
		wp_set_auth_cookie( $user_id );
		do_action( 'wp_login', $curUser->user_login );
	}

	public function get_redirectURL( $user_ID=0, $args=Array() ) {
		$strRedirect		= javo_login_redirect_callback( false, false, get_userdata( $user_ID ) );
		if( empty( $strRedirect ) )
			$strRedirect	= home_url( '/' );
		return esc_url( add_query_arg( $args, $strRedirect ) );
	}

	public static function jv_google_oauth_login( $get_vars )
	{
		$objGA_EL	= self::get_google_element();
		$objGA_auth	= new Google_Oauth2Service( $objGA_EL );
		$code		= false;

		if( isset( $_GET['code'] ) ){
			$code	= wp_kses( $_GET['code'], Array() );
			$objGA_EL->authenticate($code);
		}

		if ( $code && $objGA_EL->getAccessToken() )
		{
			$arrArgs		= Array();
			$google_user	= $objGA_auth->userinfo->get();
			$user_id		= self::$instance->exist_google_account(
				wp_kses( $google_user['id'], Array() )
			);
			
			$obj_user		= new WP_User( $user_id );

			if( empty( $obj_user->ID ) ) {
				delete_user_meta( $obj_user->ID, '_gaid' );
				$user_id = $obj_user->ID;
			}

			// Cookie Clean
			wp_clear_auth_cookie();

			if( $user_id ) {
				// Login
				self::$instance->login_trigger( $user_id );
			}else{
				// Register
				$full_name	= wp_kses( $google_user['name'], Array() );
				$user_email	= sanitize_email( wp_kses( $google_user['email'], Array() ) );

				$user_id	= wp_insert_user(
					Array(
						'user_login'	=> sanitize_key( wp_kses( $google_user['email'], Array() ) ),
						'user_pass'		=> wp_generate_password(),
						'user_email'	=> sanitize_email( wp_kses( $google_user['email'], Array() ) ),
						'first_name'	=> wp_kses( $google_user['given_name'], Array() ),
						'last_name'		=> wp_kses( $google_user['family_name'], Array() ),
					)
				);

				if( is_wp_error( $user_id ) ){
					$arrArgs[ 'ga_err' ]	= $user_id->get_error_message();
				}else{
					update_user_meta( $user_id, '_gaid', wp_kses( $google_user['id'], Array() ) );
					self::$instance->login_trigger( $user_id );
				}
			}
			wp_redirect( self::$instance->get_redirectURL( $user_id, $arrArgs ) );
		}
	}
	public static function getInstance(){
		if( !self::$instance )
			self::$instance = new self;
		return self::$instance;
	}
}
javo_Addons_Google_Login::getInstance();