<?php
session_start();

require_once('../config.php');
require_once('lib/db.php');
require_once('lib/socnetauth.php');
require_once('lib/twitter/twitteroauth.php');

$SocAuth = new SocAuth();

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


$IS_DEBUG = 0;

$CONSUMER_KEY = $SocAuth->get_config_param('socnetauth_twitter_consumer_key');
$CONSUMER_SECRET = $SocAuth->get_config_param('socnetauth_twitter_consumer_secret');
$CALLBACK_URL = 'http://'.$_SERVER['HTTP_HOST'].'/socnetauth/twitter.php';

/** Здесь необходимо подставить значения своего приложения */  
define("CONSUMER_KEY", $CONSUMER_KEY);
define("CONSUMER_SECRET", $CONSUMER_SECRET);
define("CALLBACK_URL", $CALLBACK_URL);


if( empty($_REQUEST['oauth_token']) )
{
    $twitteroauth = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET);    
    $request_token = $twitteroauth->getRequestToken($CALLBACK_URL);
    
    $_SESSION['oauth_token'] = $request_token['oauth_token'];  
    $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];  
    
	$STATE = md5($request_token['oauth_token'].$request_token['oauth_token_secret']);
	
	$SocAuth->setRecord($STATE, $_SERVER['HTTP_REFERER']);
	
    if($twitteroauth->http_code==200){  
        $url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);     
        header('Location: '. $url); 
    } else {          
        die('Something wrong happened.');  
    }  

}
elseif( $recordData = $SocAuth->getRecord( md5($_SESSION['oauth_token'].$_SESSION['oauth_token_secret']) ) ) 
{
    $twitteroauth = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
    $access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);      
    $_SESSION['access_token'] = $access_token; 
    $userdata = $twitteroauth->get('account/verify_credentials');
    
	$CURRENT_URI = $recordData['redirect'];
	
	
	if( $customer = $SocAuth->twitter_check( $userdata->id ) )
	{
		$_SESSION['customer_id'] = $customer['customer_id'];
					
		if( $IS_DEBUG ) exit('RES1|');
				
		header("Location: ".$CURRENT_URI ); 
	}
	else
	{
		$precode = $SocAuth->twitter_preregistration($userdata);
				
		if( $IS_DEBUG ) exit('RES2');
			
		header('Location: /index.php?route=socnetauth/registration&precode='.$precode.'&redirect_uri='.urlencode($CURRENT_URI) ); 
	}
	
    print_r($user_info);    
}