<?php
/*
 * @file
 * User has successfully authenticated with Twitter. Access tokens saved to session and DB.
 */

/* Load required lib files. */
session_start();
require_once('sql.php');
require_once('functions.php');
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');

/* If access tokens are not available redirect to connect page. */
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
    header('Location: ./clearsessions.php');
}
/* Get user access tokens out of the session. */
$access_token = $_SESSION['access_token'];

/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

/* If method is set change API call made. Test is called by default. */
$content = $connection->get('account/verify_credentials');

$img_original = str_replace("_normal", "", $content->profile_image_url);

$img_original = file_get_contents($img_original);
file_put_contents('user_img/'.$content->screen_name.'.jpg', $img_original);


make_img($content->screen_name);
insert_user($content->id_str,$content->name,$content->screen_name,$content->location,$content->description);



$_SESSION['tw_screen_name'] = $content->screen_name;
if(isset($_POST['submit']))
{
    $path = "user_img/".$content->screen_name.".png";
    $type = pathinfo($path, PATHINFO_EXTENSION);
    $data = file_get_contents($path);
    $img_base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
    $img_base64 = base64_encode($data);
    $change_profile = $connection->post('account/update_profile_image', array('image' => $img_base64));
    $msg = "Čestitamo!<br>Tvoj Twitter avatar je promenjen.";
    $content = $connection->post('statuses/update', array('status' => 'Promenom avatara podržavam #mojedojkesuOK Priključi se i ti! http://bit.ly/1g5LjWP'));
    echo "
    <script src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script> 
    <script>
    $(document).ready(function(){
        $('.btn').hide();
        $('.btn_above_text').hide();
    });
    window.setTimeout(function () {
        window.location.href = './clearsessions.php';
    }, 3000)
    </script>
";
}
include('home.php');
?>
