<?php

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

class FacebookAuth extends JBDAuth {
	private $appId;
	private $appSecret;

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

		$appSettings     = JBusinessUtil::getApplicationSettings();
		$this->appId     = $appSettings->facebook_client_id;
		$this->appSecret = $appSettings->facebook_client_secret;
	}

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

		$this->provider = new \League\OAuth2\Client\Provider\Facebook(array(
			'clientId'        => $this->appId,
			'clientSecret'    => $this->appSecret,
			'redirectUri'     => $this->redirectUri,
			'graphApiVersion' => 'v2.10',
		));
	}

	/**
	 * 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);
	}
}
