<?php

require_once JPATH_SITE . '/components/com_jbusinessdirectory/libraries/vendor/autoload.php';

class GoogleAuth extends JBDAuth {
	private $googleClientId;
	private $googleClientSecret;

	public function __construct() {
		$this->type = 'google';
		parent::__construct();

		$appSettings              = JBusinessUtil::getApplicationSettings();
		$this->googleClientId     = $appSettings->google_client_id;
		$this->googleClientSecret = $appSettings->google_client_secret;
	}

	/**
	 * Initializes provider. Throws exception if client-id or client-secret is missing;
	 *
	 * @throws Exception
	 *
	 * @since 5.2.2
	 */
	public function initializeProvider() {
		if (empty($this->googleClientId) || empty($this->googleClientSecret)) {
			throw new Exception(JText::_('LNG_MISSING_CLIENT_DETAILS'));
		}

		$this->provider = new \League\OAuth2\Client\Provider\Google(array(
			'clientId'     => $this->googleClientId,
			'clientSecret' => $this->googleClientSecret,
			'redirectUri'  => $this->redirectUri,
			'accessType'   => 'offline',
		));
	}

	/**
	 * Get Access Token object by code
	 *
	 * @param $code string
	 *
	 * @return mixed
	 *
	 * @since 5.2.2
	 */
	public function getToken($code) {
		$token = $this->provider->getAccessToken('authorization_code', array(
			'code' => $_GET['code']
		));

		return $token;
	}

	/**
	 * Retrieves user details by access token
	 *
	 * @param $token object
	 *
	 * @return mixed
	 *
	 * @since 5.2.2
	 */
	public function getUserDetails($token) {
		$user = $this->provider->getResourceOwner($token);

		return $user;
	}

	/**
	 * Get state
	 *
	 * @return mixed
	 *
	 * @since 5.2.2
	 */
	public function getState() {
		return $this->provider->getState();
	}

	/**
	 * Get authorization URL of provider
	 *
	 * @param null $options
	 *
	 * @return mixed
	 *
	 * @since 5.2.2
	 */
	public function getAuthorizationUrl($options = null) {
		return $this->provider->getAuthorizationUrl($options);
	}
}
