<?php 
require_once $_SERVER['DOCUMENT_ROOT'].'/admin/system/settings/db.php'; 
require __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$settings = $DB->query("select * from settings where id=1")->fetch(PDO::FETCH_ASSOC);
$client->setClientId($settings['GoogleCalendarClientId']);
$client->setClientSecret($settings['GoogleCalendarClientSecret']);
$client->setRedirectUri('https://'.$_SERVER['SERVER_NAME'].'/admin/GoogleConnect');
$client->addScope(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setPrompt("consent");


if(!$_GET['code']){
$authUrl = $client->createAuthUrl();
header("Location: $authUrl");
exit;
}

if($_GET['code']){
session_start();
$calisanID = $_SESSION['memberId'];
$code = $_GET['code'];
$token = $client->fetchAccessTokenWithAuthCode($code);
$accessToken = $token;
$refreshToken = $token['refresh_token'];
$guncelle = $DB->prepare("UPDATE provider set GoogleCalendarToken=?, GoogleCalendarRefresh=? WHERE id=?");
$guncelle -> execute(array(json_encode($accessToken),$refreshToken,$calisanID));
header("Location: ../../admin/profile-settings?connectSuccess=1");
exit;
}
?>