//Источники:
//https://mjdm.ru/forum/viewtopic.php?f=5&t=34&start=290#p96440
//https://github.com/googleapis/google-api-php-client
//https://cloud.google.com/docs/authentication/production#auth-cloud-implicit-php

//Скачиваем и распаковываем папку google-api-php-client с google-api-php-client
//Делаем сервисный экаунт
//Календарь с задачами расшаривается для этого акаунта
//Создаём json для авторизации от сервисного акаунта
//Помещаем json на сервер (например, в /var/www/html/)
//Раз в день (или чаще) считываются задачи из гугл-календаря и записываются в МДМ

//Тут надо поставить правильный путь до файла autoload.php из библиотеки:
//include your composer dependencies
require_once '/var/www/html/modules/google-api-php-client/vendor/autoload.php'; 

//Здесь полный путь и название json:
//Set the path to these credentials using the GOOGLE_APPLICATION_CREDENTIALS environment variable:
putenv('GOOGLE_APPLICATION_CREDENTIALS=/home/pi/google_calendar.json');

//Tell the Google client to use your service account credentials to authenticate:
$client = new Google_Client();
$client->useApplicationDefaultCredentials();

//Set the scopes required for the API you are going to call
$client->setApplicationName('TestCalendarAPI');
$client->setScopes('https://www.googleapis.com/auth/calendar');
$service = new Google_Service_Calendar($client);

// Берём 20 задач за сегодня 
$calendarId = 'e-mail@gmail.com'; // id основного календаря совпадает с е-мейлом

$optParams = array(
  'maxResults' => 20,
  'orderBy' => 'startTime',
  'singleEvents' => TRUE,
  'timeMin' => date('Y-m-d',strtotime('today')) .'T00:00:00+03:00',
  'timeMax' => date('Y-m-d',strtotime('+1 day')) .'T00:00:00+03:00',
);
//удаляем записи из базы
$dateMin = date('Y-m-d',strtotime('today'));
$dateMax = date('Y-m-d',strtotime('+1 day'));
SQLExec("DELETE FROM calendar_events WHERE DUE='".$dateMin."' AND CALENDAR_CATEGORY_ID=20"); 
SQLExec("DELETE FROM calendar_events WHERE DUE='".$dateMax."' AND CALENDAR_CATEGORY_ID=20"); 

$results = $service->events->listEvents($calendarId, $optParams);

if (count($results->getItems()) > 0) 
	{
	foreach ($results->getItems() as $event) 
    	{
		$rec=array();
		$rec['TITLE']=$event->getSummary();
		// Notes
		$notes = $event->getDescription();
		if ($notes){
		$rec['NOTES'] = $event->getDescription();
		}
		// DUE
		$due = $event->getStart();
		if ($due) {
			if ($due['dateTime']){
			$rec['DUE'] = date('Y-m-d H:i:s', strtotime( $due['dateTime'] ));
			} else if ($due['date']){
			$rec['DUE'] = date('Y-m-d H:i:s', strtotime( $due['date'] ));
			} else {
			$RESULT_LOG[] = "Invalid start date :".print_r($due, true);
			}
		}			  			  
    	// DONE_WHEN
		$done_when = $event->getEnd();
		if ($done_when) {
			if ($done_when['dateTime']){
			$rec['DONE_WHEN'] = date('Y-m-d H:i:s', strtotime( $done_when['dateTime'] ));
			} else if ($done_when['date']){
		    $rec['DONE_WHEN'] = date('Y-m-d H:i:s', strtotime( $done_when['date'] ));
			} else {
			$RESULT_LOG[] = "Invalid end date :".print_r($done_when, true);
			}
		}    
		$rec['CALENDAR_CATEGORY_ID']=20;
		$rec['IS_TASK']=0; //1-Задача, 0-Событие
		// ADDED
		$added = $event->getCreated();
		if ($added) {				
		$rec['ADDED'] = date('Y-m-d H:i:s', strtotime( $added ));
		}
		$rec['ID']=SQLInsert('calendar_events', $rec); 
//    	echo json_encode($rec).'<br/>\n';
    	}
	}

include_once('./modules/app_calendar/app_calendar.class.php');
$calendar = new app_calendar();
$calendar->calendar_getholidays();