<?php
include "../../mainfile.php";
require_once 'autoload.php';

$myfb_app_id = $_SESSION['fb_app_id'];
$myfb_app_secret = $_SESSION['fb_app_secret'];

$fb = new Facebook\Facebook([
  'app_id' => $myfb_app_id,
  'app_secret' => $myfb_app_secret,
  'default_graph_version' => 'v2.2',
  ]);
 // Replace {app-id} with your app id

  $helper = $fb->getRedirectLoginHelper();
  if (isset($_GET['state'])) {
     $helper->getPersistentDataHandler()->set('state', $_GET['state']);
  }



  try {
    $accessToken = $helper->getAccessToken();
  } catch(Facebook\Exceptions\FacebookResponseException $e) {
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
  } catch(Facebook\Exceptions\FacebookSDKException $e) {
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
  }

  if (! isset($accessToken)) {
    if ($helper->getError()) {
      header('HTTP/1.0 401 Unauthorized');
      echo "Error: " . $helper->getError() . "\n";
      echo "Error Code: " . $helper->getErrorCode() . "\n";
      echo "Error Reason: " . $helper->getErrorReason() . "\n";
      echo "Error Description: " . $helper->getErrorDescription() . "\n";
    } else {
      header('HTTP/1.0 400 Bad Request');
      echo 'Bad request';
    }
    exit;
  }

  // Logged in
//  echo '<h3>Access Token</h3>';
//  echo $accessToken . "<br />";


$myans = sprintf("%s",$accessToken);
$_SESSION['accesstoken'] = $myans;
setcookie('accesstoken', $myans);
//$mymsg = json_encode(array('ans'=> $myans, 'ans2'=> $myfb_app_secret));
echo $myans;

// Logged in
echo '<h3>Page ID</h3>';
var_dump($helper->getPageId());
