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

session_start();

if(isset($_GET['token']) && $_GET['token']) {
$_SESSION['userToken'] = $_GET['token'];
}

$login = false;

header("Access-Control-Allow-Origin: *");

$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->addScope('https://www.googleapis.com/auth/calendar');
$client->addScope('https://www.googleapis.com/auth/calendar.events');
$client->setAccessType("offline");

$userTokenGoogle = "";

if (isset($_SESSION['access_token']) && $_SESSION['access_token']
    && isset($_GET['state']) && $_GET['state']) {

    include("connection.php");
    $requests = array();

    $sql = "update users set google_token = '".json_encode($_SESSION['access_token'])."' where token ='".$_GET['state']."'";

    if ($conn->query($sql) === TRUE) {
        $client->setAccessToken($_SESSION['access_token']);
        session_destroy();
    }
    else
    {
        return "ERROR";
    }
    $conn->close();

    $login = true;



} else if(isset($_GET['token']) && $_GET['token']) {

    include("connection.php");
    $requests = array();

    $sql = "SELECT google_token FROM users
            WHERE token = '" . $_GET['token'] . "'";

    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {

            if($row['google_token']) {
                $client->setAccessToken($row['google_token']);
                if ($client->isAccessTokenExpired()) {

                    $newAccessToken = $client->refreshToken($client->getRefreshToken());

                    $sql = "update users set google_token = '".json_encode($newAccessToken)."' where token ='".$_GET['token']."'";

                    if ($conn->query($sql) === TRUE) {
                        $client->setAccessToken($newAccessToken);
                    }
                    else
                    {
                        return "ERROR";
                    }
                }
            }
        }
    } else {
        echo "ERROR";
    }



    $conn->close();

}

if ($client->getAccessToken()) {
//if(isset($_SESSION['access_token']) && $_SESSION['access_token']){

    $service = new Google_Service_Calendar($client);

    $eventsResult = new \stdClass;

    if (empty($service->events)) {
        $eventsResult->events = [];
        echo $eventsResult;
    } else {

        // Print the next 10 events on the user's calendar.
        $calendarId = 'primary';
        $optParams = array(
            'maxResults' => 1000000000,
            'orderBy' => 'startTime',
            'singleEvents' => true,
            'timeMin' => date('c'),
        );
        $results = $service->events->listEvents($calendarId, $optParams);
        $events = $results->getItems();

        $eventsArray = array();
        foreach ($events as $event) {

            $eventsJSON = new \stdClass;
            $eventsJSON->starts_at = $event->start->dateTime ? $event->start->dateTime : $event->start->date;
            $eventsJSON->ends_at = $event->end->dateTime ? $event->end->dateTime : $event->end->date;
            $eventsJSON->title = $event->summary;
            array_push($eventsArray,$eventsJSON);
        }

        $eventsResult->events = $eventsArray;

        echo json_encode($eventsResult);

        if($login) {
            $redirectUrlHrflo = "http://employee.snapcafe.me/calendar";
            ?>
            <meta http-equiv="refresh" content="0;URL='<?php echo $redirectUrlHrflo; ?>'" />
            <?php
        }

    }




    // add event
    /*$event = new Google_Service_Calendar_Event(array(
      'summary' => 'Google I/O 2015',
      'start' => array(
        'dateTime' => '2015-05-28T09:00:00-07:00',
        'timeZone' => 'America/Los_Angeles',
      ),
      'end' => array(
        'dateTime' => '2015-05-28T17:00:00-07:00',
        'timeZone' => 'America/Los_Angeles',
      ),
    ));

    $calendarId = 'primary';
    $event = $service->events->insert($calendarId, $event);
    printf('Event created: %s\n', $event->htmlLink);*/
    // add event
} else {
    //header("Location: oauth2callback.php");
    $redirect_uri = 'oauth2callback.php';
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

?>