<?
require_once('../config.php');
require_once('lib/db.php');
require_once('lib/socnetauth.php');
session_start();

$SocAuth = new SocAuth();

if( !$SocAuth->get_config_param('socnetauth_status') )
{
	header("Location: ".$_SERVER['HTTP_REFERER']);
	exit();
}


$IS_DEBUG = 0;

if( !empty($_GET['first']) )
{
	$APP_ID = $SocAuth->get_config_param('socnetauth_vkontakte_appid');
	$CURRENT_URI = $_SERVER['HTTP_REFERER'];
	$REDIRECT_URI = 'http://'.$_SERVER['HTTP_HOST'].'/socnetauth/vkontakte.php';
		
	$STATE = 'vkontakte_socnetauth_'.rand();
	$SocAuth->setRecord($STATE, $CURRENT_URI);

	setcookie("vk_state", $STATE);
	
	$url = 'https://oauth.vk.com/authorize?client_id='.$APP_ID.
		'&scope=SETTINGS'.
		'&redirect_uri='.$REDIRECT_URI.
		'&display=page&'.
		'response_type=code';
	
	header("Location: ".$url);
}


if( !empty( $_GET['code'] ) && !empty( $_COOKIE['vk_state'] ) &&
	$recordData = $SocAuth->getRecord( $_COOKIE['vk_state'] ) )
{


	$CODE = $_GET['code'];
	
	$CURRENT_URI = $recordData['redirect'];
	$REDIRECT_URI = 'http://'.$_SERVER['HTTP_HOST'].'/socnetauth/vkontakte.php';
	
	
	$CLIENT_ID = $SocAuth->get_config_param('socnetauth_vkontakte_appid');
	$CLIENT_SECRET = $SocAuth->get_config_param('socnetauth_vkontakte_appsecret');
	
	$url = "https://oauth.vk.com/access_token?client_id=".$CLIENT_ID.
		   "&client_secret=".$CLIENT_SECRET.
		   "&code=".$CODE.'&redirect_uri='.$REDIRECT_URI.'&';
		   
	if( $IS_DEBUG ) echo $url."<hr>";
			
	
	if( extension_loaded('curl') )
	{
		$c = curl_init($url);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
		$response = curl_exec($c);
		curl_close($c);
	}
	else
	{
		$response = file_get_contents($url);
	}
			
	
	if( $IS_DEBUG ) echo $response."<hr>";
	
	$data = json_decode($response, true);
	
	if( !empty($data['access_token']) )
	{
		$graph_url = "https://api.vk.com/method/users.get?uids=".$data['user_id'].
		"&fields=uid,first_name,last_name,city,country&access_token=".$data['access_token'];
		
		if( $IS_DEBUG ) echo $graph_url."<hr>";
		
		if( extension_loaded('curl') )
		{
			$c = curl_init($graph_url);
			curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
			$json = curl_exec($c);
			curl_close($c);
		}
		else
		{
			$json = file_get_contents($graph_url);
		}
		
		if( $IS_DEBUG ) echo $json;
		$userdata = json_decode($json, TRUE);
				
		if( $customer = $SocAuth->vkontakte_check($userdata['response'][0]['uid']) )
		{			
			$_SESSION['customer_id'] = $customer['customer_id'];
					
			if( $IS_DEBUG ) exit('RES1|'.$REDIRECT_URI);
					
			header("Location: ".$CURRENT_URI ); 
		}
		else
		{
			$precode = $SocAuth->vkontakte_preregistration($userdata['response'][0]);
				
			if( $IS_DEBUG ) exit('RES2');
			
			header('Location: /index.php?route=socnetauth/registration&precode='.$precode.'&redirect_uri='.urlencode($CURRENT_URI) ); 
		}
	}
}

?>