<?php 
require_once $_SERVER['DOCUMENT_ROOT'].'/admin/system/settings/db.php'; 
require __DIR__ . '/vendor/autoload.php';
session_start();
if(!$_SESSION['memberId']){
header('Location: /admin/login');
exit;
}else{
/////////////////////////////////////////////
/////////////////////////////////////////////
$title = "Yeni Randevu";
$desc = "Randevu Detay";
$start = "2024-01-06T10:00:00";
$end = "2024-01-06T11:00:00";
/////////////////////////////////////////////
/////////////////////////////////////////////


$calisanID = $_SESSION['memberId'];
$kontrol = $DB->prepare("SELECT * FROM provider WHERE id = ?");
$kontrol->execute(array($calisanID));
$kontrol = $kontrol ->fetch(PDO::FETCH_ASSOC);

$settings = $DB->prepare("SELECT * FROM settings WHERE id = ?");
$settings->execute(array('1'));
$settings = $settings ->fetch(PDO::FETCH_ASSOC);


$client = new Google_Client();
$client->setClientId($settings['GoogleCalendarClientId']);
$client->setClientSecret($settings['GoogleCalendarClientSecret']);
$client->setRedirectUri('https://'.$_SERVER['SERVER_NAME'].'/admin/GoogleConnect');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_Calendar::CALENDAR);


$token = $kontrol['GoogleCalendarToken'];
$getRefreshToken = $kontrol['GoogleCalendarRefresh'];
$client->setAccessToken($token);

if ($client->isAccessTokenExpired() && $getRefreshToken) {
    $client->fetchAccessTokenWithRefreshToken($getRefreshToken);
    $newToken = $client->getAccessToken();
    $guncelle = $DB->prepare("UPDATE provider set GoogleCalendarToken=? WHERE id=?");
    $guncelle -> execute(array(json_encode($newToken),$calisanID));
    echo "token yenilendi<br>";
}

$service = new Google_Service_Calendar($client);

$event = new Google_Service_Calendar_Event(array(
  'summary' => $title,
  'description' => $desc,
  'start' => array(
    'dateTime' => $start,
    'timeZone' => 'Europe/Istanbul',
  ),
  'end' => array(
    'dateTime' => $end,
    'timeZone' => 'Europe/Istanbul',
  ),
));


$calendarId = 'primary'; 
$event = $service->events->insert($calendarId, $event);
$createdEventId = $event->id;


echo 'Etkinlik başarıyla eklendi.'.$createdEventId;
}
?>