<?php
/**
 * GoogleProcessLogin class.
 *
 * @since 2.7.0
 */

namespace Masteriyo\Addons\SocialLogin;

defined( 'ABSPATH' ) || exit;


use League\OAuth2\Client\Provider\Google;
use Masteriyo\Addons\SocialLogin\Setting;

class GoogleProcessLogin {

	/**
	 * Initialization.
	 *
	 * @since 2.7.0
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'init', array( __CLASS__, 'process' ) );
	}

	/**
	 * Process the google login request and  logs in the user to home location.
	 *
	 * @since 2.7.0
	 *
	 */
	public static function process() {
		if ( ! self::is_google_login_path() || ! isset( $_GET['code'] ) ) {//phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return;
		}
		$setting = new Setting();
		$setting->init();
		$google_database_info = $setting->get( 'google' );

		$provider = self::create_google_client( $google_database_info );

		if ( isset( $_GET['code'] ) ) {//phpcs:ignore WordPress.Security.NonceVerification.Recommended
			self::handle_google_response( $provider );
		}
	}

	/**
	 * sees if user is login using google
	 *
	 * @since 2.7.0
	 *
	 * updated
	 * @since 2.17.0
	 */
	private static function is_google_login_path() {
		$request_path = trim( parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ), '/' );
		if ( strpos( $request_path, 'masteriyo-google-login' ) !== false ) {
			return true;
		}

		return false;
	}

	/**
	 * create a instance of google client
	 *
	 * @since 2.7.0
	 */
	private static function create_google_client( $google_database_info ) {
		$provider = new Google(
			array(
				'clientId'     => $google_database_info['client_id'],
				'clientSecret' => $google_database_info['secret_key'],
				'redirectUri'  => masteriyo_get_social_login_redirect_url( 'masteriyo-google-login' ),
				'scopes'       => array( 'openid', 'email', 'profile' ),
			)
		);
		return $provider;
	}

	/**
	 * Handle google response on the user data on the basis of existing database info
	 *
	 * @param \League\OAuth2\Client\Provider\Google; $provider The new provider object.
	 * @since 2.7.0
	 *
	 */
	private static function handle_google_response( $provider ) {
		$code         = isset( $_GET['state'] ) ? $_GET['code'] : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$role         = 'masteriyo_student'; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$access_token = $provider->getAccessToken(
			'authorization_code',
			array(
				'code' => $code,
			)
		);

		if ( ! $access_token ) {
			return 'Error: No access token.';
		}

		if ( $access_token ) {
			$resource_owner = $provider->getResourceOwner( $access_token );
			$email          = $resource_owner->getEmail();
			$name           = strstr( $email, '@', true );

			$firstname     = $resource_owner->getFirstName();
			$lastname      = $resource_owner->getLastName();
			$profile_image = $resource_owner->getAvatar();

			$user = get_user_by( 'email', $email );

			if ( $user ) {
				masteriyo_set_customer_auth_cookie( $user->ID );
				$page = masteriyo_get_setting( 'general.pages.account_page_id' );
				if ( $page ) {
					wp_redirect( get_permalink( $page ) );
					exit;
				} else {
					wp_redirect( home_url( '/' ) );
					exit;
				}
			}

			/** @var Masteriyo\Database\Model $user */
			$user = masteriyo( 'user' );
			$user->set_username( $name );
			$user->set_password( '' );
			$user->set_email( $email );
			$user->set_first_name( $firstname );
			$user->set_last_name( $lastname );
			$user->set_roles( $role );
			$user_id = $user->save();

			if ( is_wp_error( $user_id ) ) {
				wp_die( esc_html( $user_id->get_error_message() ) );
			}
			wp_set_auth_cookie( $user_id, true );
			$page = masteriyo_get_setting( 'general.pages.account_page_id' );
			if ( $page ) {
				wp_redirect( get_permalink( $page ) );
				exit;
			} else {
				wp_redirect( home_url( '/' ) );
				exit;
			}
		}
	}
}
