<?php
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');

include_once 'common.php';
use Abraham\TwitterOAuth\TwitterOAuth;

if(!isset($_REQUEST['rep'])) {
    $rep = $C_default_rep;
}
else {
    $rep = $_REQUEST['rep'];
}


if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {


    $token = unserialize($_SESSION['TWITTER_REQUEST_TOKEN']);

    if (isset($_REQUEST['oauth_token']) && $token['oauth_token'] !== $_REQUEST['oauth_token']) {
        exit('Invalid callback request. Oops. Sorry.');
    }

    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token['oauth_token'], $token['oauth_token_secret']);
    $access_token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_REQUEST['oauth_verifier']]);

    $_SESSION['TWITTER_ACCESS_TOKEN'] = serialize($access_token);

    /**
     * Now that we have an Access Token, we can discard the Request Token
     */
    $_SESSION['TWITTER_REQUEST_TOKEN'] = null;

    /**
     * With Access Token in hand, let's try accessing the client again
     */
    header('Location: ' . ( isset($_SESSION['TWITTER_REDIRECT_URL']) ? $_SESSION['TWITTER_REDIRECT_URL'] : ( URL_ROOT . "$rep/client.php" ) ) );

} else {
    /**
     * Mistaken request? Some malfeasant trying something?
     */
    exit('Invalid callback request. Oops. Sorry.');
}
