<?php
require_once 'vendor/autoload.php'; 
use Webklex\PHPIMAP\ClientManager;
use Webklex\PHPIMAP\Client;

// Make sure that the IEM controller does NOT redirect request.
if (!defined('IEM_NO_CONTROLLER')) {
	define('IEM_NO_CONTROLLER', true);
}

// Displaying an archive does not need a session to be started.
if (!defined('IEM_NO_SESSION')) {
	define('IEM_NO_SESSION', true);
}

// Require base sendstudio functionality. This connects to the database, sets up our base paths and so on.
require_once dirname(__FILE__) . '/admin/index.php';

if (SENDSTUDIO_IS_SETUP != 1) {
	exit;
}

/**
* This file lets us get api's, load language files and parse templates.
*/
require_once(SENDSTUDIO_FUNCTION_DIRECTORY . '/sendstudio_functions.php');

$sendstudio_functions = new Sendstudio_Functions();

 //$fullUrl = $_SERVER['REQUEST_URI'];

// Parse the URL to get the fragment
//$urlParts = parse_url($fullUrl);
//$fragment = isset($urlParts['response_type']) ? $urlParts['response_type'] : '';
// Create a new Google_Client instance
 //print_r($urlParts) ;exit;
// If the user is not authenticated, redirect them to Google's authentication page
if (!isset($_GET['code'])) {
 
	$client = new Google_Client();
   echo "Redirecting....";exit;
   // $authURL = $client->createAuthUrl();
	//echo $authURL;exit;
   // header('Location: ' . filter_var($authURL, FILTER_SANITIZE_URL));
} else {
	$client = new Google_Client();
		
	$api = new Settings_API;
	$clientID = $api->getClientID();
	$clientSecret = $api->getClientSecret();
		
	$redirectURI = SENDSTUDIO_APPLICATION_URL.'/oauth2callback.php';
	$client->setClientId($clientID);
	$client->setClientSecret($clientSecret);
	$client->setRedirectUri($redirectURI);
	$accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);
	$client->setAccessType('offline'); // Allow offline access to refresh token
	$client->setPrompt('consent');
	$client->addScope('https://mail.google.com/');	
      
    if(isset($accessToken['error']) && !empty($accessToken['error'])) {
    	//print_r($accessToken);
		$GLOBALS['Error'] = $accessToken['error'].' : '.$accessToken['error_description'];
		$sendstudio_functions->ParseTemplate('error_google_oauth', false, true, '');
        exit;
    }
  
    $client->setAccessToken($accessToken);
    $access_token = $accessToken['access_token']; // this token is used in the below code.
   	if(isset($accessToken['refresh_token'])) {
		$refreshToken  = $accessToken['refresh_token'];
		$settingApi = $sendstudio_functions->GetApi('Settings');
		//$settingApi = new   Settings_API();
		$client_secret6 = $settingApi->saveRefreshToken($refreshToken);

		//Clear Settings Cache
		$stash = IEM_InterspireStash::getInstance();
		if ($stash->exists('IEM_SYSTEM_SETTINGS')) {
			$stash->remove('IEM_SYSTEM_SETTINGS');
		}   
    //header('Location:admin/index.php?Page=Settings&Tab=7');
   }else{
      //  header('Location:admin/index.php?Page=Settings&Tab=7');
   }
    
}
	//config json client_credentials
	 
?>
<script>
	window.close();
	window.opener.location.reload();
</script>
