<?php
require_once 'google-api-php-client/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/google_calendar/oauth2callback.php');
//$client->setRedirectUri('http://backend.snapcafe.me/google_calendar//oauth2callback.php');
$client->addScope('https://www.googleapis.com/auth/calendar');
$client->addScope('https://www.googleapis.com/auth/calendar.events');
$client->setState($_SESSION['userToken']);
$client->setAccessType("offline");

if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
  //header('Location: ' . $auth_url);
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  header("Location: google_events.php?state=".$_GET['state']);
  //$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  //header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>