<?php

if('sco_ajax'==get_class($this)):
	$client_id 		=  $this->get_option('envato_app_id','',true);
	$client_secret 	=  $this->get_option('envato_app_key','',true);
	//-----
	if(!class_exists('http_class'))			require( $path.'oauth-api/http.php');
	if(!class_exists('oauth_client_class'))	require( $path.'oauth-api/oauth_client.php');

	$client = new oauth_client_class;
	$client->debug = false;
	$client->debug_http = true;
	$client->oauth_version = '2.0';
	$client->dialog_url = 'https://api.envato.com/authorization?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&state={STATE}';
	$client->access_token_url = 'https://api.envato.com/token';
	$client->token_request_method = 'POST';
	//--
	$client->redirect_uri	= $redirect_uri;
	$client->client_id 		= $client_id;
	$client->client_secret	= $client_secret;

	if(strlen($client->client_id) == 0
	|| strlen($client->client_secret) == 0)
		$this->error_message( __('Settings error, network api credentials not set.','rhsco') );

	/* API permissions
	 */
	if(($success = $client->Initialize())){
		if(($success = $client->Process())){
			if(strlen($client->access_token)){
				$success_account = $client->CallAPI(
					'https://api.envato.com/v1/market/private/user/account.json',
					'GET', array(), array('FailOnAccessError'=>true), $data_account);
				$success_username = $client->CallAPI(
					'https://api.envato.com/v1/market/private/user/username.json',
					'GET', array(), array('FailOnAccessError'=>true), $data_username);
				$success_email = $client->CallAPI(
					'https://api.envato.com/v1/market/private/user/email.json',
					'GET', array(), array('FailOnAccessError'=>true), $data_email);
			}
		}
		$success = $client->Finalize($success);
	}
	if($client->exit)
		exit;
	if($success){
		$account_short = $data_account->account;
		$user = (object)array(
			'id'		=> $data_username->username,
			'username' 	=> $data_username->username,
			'name'		=> $account_short->firstname.' '.$account_short->surname,
			'first_name'=> $account_short->firstname,
			'last_name' => $account_short->surname,
			'email' 	=> $data_email->email
		);

		$SCO_Profile = new SCO_Profile( $network, (array)$user, $this->cb_get_option, true, true );
	}else{
		$this->error_message( sprintf( __('Error authenticating with social network: %s','rhsco'), HtmlSpecialChars($client->error) ) );
	}
else:
	$this->error_message( __('Settings error, cannot link directly to this file.', 'rhsco') );
endif; 
 

?>