<?php

/**
 * Helper for Google integration.
 */
class Tapatalk_Provider_TapatalkOauth2Provider extends XenForo_ControllerHelper_Abstract
{
	public $provider = 'tapatalk';
	public $tokenUrl = 'https://search-chao.tapatalk.com/oauth/access_token';
	public $authUrl = 'http://stage.tapatalk.com/oauth';
	public $profileUrl = 'https://search-chao.tapatalk.com/oauth/resource';
	public $scope = 'profile email';
  
    public $id;
	public $secret;
    protected function _constructSetup()
	{
		$options = XenForo_Application::getOptions();
		$this->id = self::tt_get_board_url();
		$this->secret = $options->get('tp_push_key');

		if (!$this->id || !$this->secret)
		{
			throw $this->_controller->responseException(
				$this->_controller->responseMessage(new XenForo_Phrase('tapatalk_provider_not_properly_configured'))
			);
		}
	}
    protected static function tt_get_board_url(){
        $request = new Zend_Controller_Request_Http();
        $getScheme = $request->getScheme();
        $getHttpHost = $request->getHttpHost();
        $getBasePath = $request->getBasePath();
        if (!empty($getScheme) && !empty($getHttpHost)){
            return $getScheme . '://' . $getHttpHost . $getBasePath;
        } else {
            return XenForo_Application::get('options')->boardUrl;
        }
    }
    /**
     * Takes a code (with a redirect URL) and gets an access token.
     *
     * @param string $url
     * @param string $code
     *
     * @return array|false Array of info (may be error); false if Provider integration not active
     */
	public function getAccessToken($redirectUri)
	{
		if (!$code = $this->_controller->getInput()->filterSingle('code', XenForo_Input::STRING))
		{
			throw $this->_controller->responseException(
				$this->_controller->responseMessage(new XenForo_Phrase('tapatalk_invalid_authorization_code'))
			);
		}

		try
		{
			$client = XenForo_Helper_Http::getClient($this->tokenUrl);

			$client->setParameterPost(array(
				'client_id' => $this->id,
				'client_secret' => $this->secret,
		    	'redirect_uri' => $redirectUri,
				'code' => $code,
				'grant_type' => 'authorization_code',
			));

			$body = $client->request('POST')->getBody();

			if (preg_match('#^[{\[]#', $body))
			{
				$parts = json_decode($body, true);
			}
			else
			{
				$parts = XenForo_Application::parseQueryString($body);
			}

			return $parts;
		}
		catch (Zend_Http_Client_Exception $e)
		{
			throw $this->_controller->responseException(
				$this->_controller->responseError($e->getMessage())
			);
		}
	}


	public function isValidToken($token)
	{
		return !empty($token['access_token']);
	}

	public function getAuthorizeUrl($redirectUri)
	{
		return $this->authUrl
			. '?client_id=' . urlencode($this->id)
			. '&scope=' . urlencode($this->scope)
			. '&state=profile'
			. '&redirect_uri=' . urlencode($redirectUri)
			. '&response_type=code';
	}
    public function authenticate($redirectUri = null)
	{
		$token = $this->getAccessToken($redirectUri);

		if (!$this->isValidToken($token))
		{
			throw $this->_controller->responseException(
				$this->_controller->responseError(new XenForo_Phrase('tapatalk_invalid_access_token'))
			);
		}

		$this->token = $token;
		return $token;
	}

	public function getProfile($authId = null)
	{
		$client = XenForo_Helper_Http::getClient($this->profileUrl);
		$client->setParameterGet('scope', $this->scope);
		if (isset($this->token['access_token']))
			$client->setParameterGet('access_token', $this->token['access_token']);

		$response = json_decode($client->request('GET')->getBody(), true);
        if(isset($response['status']) && $response['status'])
        {
            return array(
                'auth_id' => isset($response['data']['basic']['id']) ? $response['data']['basic']['id'] : 0,
                'username' => isset($response['data']['basic']['username']) ? $response['data']['basic']['username'] : '',
                'email' => isset($response['data']['basic']['email']) ? $response['data']['basic']['email'] : '',
                'profile' => $response['data']['profile']
            );
        }
	}

	public function getPermanentUserInfo(array $profile)
	{
		return array(
			'email' => isset($profile['email']) ? $profile['email'] : '',
		);
	}
}