<?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;
use GuzzleHttp\Client;

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['SOCIAL_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" ) ) );

} elseif (!empty($_GET) && isset($_SESSION['SOCIAL_AUTH_STATE']) && isset($_SESSION['SOCIAL_LOGIN_DOMAIN'])) {

    if($_GET['state'] != $_SESSION['SOCIAL_AUTH_STATE']) {
        exit("Invalid state, state mismatch. Aborting.");
    }

    $login_domain = $_SESSION['SOCIAL_LOGIN_DOMAIN'];
    $base_uri = "https://$login_domain";
    $client = new Client([
        'base_uri' => $base_uri,
        'timeout'  => 2.0,
    ]);

    //get token
    $client_ids = get_cached_app_ids($login_domain, $rep, $appCacheHandle);

    $client_id = $client_ids["client_id"];
    $client_secret = $client_ids["client_secret"];

    if(!$client_id || !$client_secret) {
        exit("Invalid app cache. Aborting.");
    }

    $token_resp = $client->post("/oauth/token", ['form_params' => [
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'redirect_uri' => URL_ROOT . "callback.php?rep=$rep",
        'grant_type' => 'authorization_code',
        'code' => $_GET['code'],
        'scope' => 'read write push',
    ]]);
    $body = $token_resp->getBody();
    $token_ent = json_decode($body, true);

    $_SESSION['SOCIAL_ACCESS_TOKEN'] = serialize($token_ent['access_token']);
    $_SESSION['SOCIAL_AUTH_STATE'] = null;

    header('Location: ' . ( URL_ROOT . "$rep/client.php" ) );

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