<?php
/*
Documentation: https://googlecalapi.com/docs/quickstart
*/
require_once dirname( __FILE__ ).'/base.addon.php';

if( !class_exists( 'CPABC_GoogleCalendarAPI' ) )
{
    class CPABC_GoogleCalendarAPI extends CPABC_BaseAddon
    {
        /************* ADDON SYSTEM - ATTRIBUTES AND METHODS *************/
		protected $addonID = "addon-abcgooglecalapi-20190815";
		protected $name = "Google Calendar API (Beta version)";
		protected $description;
        protected $default_pay_label = "Integration with Google Calendar via API";

		public function get_addon_form_settings( $form_id )
		{
			global $wpdb;
            
			// Insertion in database
			if(
				isset( $_REQUEST[ 'CPABC_GoogleCalendarAPI_id' ] )
			)
			{   
                
                $rows = $wpdb->get_results(
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $form_id )
					);
                if (count($rows))
                    $access_token = $rows[0]->access_token;
                else            
                    $access_token = "";                    
                
			    $wpdb->delete( $wpdb->prefix.$this->form_table, array( 'formid' => $form_id ), array( '%d' ) );
                
				$wpdb->insert(
								$wpdb->prefix.$this->form_table,
								array(
									'formid' => $form_id,
									
                                    'googlecalapi_key'	 => trim($_REQUEST["googlecalapi_key"]),
									'googlecalapi_secretkey'	 => trim($_REQUEST["googlecalapi_secretkey"]),
									'enabled'	 => $_REQUEST["googlecalapi_enabled"],
                                    
                                    'eventsummary'	 => $_REQUEST["googlecalapi_eventsummary"],
                                    'eventdescription'	 => $_REQUEST["googlecalapi_eventdescription"],
                                    'timezone'	 => (isset($_REQUEST["timezone"])?$_REQUEST["timezone"]:'0'),
                                    
                                    'selectedcalendar' => (isset($_REQUEST["selectedcalendar"])?$_REQUEST["selectedcalendar"]:''),
                                    'access_token'	 => $access_token,
                                    'debugmode'	 => (isset($_REQUEST["googlecalapi_debugmode"])?$_REQUEST["googlecalapi_debugmode"]:'0'),
                                    
                                    'importoption'	 => (isset($_REQUEST["googlecalapi_importoption"])?$_REQUEST["googlecalapi_importoption"]:'0'),
                                    
                                    'onlyfuture'	 => $_REQUEST["onlyfuture"],
                                    
                                    'gcalapi_modify_import'	 => $_REQUEST["gcalapi_modify_import"],
                                    'gcalapi_modify_export'	 => $_REQUEST["gcalapi_modify_export"],
								),
								array( '%d', '%s', '%s', '%s', 
                                             '%s', '%s', '%s', 
                                             '%s', '%s', '%s', 
                                             '%s', '%s', '%s', 
                                             '%s'   
                                     )
							);               

                if (@$_POST["CPABC_GoogleCalendarAPI_goauth"] == '1')
                {
                    echo "<script>document.location='?cpabc_googlecalapi_auth=1&formid=".$form_id."';</script>";
                    exit;
                } 
                
                $this->gCalAPI_Import();
			}
            $error_message = "";
            try {
			    $rows = $wpdb->get_results(
			    			$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $form_id )
			    		);
			    if (!count($rows))
			    {
			        $row["googlecalapi_key"] = "";
			        $row["googlecalapi_secretkey"] = "";
			        $row["enabled"] = "0";
                    $row["eventsummary"] = "Booking for %email%";
                    $row["eventdescription"] = "Booking for %email%";
                    $row["timezone"] = "0";
                    $row["selectedcalendar"] = "0";
                    $row["debugmode"] = "0";
                    $row["importoption"] = "0";
                    $row["onlyfuture"] = '';
                    $row["gcalapi_modify_import"] = '';
                    $row["gcalapi_modify_export"] = '';
			    } else {
			        $row["googlecalapi_key"] = $rows[0]->googlecalapi_key;
			        $row["googlecalapi_secretkey"] = $rows[0]->googlecalapi_secretkey;
			        $row["enabled"] = $rows[0]->enabled;
                    $row["eventsummary"] = $rows[0]->eventsummary;
                    $row["eventdescription"] = $rows[0]->eventdescription;
                    $row["timezone"] = $rows[0]->timezone;
                    $row["selectedcalendar"] = $rows[0]->selectedcalendar;
                    $row["debugmode"] = $rows[0]->debugmode;
                    $row["importoption"] = $rows[0]->importoption;
                    $row["onlyfuture"] = $rows[0]->onlyfuture;
                    $row["gcalapi_modify_import"] = $rows[0]->gcalapi_modify_import;
                    $row["gcalapi_modify_export"] = $rows[0]->gcalapi_modify_export;
			    }
                
                $calendars = array();
                
                $url = cpabc_appointment_get_FULL_site_url().'/?cpabc_googlecalapi_auth=1&formid='.$form_id;
                
                $json_access = json_decode('{"web":{"client_id":"'.$rows[0]->googlecalapi_key.'","project_id":"cff-php-integration","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://www.googleapis.com/oauth2/v3/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"'.$rows[0]->googlecalapi_secretkey.'","redirect_uris":["'.cpabc_appointment_get_FULL_site_url().'"],"javascript_origins":["'.cpabc_appointment_get_FULL_site_url().'"]}}', true);
                
                require_once __DIR__.'/gapi.addon/autoload.php';			            
                $client = new Google_Client();
                $client->setAuthConfig($json_access);            
                $client->addScope(Google_Service_Calendar::CALENDAR);
                $client->setAccessType('offline');
                $client->setPrompt('select_account consent');
                $client->setRedirectUri($url);            
                $accessToken = unserialize($rows[0]->access_token);     
                
                $notoken  = false;
                if ($accessToken != '' && $row["googlecalapi_secretkey"] != '' && $row["googlecalapi_key"] != '')
                {
                    try {            
                        $client->setAccessToken($accessToken);
                    } catch (Exception $e) { $notoken = true; } 
                    
                    if ($client->isAccessTokenExpired()) {
                        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                        $accessToken = $client->getAccessToken();
                        $client->setAccessToken($accessToken);                                
                    }
                    
                    $service = new Google_Service_Calendar($client);
                    $calendarList = $service->calendarList->listCalendarList();                
                    
                    while(true) {
                      foreach ($calendarList->getItems() as $calendarListEntry) {
                          $calendars[] = array ( "id" => $calendarListEntry->id, "name" => $calendarListEntry->summary, "timezone" => $calendarListEntry->timeZone);
                      }
                      $pageToken = $calendarList->getNextPageToken();
                      if ($pageToken) {
                          $optParams = array('pageToken' => $pageToken);
                          $calendarList = $service->calendarList->listCalendarList($optParams);
                      } else {
                          break;
                      }
                    }
                }
                
            } catch (Exception $e) { $error_message = $e->getMessage(); }             
			?>
            <script type="text/javascript">
             function GCalproceedAuth()
             {
                  if (confirm('This will save the settings and will redirect to Google to proceed with the authorization. Do you want to continue?'))
                  {
                      document.getElementById("CPABC_GoogleCalendarAPI_goauth").value = '1';
                      document.dexconfigofrm.submit();
                  }
             }
             <?php if (@$_GET["step6"] == '1') { ?>
             	jQuery(function(){
		           // ahbGoToStep(6);
                });
             <?php } ?>   
            </script>
            <a name="configgcal"></a>
			<div id="metabox_basic_settings" class="postbox" >
				<h3 class='hndle' style="padding:5px;"><span><?php print $this->name; ?></span></h3>
				<div class="inside">
				   <input type="hidden" name="CPABC_GoogleCalendarAPI_id" value="1" />
                   <input type="hidden" name="CPABC_GoogleCalendarAPI_goauth" id="CPABC_GoogleCalendarAPI_goauth" value="0" />
                   <?php if ($error_message != '') { ?>
                   <div style="border:1px solid red; padding:15px;background-color:##FFFACD;color:red;">Google Connection Error: <?php echo $error_message; ?></div>
                   <?php } ?>
                   
                   <table class="form-table">
                    <tr valign="top">
                    <th scope="row"><?php _e('Enable GoogleCalendarAPI?', 'appointment-booking-calendar'); ?></th>
                    <td><select name="googlecalapi_enabled" id="googlecalapi_enabled" onchange="ahb_show_hide_gcalapi();">
                         <option value="0" <?php if (!$row["enabled"]) echo 'selected'; ?>><?php _e('No', 'appointment-booking-calendar'); ?></option>
                         <option value="1" <?php if ($row["enabled"]) echo 'selected'; ?>><?php _e('Yes', 'appointment-booking-calendar'); ?></option>
                         </select>
                    </td>
                    </tr> 
                   </table>
                   <table class="form-table" id="ahh_gcalapi_settings">                   
                   <?php if (!count($calendars)) { ?>
                    <tr valign="top">                    
                    <td colspan="2" scope="row">  
                     <div style="color:#AA0000">                     
                     <strong>STEPS REQUIRED:</strong>
                     <ol>
                      <li>Go to <a href="https://console.developers.google.com/apis/credentials" target="_blank">https://console.developers.google.com/apis/credentials</a></li>
                      <li>On the Google console click "<strong>Create Credentials</strong>" >> "<strong>Oauth client ID</strong>">> "<strong>Web application</strong>"</li>
                      <li>For the Google API configuration settings, indicate:  <strong> Redirect URI:</strong> <?php echo cpabc_appointment_get_FULL_site_url(); ?>/?cpabc_googlecalapi_auth=1&formid=<?php echo $form_id; ?></li>
                      <li>For the Google API configuration settings, indicate:  <strong> JavaScript Origins:</strong> 
                             <?php echo sprintf(
                                "%s://%s",
                                isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
                                $_SERVER['SERVER_NAME']
                              );; ?></li>
                      <li>Enter the Google Calendar API  <strong>Client ID</strong> and <strong>Client secret</strong> in the settings field below</li>
                      <li>When done all the above <a href="javascript:GCalproceedAuth();">click here</a> to proceed with the authorization</li>
                     </ol>
                     </div>
                    </th>
                    </tr>                     
                   <?php } else { ?>
                    <tr valign="top">                    
                    <td colspan="2" scope="row">       
                      <?php if (!$row["selectedcalendar"]) {?>    
                       <div style="color:#AA0000">                      
                       <strong>STEPS REQUIRED:</strong>
                       <p>Great! You have completed the Google Calendar connection. Now <strong>please select in the drop-down field below to which calendar</strong> you want to
                          add the new bookings received through the plugin:</p>     
                       </div>                           
                      <?php } else { ?> 
                        <div style="color:#009900">                      
                        <strong>Great! Google Calendar connection completed.</strong>      
                        <p>New bookings received through the plugin will be added to the calendar selected in the drop-down field below:</p>
                        </div>
                      <?php } ?>                        
                    </th>
                    </tr>                    
                    <tr valign="top">
                    <th scope="row">Calendar to add the bookings:</th>
                    <td><select name="selectedcalendar">
                          <option value=""> -- Please select calendar --</option>
                          <?php foreach ($calendars as $item) { ?>                            
                            <option value="<?php echo $item["id"]; ?>" <?php if ($item["id"] == $row["selectedcalendar"]) echo 'selected'; ?>><?php echo $item["name"]; ?></option>
                          <?php } ?>  
                         </select></td>
                    </tr>
                   <?php } ?>              
                    <tr valign="top">
                    <th scope="row">Google Calendar API  <?php _e('Client ID', 'appointment-booking-calendar'); ?></th>
                    <td><input type="text" name="googlecalapi_key" size="85" value="<?php echo esc_attr($row["googlecalapi_key"]); ?>" /></td>
                    </tr>
                    <tr valign="top">
                    <th scope="row">Google Calendar API <?php _e('Client secret', 'appointment-booking-calendar'); ?></th>
                    <td><input type="text" name="googlecalapi_secretkey" size="40" value="<?php echo esc_attr($row["googlecalapi_secretkey"]); ?>" /></td>
                    </tr>                   
                    <tr valign="top" <?php if (!count($calendars)) echo 'style="display:none"'; ?>>
                    <th scope="row"><?php _e('Event Summary', 'appointment-booking-calendar'); ?></a></th>
                    <td><input type="text   " name="googlecalapi_eventsummary" size="50" value="<?php echo esc_attr($row["eventsummary"]); ?>" />  <br />
                         <em>* Note: You can get the field IDs/tags from the form builder.</em></td>
                    </tr>           
                    <tr valign="top" <?php if (!count($calendars)) echo 'style="display:none"'; ?>>
                    <th scope="row"><?php _e('Event Description', 'appointment-booking-calendar'); ?></a></th>
                    <td><textarea name="googlecalapi_eventdescription" cols="80" rows="5"><?php echo esc_attr($row["eventdescription"]); ?></textarea>  <br />
                         <em>* Note: You can get the field IDs/tags from the form builder.</em></td>
                    </tr>
                    <tr valign="top">
                    <th scope="row"><?php _e('Import also items from the Google Calendar into the plugin bookings?', 'appointment-booking-calendar'); ?></th>
                    <td><select name="googlecalapi_importoption" id="googlecalapi_importoption">
                     <option value="0" <?php if ($row["importoption"] != '1') echo 'selected'; ?>><?php _e('No (pending for 2nd phase implementation)', 'appointment-booking-calendar'); ?></option>
                        <!-- <option value="0" <?php if ($row["importoption"] != '1') echo 'selected'; ?>><?php _e('No', 'appointment-booking-calendar'); ?></option>
                         <option value="1" <?php if ($row["importoption"] == '1') echo 'selected'; ?>><?php _e('Yes', 'appointment-booking-calendar'); ?></option>
                         -->
                         </select><br />
                         <em>* Warning: This is a two-way sync. With this option enabled if you delete an imported booking in the plugin it will delete the booking also in Google Calendar and a booking deleted in Google Calendar will be deleted in the plugin.<br />
                         The sync <strong>from the plugin to Google</strong> is <strong>immediate</strong>. The sync <strong>from Google into the plugin</strong> is made <strong>every 5 minutes and every time the plugin settings are saved</strong>.</em>
                    </td>
                    </tr> 
                    <tr valign="top">
                    <th scope="row"><?php _e('Import only items with date in the future?', 'appointment-booking-calendar'); ?></th>
                    <td><select name="onlyfuture">
                          <option value="0" <?php if ($row["onlyfuture"] == '' || $row["onlyfuture"] == '0') echo ' selected'; ?>>No</option> 
                          <option value="1" <?php if ($row["onlyfuture"] == '1') echo ' selected'; ?>>Yes</option>
                         </select>
                         <br />
                         <em>* Select "Yes" if you don't want to import items with date in the past.</em>
                    </td>
                    </tr>              
                    <tr valign="top">
                    <th scope="row"><?php _e('Modify time of imported items from Google Calendar?', 'appointment-booking-calendar'); ?></th>
                    <td><select name="gcalapi_modify_import">
                          <option value="">- No -</option> 
                          <?php for ($i=-23;$i<24; $i++) { ?>        
                           <option value="<?php $text = " ".($i<=0?"":"+").$i." hours"; $text2 = " ".($i<=0?"+".(-1*$i):"-".$i)." hours"; echo $text; ?>" <?php if ($row["gcalapi_modify_import"] == $text) echo ' selected'; ?>><?php echo $text2; ?></option>
                          <?php } ?>
                         </select>      
                         <em>* If needed, use this field to make the imported times match the expected time into the plugin.</em>
                    </td>
                    </tr>
                    <tr valign="top">
                    <th scope="row"><?php _e('Modify time of exported items to Google Calendar?', 'appointment-booking-calendar'); ?></th>
                    <td><select name="gcalapi_modify_export">
                          <option value="">- No -</option> 
                          <?php for ($i=-23;$i<24; $i++) { ?>        
                           <option value="<?php $text = " ".($i<=0?"":"+").$i." hours"; $text2 = " ".($i<=0?"+".(-1*$i):"-".$i)." hours"; echo $text; ?>" <?php if ($row["gcalapi_modify_export"] == $text) echo ' selected'; ?>><?php echo $text2; ?></option>
                          <?php } ?>
                         </select>         
                         <em>* If needed, use this field to make the exported times match the expected time at Google Calendar.</em>                         
                    </td>
                    </tr>                    
                    
                    <tr valign="top">
                    <th scope="row"><?php _e('Enable Debug Mode?', 'appointment-booking-calendar'); ?></th>
                    <td><select name="googlecalapi_debugmode" id="googlecalapi_debugmode">
                         <option value="0" <?php if ($row["debugmode"] != '1') echo 'selected'; ?>><?php _e('No', 'appointment-booking-calendar'); ?></option>
                         <option value="1" <?php if ($row["debugmode"] == '1') echo 'selected'; ?>><?php _e('Yes', 'appointment-booking-calendar'); ?></option>
                         </select><br />
                         <em>* Enable "Debug Mode" only for troubleshooting. Don't keep this enabled in production environments</em>
                         
                    </td>
                    </tr> 
                   </table>
                   <script>
                     function ahb_show_hide_gcalapi()
                     {
                         if (document.getElementById("googlecalapi_enabled").options.selectedIndex)
                             document.getElementById("ahh_gcalapi_settings").style.display = '';
                         else
                             document.getElementById("ahh_gcalapi_settings").style.display = 'none';
                     }
                     ahb_show_hide_gcalapi();
                   </script>
				</div>
			</div>
			<?php
		} // end get_addon_form_settings



		/************************ ADDON CODE *****************************/

        /************************ ATTRIBUTES *****************************/

        private $form_table = 'cpabc_googlecalapi';
        private $form_table_events = 'cpabc_googlecalapi_ev';
		private $table_columns;
        private $_inserted = false;
        private $_im_flag = false;

        /************************ CONSTRUCT *****************************/

        function __construct()
        {
			$this->description = __("The add-on adds support for Google Calendar API integration", 'appointment-booking-calendar' );
            // Check if the plugin is active
                        
			if( !$this->addon_is_active() ) return;

			add_action( 'init', array( &$this, 'pp_googlecalapi_checkauth' ), 1 );        

            add_action( 'cpabc_update_status', array( &$this, 'pp_google_check_item_status' ), 10, 2 );       

            add_action( 'cpabc_process_data', array( &$this, 'pp_google_check_item' ), 11, 1 );  

            add_action( 'cpabc_item_deleted', array( &$this, 'pp_google_item_deleted' ), 11, 1 ); 

            add_filter( 'cron_schedules',  array( &$this, 'isa_add_cron_recurrence_interval' ) );

            // aqui un action de init o lo que sea para el cron 
            if ( ! wp_next_scheduled( 'cpabc_gcalapi_import_hook_fmin' ) ) {                
                //wp_schedule_event( time(), 'hourly', 'cpabc_gcalapi_import_hook_fmin' );
                wp_schedule_event( time(), 'cp_every_three_minutes', 'cpabc_gcalapi_import_hook_fmin' );
            }

            add_action( 'cpabc_gcalapi_import_hook_fmin', array( &$this, 'gCalAPI_Import' ) );            

            $this->update_database();

        } // End __construct
        
        
        public function isa_add_cron_recurrence_interval( $schedules ) {
         
            $schedules['cp_every_three_minutes'] = array(
                    'interval'  => 60*5,
                    'display'   => __( 'Every 5 Minutes', 'appointment-booking-calendar' )
            );
             
            return $schedules;
        }        



        /************************ PRIVATE METHODS *****************************/

		/**
         * Create the database tables
         */
        protected function update_database()
		{
			global $wpdb;
			$charset_collate = $wpdb->get_charset_collate();
			$sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix.$this->form_table." (
					id mediumint(9) NOT NULL AUTO_INCREMENT,
					formid INT NOT NULL,
					enabled varchar(10) DEFAULT '0' NOT NULL ,
					googlecalapi_key varchar(255) DEFAULT '' NOT NULL ,
					googlecalapi_secretkey varchar(255) DEFAULT '' NOT NULL ,	
                    eventsummary TEXT DEFAULT '' NOT NULL ,	
                    eventdescription TEXT DEFAULT '' NOT NULL ,	
                    timezone TEXT DEFAULT '' NOT NULL ,     
                    selectedcalendar varchar(255) DEFAULT '' NOT NULL ,                    
                    access_token TEXT DEFAULT '' NOT NULL ,      
                    debugmode varchar(10) DEFAULT '0' NOT NULL ,
                    importoption varchar(10) DEFAULT '0' NOT NULL , 
                    onlyfuture varchar(10) DEFAULT '0' NOT NULL ,   
                    gcalapi_modify_import varchar(50) DEFAULT '0' NOT NULL ,
                    gcalapi_modify_export varchar(50) DEFAULT '0' NOT NULL ,                    
					UNIQUE KEY id (id)
				)
				CHARACTER SET utf8
				COLLATE utf8_general_ci;";
            $wpdb->query($sql);
            
			$sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix.$this->form_table_events." (
					id mediumint(9) NOT NULL AUTO_INCREMENT,
					submissionid INT NOT NULL,
					eventid varchar(255) DEFAULT '' NOT NULL ,
					UNIQUE KEY id (id)
				)
				CHARACTER SET utf8
				COLLATE utf8_general_ci;";      
            $wpdb->query($sql);                
		} // end update_database


		/************************ PUBLIC METHODS  *****************************/
        
		/**
		 * mark the item as paid
		 */
		private function _log($adarray = array())
		{
			$h = fopen( dirname(__FILE__).'/logs.txt', 'a' );
			$log = "";
			foreach( $_REQUEST as $KEY => $VAL )
			{
				$log .= $KEY.": ".$VAL."\n";
			}
			foreach( $adarray as $KEY => $VAL )
			{
				$log .= $KEY.": ".$VAL."\n";
			}
			$log .= "================================================\n";
			fwrite( $h, $log );
			fclose( $h );
		}

        
        private function add_calendar_item($client, $form_id, $params)
        {
            global $wpdb;

            $rows = $wpdb->get_results(
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $form_id )
					);
            
            foreach ($params["itemnumbers"] as $itemnumber)
            {
                $rows_inserted = $wpdb->get_results(
			    			$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table_events." WHERE submissionid=%d", $itemnumber )
			    		);                       
                if (count($rows_inserted)) // event already inserted, don't re-insert
                    return;        
                
                $summary = $rows[0]->eventsummary;        
                $description = $rows[0]->eventdescription; 
			    
                foreach ($params as $item => $value)
                {
                    $summary = str_replace('<%'.$item.'%>', $value, $summary);
                    $description = str_replace('<%'.$item.'%>', $value, $description);
                    $summary = str_replace('%'.$item.'%', $value, $summary);
                    $description = str_replace('%'.$item.'%', $value, $description);
                }           
                       
                $service = new Google_Service_Calendar($client);           
                $calendarListEntry = $service->calendarList->get( $rows[0]->selectedcalendar );            
                $tzone = $calendarListEntry->timeZone;               
                
                $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id=".intval($itemnumber) ); 
                                      
                $datetime = $myrows[0]->booked_time; 
                if ($rows[0]->gcalapi_modify_export != '')
                    $datetime .= $rows[0]->gcalapi_modify_export;
                $duration = "+".get_option('CPABC_CAL_TIME_SLOT_SIZE_SET',"15")." minutes";
                        
                $eventdate = $datetime;
                $eventdate_end = date("Y-m-d H:i:s",strtotime($eventdate." ".$duration));
                       
                $calendarId = $rows[0]->selectedcalendar;                 
                  
                /************* INSERT ****************/
                $event = new Google_Service_Calendar_Event(array(
                 'summary' => $summary,
                 'description' => $description,
                 'start' => array(
                   'dateTime' =>  date("Y-m-d", strtotime($eventdate)).'T'.date("H:i:s", strtotime($eventdate)),
                   'timeZone' => $tzone,
                 ),
                 'end' => array(
                    'dateTime' =>  date("Y-m-d", strtotime($eventdate_end)).'T'.date("H:i:s", strtotime($eventdate_end)),
                    'timeZone' => $tzone,
                 ),
                 'attendees' => array(
                  // array('email' => $submission_obj->notifyto),
                 ),
                ));
                
                try {
                    $events = $service->events->insert($calendarId, $event);
                } catch (Exception $e) {
                    if ($rows[0]->debugmode == '1') // display if debug mode is enabled
                    {
                        echo '<strong>Error - Debug information:<strong> '. $e->getMessage();
                        exit;
                    }                        
                }
                
                // insert my local reference
                $wpdb->insert(
			    					$wpdb->prefix.$this->form_table_events,
			    					array(
			    						'submissionid' => $itemnumber,
                                        'eventid'	 => $events->id,
			    					),
			    					array( '%d', '%s' )
			    				);
                
            }
        }
 
 
        function check_insert_event($gevent, $calId, $onlyfuture = '', $modifytime_import = '')
        {
            global $wpdb;
return;// remove             
            if ($gevent->status == 'cancelled')
				return;
			$gstart = $gevent->getStart();				
            if ($gstart && $gstart->getDate()) // all day event, don't process
                  return;
           
            $event = array();
            $event["id"] = $gevent->getId();     

            
            if ($rows[0]->gcalapi_modify_export != '')
            $modifytime_import = $modifytime_import;            
            
            $date_s = substr($gevent->getStart()->getDateTime(),0,strlen('2018-11-16T16:45:00'));            
            $event["date"] = date("Y-m-d",strtotime( $date_s.$modifytime_import ));
            $event["time"] = date("H:i",strtotime( $date_s.$modifytime_import ));
  
            if ($onlyfuture == '1' && $event["date"] < date("Y-m-d"))  // don't import part events
                return;
            
            $date_e = substr($gevent->getEnd()->getDateTime(),0,strlen('2018-11-16T16:45:00'));
            $event["datee"] = date("Y-m-d",strtotime( $date_e.$modifytime_import ));
            $event["timee"] = date("H:i",strtotime( $date_e.$modifytime_import ));
            $event["duration"] = round((strtotime($date_e) - strtotime($date_s))/60);
            $event["summary"] = $gevent->getSummary();
            
            $date = $event["date"]." ".$event["time"];
            $apps = array();
            $apps[] = array (
                         'id' => 1,
                         'cancelled' => '',
                         'serviceindex' => 0,
                         'service' => 'Imported: '.$event["summary"],
                         'duration' => $event["duration"],
                         'price' => 0,
                         'date' => date("Y-m-d", strtotime($date)),
                         'slot' => date("H:i", strtotime($date))."/". date("H:i",strtotime($event["datee"]." ".$event["timee"]))
                         );
            $apptext =  __('Appointments','appointment-booking-calendar').":\n". $cp_appb_plugin->get_appointments_text ($apps) ."\n" . $event["summary"] ."\n";  
            $params = array();                        
            $params["apps"] = $apps;  
            $params["formid"] = $calId;       
                    
            $rows_inserted = $wpdb->get_results(
			                			$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table_events." WHERE eventid=%s", $event["id"] )
			                		); 
                                    
            if (count( $rows_inserted ))
            {
                $rows_current = $wpdb->get_results(
			                			$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$cp_appb_plugin->table_messages." WHERE id=%s", $rows_inserted[0]->submissionid )
			                		);                                   
                if (count($rows_current) && $rows_current[0]->ipaddr == 'remote-ical-file')
                {              
                    $params_new = unserialize ($rows_current[0]->posted_data);
                    $params_new["apps"] = $apps;  
                    $params_new["formid"] = $calId; 
                    $wpdb->update( $wpdb->prefix.$cp_appb_plugin->table_messages, array( 'formid' => intval($calId),
                                                                            'posted_data' => serialize($params_new),
                                                                            'data' => $apptext
                                                                           ),
                                                                             array (
                                                                             'id' => $rows_inserted[0]->submissionid
                                                                           )
                                                                           ); 
                }
			    return;                         
            }                       
                    
            // insert event                                    
            $wpdb->insert( $wpdb->prefix.$cp_appb_plugin->table_messages, array( 'formid' => intval($calId),
                                                                            'time' => current_time('mysql'),
                                                                            'ipaddr' => 'remote-ical-file',
                                                                            'notifyto' => '',
                                                                            'posted_data' => serialize($params),
                                                                            'data' => $apptext
                                                                           ) );  
            $itemnumber = $wpdb->insert_id;
            $params["itemnumber"] = $itemnumber;
            $wpdb->update( $wpdb->prefix.$cp_appb_plugin->table_messages, array( 
                                                                            'posted_data' => serialize($params)
                                                                           ),
                                                                           array( 
                                                                            'id' => $itemnumber
                                                                           ) );  
                                                                           
            // insert my local reference
            $wpdb->insert(
						$wpdb->prefix.$this->form_table_events,
						array(
							'submissionid' => $itemnumber,
                            'eventid'	 => $event["id"],
						),
						array( '%d', '%s' )
					);  
          
        }
 
 
        /**
         * import hook
         */
        function gCalAPI_Import($calId = 0)
		{
			global $wpdb;
return;// remove          
            $rows = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE importoption=1 AND enabled=1".($calId?' AND formid='.intval($calId):'') );
            $used_items = array();
            $existent_items = array();        
              
            foreach ($rows as $item)
                if ($item->enabled && $item->importoption == '1')
                {
                    $itema = array( $item );
                    $client = $this->_connect_to_google($itema);              
                    if ($client) // if successful connection
                    {                        
                        try
                        {
                            $service = new Google_Service_Calendar($client);
                            $events = $service->events->listEvents($item->selectedcalendar);
                            while(true) {
                              foreach ($events->getItems() as $event ) {
                                 $this->check_insert_event($event, $item->formid, $item->onlyfuture, $item->gcalapi_modify_import);
                                 $used_items[] = $event->getId();
                              }
                              $pageToken = $events->getNextPageToken();
                              if ($pageToken) {
                                $optParams = array('pageToken' => $pageToken);
                                $events = $service->events->listEvents( $item->selectedcalendar, $optParams);
                              } else {
                                break;
                              }
                            }
                            
                            // check for deleted items
                            $rows_inserted = $wpdb->get_results(  "SELECT eventid FROM ".$wpdb->prefix.$this->form_table_events );
                            foreach ($rows_inserted as $item)                
                                $existent_items[] = $item->eventid;
                            $to_delete = array_diff ($existent_items,$used_items);
                            foreach ($to_delete as $deleteitem)
                            {
                                $row_to_delete = $wpdb->get_results(
			                			$wpdb->prepare( "SELECT id,submissionid FROM ".$wpdb->prefix.$this->form_table_events." WHERE eventid=%s", $deleteitem )
			                		);
                                $wpdb->query('DELETE FROM `'.$wpdb->prefix.$cp_appb_plugin->table_messages.'` WHERE id='.intval( $row_to_delete[0]->submissionid ));
                                $wpdb->query('DELETE FROM `'.$wpdb->prefix.$this->form_table_events.'` WHERE id='.intval( $row_to_delete[0]->id ));   
                            }
                        } 
                        catch (Exception $e) 
                        {
                            if ($item->debugmode == '1') // display if debug mode is enabled
                            {
                                echo '<strong>Error - Debug information:<strong> '. $e->getMessage();
                                exit;
                            }
                        }
                    }
                }    
		} // end gCalAPI_import  
        
 
        /**
         * action hook for deleted item change
         */ 
        public function pp_google_item_deleted($itemnumber)
        {
            global $wpdb;
            
            $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME." WHERE id=".intval($itemnumber) );             
            if (!empty( $myrows ))
			{   
                $itemnumber = $myrows[0]->reference;
                $form_id = intval($myrows[0]->appointment_calendar_id);
                
                $rows = $wpdb->get_results(
			    			$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $form_id )
			    		);
                
			    if (empty( $rows ) || !$rows[0]->enabled)
			        return;      
                
                $rows_inserted = $wpdb->get_results(
			    			$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table_events." WHERE submissionid=%d", $itemnumber )
			    		); 
                        
                if (empty( $rows_inserted ))
			       return;             
                 
                $client = $this->_connect_to_google($rows);
                if ($client)
                {                
                    $service = new Google_Service_Calendar($client);
                    try {
                        $service->events->delete($rows[0]->selectedcalendar, $rows_inserted[0]->eventid);  
                    } catch (Exception $e) {
                        // if already deleted just ignore
                    }
                    $wpdb->query("DELETE FROM ".$wpdb->prefix.$this->form_table_events." WHERE submissionid=".intval($itemnumber));
                }           
            }
        }
 
 
        /**
         * action hook for status change
         */ 
        public function pp_google_check_item_status($itemnumber, $status)
        {
            global $wpdb;
return;// remove
            $myrows = $wpdb->get_results( $wpdb->prepare("SELECT * FROM ".$wpdb->prefix.$cp_appb_plugin->table_messages." WHERE id=%d", $itemnumber) );
            if (empty( $myrows ))
			   return;
           
            $form_id = intval($myrows[0]->formid);

            $rows = $wpdb->get_results(
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $form_id )
					);

			if (empty( $rows ) || !$rows[0]->enabled)
			    return;      
           
            $client = $this->_connect_to_google($rows);
            if ($client)
                $this->add_calendar_item($client, $form_id, unserialize($myrows[0]->posted_data));           
        }

        
        /**
         * action hook for new item added
         */
		function pp_google_check_item($params)
		{
            global $wpdb;

            $rows = $wpdb->get_results(
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $params["formid"] )
					);

			if (empty( $rows ) || !$rows[0]->enabled)
			    return;          
         
            $client = $this->_connect_to_google($rows);
            if ($client)
                $this->add_calendar_item($client, $params["formid"], $params);             
         }        
        
        
        function _connect_to_google($rows)
        {
            global $wpdb;
            
            if (!$rows[0]->googlecalapi_key || !$rows[0]->googlecalapi_secretkey || !$rows[0]->access_token)  // if no setup yet then go out
                return false;
            
            @session_start();
            
            $json_access = json_decode('{"web":{"client_id":"'.$rows[0]->googlecalapi_key.'","project_id":"cff-php-integration","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://www.googleapis.com/oauth2/v3/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"'.$rows[0]->googlecalapi_secretkey.'","redirect_uris":["'.cpabc_appointment_get_FULL_site_url().'"],"javascript_origins":["'.cpabc_appointment_get_FULL_site_url().'"]}}', true);
             
            try 
            {               
                
                require_once __DIR__.'/gapi.addon/autoload.php';			
                $client = new Google_Client();
                $client->setAuthConfig($json_access);
                $client->addScope(Google_Service_Calendar::CALENDAR);
                $client->setAccessType('offline');
                $client->setPrompt('force');
                
                $accessToken = unserialize($rows[0]->access_token);
                $client->setAccessToken($accessToken);
                
                
                if ($client->isAccessTokenExpired()) {
                    // Refresh the token if possible, else fetch a new one.
                    if ($client->getRefreshToken()) {
                        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());                                                   
                    } 
                    else
                    {
                        if ($rows[0]->debugmode == '1') // display if debug mode is enabled
                        {
                            echo 'Connection to Google Calendar expired or was access was removed. Please re-connect to Google Calendar from the settings area.';
                            exit;
                        } 
                        return false;
                    }
                }
            } 
            catch (Exception $e) 
            {
                if ($rows[0]->debugmode == '1') // display if debug mode is enabled
                {
                    echo '<strong>Error - Debug information:<strong> '. $e->getMessage();
                    exit;
                } 
                return false;
            }      
            return $client;            
        }

        
        /**
         * 
         */
		public function pp_googlecalapi_checkauth()
		{
            global $wpdb;

            if (!isset($_GET["cpabc_googlecalapi_auth"]) || !isset($_GET["formid"]))
                return;
         
            $form_id = intval($_GET["formid"]);

            $rows = $wpdb->get_results(
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $form_id )
					);
     
			if (empty( $rows ) || !$rows[0]->enabled)
			    return;
                        
       
            $url = cpabc_appointment_get_FULL_site_url().'/?cpabc_googlecalapi_auth=1&formid='.$form_id;
            @session_start();
            
            $json_access = json_decode('{"web":{"client_id":"'.$rows[0]->googlecalapi_key.'","project_id":"cff-php-integration","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://www.googleapis.com/oauth2/v3/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"'.$rows[0]->googlecalapi_secretkey.'","redirect_uris":["'.cpabc_appointment_get_FULL_site_url().'"],"javascript_origins":["'.cpabc_appointment_get_FULL_site_url().'"]}}', true);

            require_once __DIR__.'/gapi.addon/autoload.php';			
            $client = new Google_Client();
            $client->setAuthConfig($json_access);
            $client->addScope(Google_Service_Calendar::CALENDAR);
            $client->setAccessType('offline');
            $client->setPrompt('select_account consent');
            $client->setRedirectUri($url);
            
            if (! isset($_GET['code'])) {                              
                $authUrl = $client->createAuthUrl();
                header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
                exit;
            } 
            else
            {
                $authCode = $_GET['code'];
                $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
                
                try {
                    $client->setAccessToken($accessToken);
                }
				catch (Exception $e)
				{
					echo 'Error setting token. Error details: <pre style="color:#ff0000">';
					print_r($e);
				    exit;
				}
                
                $wpdb->update($wpdb->prefix.$this->form_table, array ( 'access_token' => serialize($accessToken) ) , array( 'formid' => $form_id ) );
                
                header("Location: ".get_admin_url()."admin.php?page=cpabc_appointments&cal=".$form_id."&step6=1#configgcal");
                exit;
            }
         }

         
        function add_field_verify ($field, $type = "varchar(255) DEFAULT '' NOT NULL", $table = '')
        {
            global $wpdb;
            if ($table == '')
                $table = $this->form_table;
            $results = $wpdb->get_results("SHOW columns FROM `".$wpdb->prefix.$table."` where field='".$field."'");
            if (!count($results))
            {
                $sql = "ALTER TABLE  `".$wpdb->prefix.$this->form_table."` ADD `".$field."` ".$type;
                $wpdb->query($sql);
            }
        }
        
         
        /**
         * script process payment
         */
		public function apply_addon($id)
		{
            global $wpdb;

            $rows = $wpdb->get_results(
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $id )
					);
            return !(empty( $rows ) || !$rows[0]->enabled);
        }


    } // End Class

    // Main add-on code
    $CPABC_GoogleCalendarAPI_obj = new CPABC_GoogleCalendarAPI();

    global $cpabc_addons_objs_list;
	$cpabc_addons_objs_list[ $CPABC_GoogleCalendarAPI_obj->get_addon_id() ] = $CPABC_GoogleCalendarAPI_obj;
}
?>