<?php

class EcmGoogleService
{

    private $client;

    private $cal;

    private $oauth;
    
    public $userinfo;

    function __construct ($module, $id, $adress)
    {
        global $sugar_config;
        if ($sugar_config['googleClientId'] != '' &&
                 $sugar_config['googleRedirectUri'] != '' &&
                 $sugar_config['googleScopes'] != '' &&
                 $sugar_config['googleClientSecret'] != '') {
            session_start();
            require_once ('include/ECM/EcmGoogleServices/src/Google/autoload.php');
            $this->client = new Google_Client();
            
            $this->client->setClientId($sugar_config['googleClientId']);
            $this->client->setClientSecret($sugar_config['googleClientSecret']);
            $this->client->setRedirectUri($sugar_config['googleRedirectUri']);
            
            $this->client->setScopes($sugar_config['googleScopes']); // Calender
                                                                     // Scope
            $this->cal = new Google_Service_Calendar($this->client);
            $this->oauth = new Google_Service_Oauth2($this->client);
        } else {
            return false;
        }
    }

    function getUserInfo()
    {
        $this->userinfo = $this->oauth->userinfo;
        $this->userinfo = $this->userinfo->get();
        return $this->userinfo;
    }
    

    function checkLogin()
    {
        if ($_SESSION['access_token'] != '') {
           
            $this->client->setAccessToken($_SESSION['access_token']);
            if ($this->client->isAccessTokenExpired()) {
                if($this->client->getAccessToken()==''){
                    return false;
                } else {
                    $refresh_code=$this->client->getRefreshToken();
                    if($refresh_code!=''){
                        $NewAccessToken = json_decode($this->client->getAccessToken());
                        $NewAccessToken->refresh_token=$refresh_code;
                        $this->client->refreshToken($NewAccessToken->refresh_token);
                        return true;
                    } else {
                        return false;
                    }
                }
            } else {
                $token = $this->client->getAccessToken();
                $_SESSION['access_token'] = $token;
                return true;
            }
        } else {
            return false;
        }
    }
    
    function generateUrl()
    {
        return $this->client->createAuthUrl();
    }
    
    function logIn($code)
    {
        $accessToken = $this->client->authenticate($code);
        if($accessToken!=''){
            $this->client->setAccessToken($accessToken);
            $token = $this->client->getAccessToken();
            $_SESSION['access_token'] = $token;
            return true;
        
        } else {
           return false;
        }
    }
    
    function DataIT2DB($datapega) {
        if ($datapega) {
            $data = explode('/', $datapega);
            if (count($data) > 1) {
                $datacerta = $data[2] . '-' . $data[1] . '-' . $data[0];
            } else {
                $datacerta = $datapega;
            }
        } else {
            $datacerta = $datapega;
        }
        return $datacerta;
    }
    
    function geratime($DateStart, $TimeStart) {
        $dataHora = $DateStart . 'T' . $TimeStart . ':00.000+02:00'; //Fuso Rome
        return $dataHora;
    }
    
    function deleteEvent($id)
    {
        $createdEvent = $this->cal->events->delete('primary', $id);
    }
    
    function addEvent($title,$description,$DateStart,$TimeStart,$DateEnd,$TimeEnd,$DateReminder)
    {
        $event = new Google_Service_Calendar_Event();
        $event->setDescription($description);
        if($title!=''){
        $event->setSummary($title);
        }
        $event->setLocation('Poland');
        //$event->sendNotifications('TRUE');
        $start = new Google_Service_Calendar_EventDateTime();
        $start->setDateTime($this->geratime($this->DataIT2DB(date('Y-m-d',strtotime($DateStart))), date('H:i',strtotime($TimeStart))));
        $event->setStart($start);
        $end = new Google_Service_Calendar_EventDateTime();
        if($DateEnd!=''){
        $end->setDateTime($this->geratime($this->DataIT2DB(date('Y-m-d',strtotime($DateEnd))), date('H:i',strtotime($TimeEnd))));
        $event->setEnd($end);
        } else {
            $end->setDateTime($this->geratime($this->DataIT2DB(date('Y-m-d',strtotime($DateStart))), date('H:i',strtotime($TimeStart))));
            $event->setEnd($end);
        }
        $event->setHangoutLink(null);
        if($DateReminder==''){
            $reminderI = new Google_Service_Calendar_EventReminder();
            $reminderI->setMethod('popup');
            $reminderI->setMinutes('5');
        } else {
            $datetime1 = date_create($DateStart);
            $datetime2 = date_create($DateReminder);
            echo $DateReminder;
            $interval = date_diff($datetime1, $datetime2);
         //   echo $interval->format('%i');
            $reminderI = new Google_Service_Calendar_EventReminder();
            $reminderI->setMethod('popup');
          
            $hours   = $interval->format('%h'); 
            $minutes = $interval->format('%i');
            $reminderI->setMinutes(($hours * 60 + $minutes));
          
        }
        $reminder = new Google_Service_Calendar_EventReminders();
        $reminder->setUseDefault('false');
        $reminder->setOverrides(array($reminderI));
        $event->setReminders($reminder);
        
        $createdEvent = $this->cal->events->insert('primary', $event);

        return $createdEvent->getId();
        //Create Calender Event
    }
    function updateEvent($id,$title,$description,$DateStart,$TimeStart,$DateEnd,$TimeEnd,$DateReminder)
    {
        $event = new Google_Service_Calendar_Event();
        $event->setDescription($description);
        if($title!=''){
            $event->setSummary($title);
        }
        $event->setLocation('Poland');
        //$event->sendNotifications('TRUE');
        $start = new Google_Service_Calendar_EventDateTime();
        $start->setDateTime($this->geratime($this->DataIT2DB(date('Y-m-d',strtotime($DateStart))), date('H:i',strtotime($TimeStart))));
        $event->setStart($start);
        $end = new Google_Service_Calendar_EventDateTime();
        if($DateEnd!=''){
            $end->setDateTime($this->geratime($this->DataIT2DB(date('Y-m-d',strtotime($DateEnd))), date('H:i',strtotime($TimeEnd))));
            $event->setEnd($end);
        } else {
            $end->setDateTime($this->geratime($this->DataIT2DB(date('Y-m-d',strtotime($DateStart))), date('H:i',strtotime($TimeStart))));
            $event->setEnd($end);
        }
        $event->setHangoutLink(null);
        if($DateReminder==''){
            $reminderI = new Google_Service_Calendar_EventReminder();
            $reminderI->setMethod('popup');
            $reminderI->setMinutes('5');
        } else {
            $datetime1 = date_create($DateStart);
            $datetime2 = date_create($DateReminder);
            echo $DateReminder;
            $interval = date_diff($datetime1, $datetime2);
            //   echo $interval->format('%i');
            $reminderI = new Google_Service_Calendar_EventReminder();
            $reminderI->setMethod('popup');
    
            $hours   = $interval->format('%h');
            $minutes = $interval->format('%i');
            $reminderI->setMinutes(($hours * 60 + $minutes));
    
        }
        $reminder = new Google_Service_Calendar_EventReminders();
        $reminder->setUseDefault('false');
        $reminder->setOverrides(array($reminderI));
        $event->setReminders($reminder);
    
        $createdEvent = $this->cal->events->update('primary',$id, $event);
    
        return $createdEvent->getId();
        //Create Calender Event
    }
}

?>