<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

if ( ! class_exists( 'SftcyWordformConnectGooglecalendar' ) ) {
	class SftcyWordformConnectGooglecalendar {
		private static $initiated = false;
		public static $output     = [];
		public static $configure_spinning_icon = '<i class="fa-solid fa-gear fa-spin"></i>';

		public function __construct() {
			if ( ! self::$initiated ) {
				self::initiate_hooks();
			}
		}

		private static function initiate_hooks() {
			add_action( 'wp_ajax_wordform_connect_save_googlecalendar_credentials_with_authentication', [ __CLASS__, 'wordform_connect_save_googlecalendar_credentials_with_authentication' ] );
			add_action( 'wp_ajax_wordform_connect_fetch_googlecalendar_calendars', [ __CLASS__, 'wordform_connect_fetch_googlecalendar_calendars' ] );
			add_action( 'wp_ajax_wordform_connect_save_googlecalendar_data_as_wp_option_data', [ __CLASS__, 'wordform_connect_save_googlecalendar_data_as_wp_option_data' ] );
			add_action( 'wp_ajax_wordform_connect_create_googlecalendar_with_form_fields', [ __CLASS__, 'wordform_connect_create_googlecalendar_with_form_fields' ] );

			self::$initiated = true;
		}

		public static function get_googlecalendar_configured_info() {
			$calendar_info = get_option( 'wordform_connect_googlecalendar_info', [] );
			if ( isset( $calendar_info['calendarId'] ) && ! empty( $calendar_info['calendarId'] ) ) {
				return [
					'calendarId'    => sanitize_text_field( (string) $calendar_info['calendarId'] ),
					'calendarLabel' => isset( $calendar_info['calendarLabel'] ) ? sanitize_text_field( (string) $calendar_info['calendarLabel'] ) : '',
				];
			}

			return [];
		}

		public static function get_googlecalendar_token_info() {
			$token_info = get_option( 'wordform_connect_google_calendar_token', [] );
			return is_array( $token_info ) ? $token_info : [];
		}

		public static function get_googlecalendar_authorization_uri() {
			$credentials = SftcyWordformConnectGooglesheet::get_google_credentials();
			if ( ! $credentials ) {
				return '';
			}

			$redirect_params = [
				'response_type' => 'code',
				'client_id'     => $credentials['clientID'],
				'redirect_uri'  => $credentials['clientRedirectUrl'],
				'scope'         => 'https://www.googleapis.com/auth/calendar',
				'access_type'   => 'offline',
				'prompt'        => 'consent',
				'state'         => 'googlecalendar',
			];

			return 'https://accounts.google.com/o/oauth2/auth?' . http_build_query( $redirect_params );
		}

		private static function get_googlecalendar_authorization_uri_from_credentials( $credentials = [] ) {
			if ( ! is_array( $credentials ) || empty( $credentials['clientID'] ) || empty( $credentials['clientRedirectUrl'] ) ) {
				return '';
			}

			$redirect_params = [
				'response_type' => 'code',
				'client_id'     => $credentials['clientID'],
				'redirect_uri'  => $credentials['clientRedirectUrl'],
				'scope'         => 'https://www.googleapis.com/auth/calendar',
				'access_type'   => 'offline',
				'prompt'        => 'consent',
				'state'         => 'googlecalendar',
			];

			return 'https://accounts.google.com/o/oauth2/auth?' . http_build_query( $redirect_params );
		}

		public static function wordform_connect_save_googlecalendar_credentials_with_authentication() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			self::$output = [];
			if ( isset( $_POST['params'] ) && array_filter( $_POST['params'] ) ) {
				$google_client_id     = isset( $_POST['params']['googleClientId'] ) ? sanitize_text_field( trim( $_POST['params']['googleClientId'] ) ) : '';
				$google_client_secret = isset( $_POST['params']['googleClientSecret'] ) ? sanitize_text_field( trim( $_POST['params']['googleClientSecret'] ) ) : '';
				$google_redirect_url  = isset( $_POST['params']['googleRedirectUrl'] ) ? esc_url_raw( trim( $_POST['params']['googleRedirectUrl'] ) ) : '';

				if ( ! empty( $google_client_id ) && ! empty( $google_client_secret ) && ! empty( $google_redirect_url ) ) {
					$google_credentials = [
						'clientID'          => $google_client_id,
						'clientSecret'      => $google_client_secret,
						'clientRedirectUrl' => $google_redirect_url,
					];

					$auth_redirect_uri = self::get_googlecalendar_authorization_uri_from_credentials( $google_credentials );
					if ( empty( $auth_redirect_uri ) ) {
						self::$output['status']  = 'fail';
						self::$output['reason']  = 'Google Calendar authorization URL could not be created.';
						self::$output['comment'] = 'Google Calendar authorization could not be prepared with the provided credentials.';
					} elseif ( update_option( 'wordform_connect_google_credentials', $google_credentials ) ) {
						self::$output['status']          = 'success';
						self::$output['reason']          = 'Google credentials updated successfully.';
						self::$output['comment']         = self::$configure_spinning_icon . ' Credentials saved. Redirecting to Google Calendar authorization...';
						self::$output['authRedirectUri'] = $auth_redirect_uri;
					} else {
						self::$output['status']          = 'warning';
						self::$output['reason']          = 'Google credentials did not change.';
						self::$output['comment']         = self::$configure_spinning_icon . ' Credentials are already saved. Redirecting to Google Calendar authorization...';
						self::$output['authRedirectUri'] = $auth_redirect_uri;
					}
				} else {
					self::$output['status']  = 'fail';
					self::$output['reason']  = 'Required Google credentials are missing.';
					self::$output['comment'] = 'Google Client ID, Client Secret, and Redirect URL are required.';
				}
			} else {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Post parameters are missing.';
				self::$output['comment'] = 'Required Google Calendar credentials are missing.';
			}

			echo wp_json_encode( self::$output, JSON_HEX_AMP );
			wp_die();
		}

		public static function wordform_connect_configure_googlecalendar_authentication( $code = null ) {
			$credentials = SftcyWordformConnectGooglesheet::get_google_credentials();
			if ( is_null( $code ) || ! array_filter( $credentials ) ) {
				SftcyWordformConnectBase::log_connection_configuration_event( 'googlecalendar', 'oauth_callback', 'Google Calendar authorization code or credentials are missing.', array(), 'error' );
				update_option( 'wordform_connect_google_calendar_last_auth_error', 'Google Calendar authorization code or credentials are missing.' );
				return false;
			}

			$response = wp_remote_post(
				'https://oauth2.googleapis.com/token',
				[
					'timeout' => 20,
					'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded' ],
					'body'    => [
						'code'          => $code,
						'client_id'     => $credentials['clientID'],
						'client_secret' => $credentials['clientSecret'],
						'redirect_uri'  => $credentials['clientRedirectUrl'],
						'grant_type'    => 'authorization_code',
					],
				]
			);

			if ( is_wp_error( $response ) ) {
				SftcyWordformConnectBase::log_connection_configuration_event( 'googlecalendar', 'oauth_callback', $response->get_error_message(), array(), 'error' );
				update_option( 'wordform_connect_google_calendar_last_auth_error', $response->get_error_message() );
				return false;
			}

			$response_body = wp_remote_retrieve_body( $response );
			$response_json = json_decode( $response_body, true );
			$access_token  = isset( $response_json['access_token'] ) ? sanitize_text_field( (string) $response_json['access_token'] ) : '';
			$expires_in    = isset( $response_json['expires_in'] ) ? absint( $response_json['expires_in'] ) : 0;
			$refresh_token = isset( $response_json['refresh_token'] ) ? sanitize_text_field( (string) $response_json['refresh_token'] ) : '';
			$refresh_token_expires_in = isset( $response_json['refresh_token_expires_in'] ) ? absint( $response_json['refresh_token_expires_in'] ) : 0;

			if ( empty( $access_token ) || empty( $refresh_token ) ) {
				$error_message = SftcyWordformConnectBase::extract_connect_remote_error_message( $response_body );
				SftcyWordformConnectBase::log_connection_configuration_event( 'googlecalendar', 'oauth_callback', ! empty( $error_message ) ? $error_message : 'Google Calendar did not return a valid access token.', array(), 'error' );
				update_option( 'wordform_connect_google_calendar_last_auth_error', ! empty( $error_message ) ? $error_message : 'Google Calendar did not return a valid access token.' );
				return false;
			}

			$current_timestamp = time();
			$token_info = [
				'access_token'                  => $access_token,
				'refresh_token'                 => $refresh_token,
				'access_token_expire_datetime'  => date( 'Y-m-d H:i:s', $current_timestamp + $expires_in ),
				'refresh_token_expire_datetime' => $refresh_token_expires_in > 0 ? date( 'Y-m-d H:i:s', $current_timestamp + $refresh_token_expires_in ) : '',
				'tokeninfo_updated_datetime'    => date( 'Y-m-d H:i:s', $current_timestamp ),
			];

			$token_saved = false !== update_option( 'wordform_connect_google_calendar_token', $token_info );
			if ( ! $token_saved ) {
				$existing_token_info = self::get_googlecalendar_token_info();
				$token_saved         = isset( $existing_token_info['access_token'], $existing_token_info['refresh_token'] )
					&& $existing_token_info['access_token'] === $token_info['access_token']
					&& $existing_token_info['refresh_token'] === $token_info['refresh_token'];
			}

			if ( ! $token_saved ) {
				SftcyWordformConnectBase::log_connection_configuration_event( 'googlecalendar', 'oauth_callback', 'Google Calendar token information could not be stored.', array(), 'error' );
				update_option( 'wordform_connect_google_calendar_last_auth_error', 'Google Calendar token information could not be stored.' );
				return false;
			}

			$calendar_info = self::get_default_googlecalendar_info( $access_token );
			if ( empty( $calendar_info['calendarId'] ) ) {
				$calendar_info = self::get_googlecalendar_configured_info();
			}
			if ( empty( $calendar_info['calendarId'] ) ) {
				$calendar_info = [
					'calendarId'    => 'primary',
					'calendarLabel' => 'Primary Calendar',
				];
			}

			if ( ! empty( $calendar_info['calendarId'] ) ) {
				update_option( 'wordform_connect_googlecalendar_info', $calendar_info );
				self::save_configured_googlecalendar_application( $calendar_info );
			}

			delete_option( 'wordform_connect_google_calendar_last_auth_error' );
			return true;
		}

		public static function wordform_connect_fetch_googlecalendar_calendars() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$access_token = self::get_googlecalendar_access_token();
			if ( empty( $access_token ) ) {
				echo wp_json_encode( [ 'status' => 'fail', 'comment' => 'Google Calendar authorization is required before calendars can be loaded.' ], JSON_HEX_APOS );
				wp_die();
			}

			$resources = self::fetch_googlecalendar_resources( $access_token );
			if ( isset( $resources['error'] ) ) {
				echo wp_json_encode( [ 'status' => 'fail', 'comment' => $resources['error'] ], JSON_HEX_APOS );
				wp_die();
			}

			if ( empty( $resources ) ) {
				echo wp_json_encode( [ 'status' => 'fail', 'comment' => 'No writable Google Calendars were found for this account.' ], JSON_HEX_APOS );
				wp_die();
			}

			echo wp_json_encode( [ 'status' => 'success', 'comment' => 'Google Calendars loaded successfully.', 'resources' => $resources ], JSON_HEX_APOS );
			wp_die();
		}

		public static function wordform_connect_save_googlecalendar_data_as_wp_option_data() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$calendar_id    = isset( $_POST['params']['googleCalendarId'] ) ? sanitize_text_field( trim( $_POST['params']['googleCalendarId'] ) ) : '';
			$calendar_label = isset( $_POST['params']['googleCalendarLabel'] ) ? sanitize_text_field( trim( $_POST['params']['googleCalendarLabel'] ) ) : '';
			self::$output   = [];

			if ( empty( self::get_googlecalendar_access_token() ) ) {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Google Calendar authorization missing.';
				self::$output['comment'] = 'Authorize Google Calendar first, then load calendars and save the selected calendar.';
			} elseif ( empty( $calendar_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Google Calendar ID missing.';
				self::$output['comment'] = 'Please select or enter a Google Calendar ID.';
			} else {
				$calendar_info = [ 'calendarId' => $calendar_id, 'calendarLabel' => $calendar_label ];
				if ( update_option( 'wordform_connect_googlecalendar_info', $calendar_info ) ) {
					self::$output['status']  = 'success';
					self::$output['reason']  = 'Google Calendar configuration saved.';
					self::$output['comment'] = 'Google Calendar configuration saved successfully.';
				} else {
					self::$output['status']  = 'warning';
					self::$output['reason']  = 'Google Calendar configuration did not change.';
					self::$output['comment'] = 'Google Calendar configuration saved successfully.';
				}
				self::$output['googlecalendarConfiguredInfoStatus'] = self::save_configured_googlecalendar_application( $calendar_info );
				self::$output['configuredApplication'] = SftcyWordformConnectBase::get_configured_application_option_payload( 'googlecalendar' );
			}

			echo wp_json_encode( self::$output, JSON_HEX_APOS );
			wp_die();
		}

		public static function save_configured_googlecalendar_application( $calendar_info = [] ) {
			if ( ! is_array( $calendar_info ) || empty( $calendar_info['calendarId'] ) ) {
				return false;
			}

			$application_slug = 'googlecalendar';
			$application_name = 'Google Calendar';
			$data             = [ 'application_slug' => $application_slug, 'application_name' => $application_name ];

			global $wpdb;
			$table         = $wpdb->prefix . SftcyWordformBase::$sc_wordform_configured_application_tbl;
			$query_results = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE application_slug = %s LIMIT 1', array( $table, $application_slug ) ), ARRAY_A );
			$data['configured_info'] = wp_json_encode([
				'reconfigured'  => $query_results ? 'yes' : 'no',
				'payloadFormat' => 'google-calendar-event',
				'calendarId'    => $calendar_info['calendarId'],
				'calendarLabel' => isset( $calendar_info['calendarLabel'] ) ? $calendar_info['calendarLabel'] : '',
			]);

			if ( $query_results ) {
				$where                     = [ 'id' => $query_results[0]['id'] ];
				$data['configured_status'] = 'active';
				return false !== $wpdb->update( $table, $data, $where );
			}

			return false !== $wpdb->insert( $table, $data );
		}

		private static function fetch_googlecalendar_resources( $access_token = '' ) {
			$access_token = sanitize_text_field( (string) $access_token );
			if ( '' === $access_token ) {
				return [ 'error' => 'Google Calendar authorization is required before calendars can be loaded.' ];
			}

			$response = wp_remote_get(
				'https://www.googleapis.com/calendar/v3/users/me/calendarList?maxResults=250',
				[
					'timeout' => 20,
					'headers' => [
						'Authorization' => 'Bearer ' . $access_token,
						'Accept'        => 'application/json',
					],
				]
			);

			if ( is_wp_error( $response ) ) {
				return [ 'error' => 'Google Calendars could not be loaded right now.' ];
			}

			$status_code   = (int) wp_remote_retrieve_response_code( $response );
			$response_json = json_decode( wp_remote_retrieve_body( $response ), true );
			if ( $status_code < 200 || $status_code >= 300 || ! is_array( $response_json ) ) {
				return [ 'error' => self::build_googlecalendar_api_error_message( $response_json, 'Google Calendar authorization could not be verified. Please reconnect and try again.' ) ];
			}

			$resources = [];
			if ( ! empty( $response_json['items'] ) && is_array( $response_json['items'] ) ) {
				foreach ( $response_json['items'] as $calendar ) {
					if ( empty( $calendar['id'] ) || ( isset( $calendar['accessRole'] ) && 'reader' === $calendar['accessRole'] ) ) {
						continue;
					}

					$calendar_id    = sanitize_text_field( (string) $calendar['id'] );
					$calendar_label = isset( $calendar['summary'] ) && '' !== trim( (string) $calendar['summary'] ) ? sanitize_text_field( (string) $calendar['summary'] ) : $calendar_id;
					if ( ! empty( $calendar['primary'] ) ) {
						$calendar_label .= ' (Primary)';
					}

					$resources[] = [
						'value'   => $calendar_id,
						'label'   => $calendar_label,
						'primary' => ! empty( $calendar['primary'] ),
					];
				}
			}

			return $resources;
		}

		private static function build_googlecalendar_api_error_message( $response_json = [], $fallback_message = '' ) {
			$fallback_message = sanitize_text_field( (string) $fallback_message );
			if ( ! is_array( $response_json ) || empty( $response_json['error'] ) || ! is_array( $response_json['error'] ) ) {
				return $fallback_message;
			}

			$error_data     = $response_json['error'];
			$error_message  = isset( $error_data['message'] ) ? sanitize_text_field( (string) $error_data['message'] ) : $fallback_message;
			$activation_url = '';
			$error_reason   = '';

			if ( ! empty( $error_data['details'] ) && is_array( $error_data['details'] ) ) {
				foreach ( $error_data['details'] as $detail ) {
					if ( ! is_array( $detail ) ) {
						continue;
					}

					if ( empty( $error_reason ) && isset( $detail['reason'] ) ) {
						$error_reason = sanitize_key( (string) $detail['reason'] );
					}

					if ( empty( $activation_url ) && isset( $detail['metadata']['activationUrl'] ) ) {
						$activation_url = esc_url_raw( (string) $detail['metadata']['activationUrl'] );
					}

					if ( empty( $activation_url ) && ! empty( $detail['links'] ) && is_array( $detail['links'] ) ) {
						foreach ( $detail['links'] as $link ) {
							if ( ! empty( $link['url'] ) ) {
								$activation_url = esc_url_raw( (string) $link['url'] );
								break;
							}
						}
					}
				}
			}

			if ( 'service_disabled' === $error_reason || false !== stripos( $error_message, 'disabled' ) || false !== stripos( $error_message, 'accessNotConfigured' ) ) {
				$message = 'Google Calendar API is disabled for this Google Cloud project. Enable the API, wait a few minutes, then try loading calendars again.';
				if ( ! empty( $activation_url ) ) {
					$message .= ' <a href="' . esc_url( $activation_url ) . '" target="_blank" rel="noopener">Enable Google Calendar API</a>';
				}
				return $message;
			}

			return '' !== $error_message ? $error_message : $fallback_message;
		}

		private static function get_default_googlecalendar_info( $access_token = '' ) {
			$resources = self::fetch_googlecalendar_resources( $access_token );
			if ( ! is_array( $resources ) || empty( $resources ) || isset( $resources['error'] ) ) {
				return [];
			}

			$default_resource = null;
			foreach ( $resources as $resource ) {
				if ( ! empty( $resource['primary'] ) ) {
					$default_resource = $resource;
					break;
				}
			}

			if ( null === $default_resource ) {
				$default_resource = $resources[0];
			}

			if ( empty( $default_resource['value'] ) ) {
				return [];
			}

			return [
				'calendarId'    => sanitize_text_field( (string) $default_resource['value'] ),
				'calendarLabel' => isset( $default_resource['label'] ) ? sanitize_text_field( (string) $default_resource['label'] ) : '',
			];
		}

		public static function wordform_connect_create_googlecalendar_with_form_fields() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output = [];
			if ( isset( $_POST['params'] ) && array_filter( $_POST['params'] ) ) {
				$wordform_id                 = isset( $_POST['params']['wordFormID'] ) ? sanitize_text_field( $_POST['params']['wordFormID'] ) : '';
				$wordform_name               = isset( $_POST['params']['wordFormName'] ) ? sanitize_text_field( $_POST['params']['wordFormName'] ) : '';
				$configured_application_id   = isset( $_POST['params']['applicationID'] ) ? absint( $_POST['params']['applicationID'] ) : 0;
				$configured_application_name = isset( $_POST['params']['applicationName'] ) ? sanitize_text_field( $_POST['params']['applicationName'] ) : '';

				if ( ! empty( $wordform_id ) && ! empty( $configured_application_id ) ) {
					$form_fields = SftcyWordformBuildForm::wordform_get_field_names( $wordform_id );
					if ( $form_fields && array_filter( $form_fields ) ) {
						$calendar_info = self::get_googlecalendar_configured_info();
						if ( ! empty( $calendar_info['calendarId'] ) && ! empty( self::get_googlecalendar_access_token() ) ) {
							$connection_info = [
								'applicationName'     => $configured_application_name,
								'formName'            => $wordform_name,
								'formFields'          => $form_fields,
								'payloadFormat'       => 'google-calendar-event',
								'calendarId'          => $calendar_info['calendarId'],
								'calendarLabel'       => isset( $calendar_info['calendarLabel'] ) ? $calendar_info['calendarLabel'] : '',
								'connectionUpdatedAt' => current_time( 'mysql' ),
							];
							$insertdata = [
								'configured_application_tbl_id' => $configured_application_id,
								'wordform_id'                   => $wordform_id,
								'connection_info'               => wp_json_encode( $connection_info ),
							];
							$db_result = SftcyWordformConnectBase::wordform_save_connected_application_info( $insertdata );
							if ( false !== $db_result ) {
								self::$output['status']              = 'success';
								self::$output['formFields']          = $form_fields;
								self::$output['formName']            = $wordform_name;
								self::$output['reason']              = 'Google Calendar connected successfully.';
								self::$output['comment']             = 'Google Calendar connected successfully.';
								self::$output['connectedInfoStored'] = $db_result;
							} else {
								self::$output['status']  = 'fail';
								self::$output['reason']  = 'Connection info storing failed.';
								self::$output['comment'] = 'Could not create Google Calendar connection record.';
							}
						} else {
							self::$output['status']  = 'fail';
							self::$output['reason']  = 'Google Calendar configuration missing.';
							self::$output['comment'] = 'Authorize Google Calendar and save a target calendar before creating the connection.';
						}
					} else {
						self::$output['status']  = 'fail';
						self::$output['reason']  = 'WordForm form fields are not available.';
						self::$output['comment'] = 'WordForm fields not found for selected form.';
					}
				} else {
					self::$output['status']  = 'fail';
					self::$output['reason']  = 'WordForm ID or configured application ID missing.';
					self::$output['comment'] = 'Required connection fields are missing.';
				}
			} else {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Post parameters are missing.';
				self::$output['comment'] = 'Required post parameters are missing.';
			}

			echo wp_json_encode( self::$output, JSON_HEX_AMP );
			wp_die();
		}

		private static function extract_googlecalendar_event_slot( $forms_data = [] ) {
			$candidates = [];
			$timezone = function_exists( 'wp_timezone' ) ? wp_timezone() : new DateTimeZone( 'UTC' );
			$timezone_string = $timezone instanceof DateTimeZone ? $timezone->getName() : 'UTC';

			if ( ! is_array( $forms_data ) || ! array_filter( $forms_data ) ) {
				return [];
			}

			foreach ( $forms_data as $field_info ) {
				$field_type  = isset( $field_info['formFieldType'] ) ? sanitize_key( $field_info['formFieldType'] ) : '';
				$field_value = isset( $field_info['formRawValue'] ) && in_array( $field_type, array( 'date', 'datetime' ), true )
					? trim( str_replace( 'T', ' ', (string) $field_info['formRawValue'] ) )
					: trim( (string) ( $field_info['formFieldValues'] ?? '' ) );
				if ( '' === $field_value ) {
					continue;
				}
				$normalized_value = str_replace( ' ', 'T', $field_value );
				if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $field_value ) ) {
					$candidates[] = [ 'type' => 'date', 'value' => $field_value ];
					continue;
				}
				if ( preg_match( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/', $normalized_value ) ) {
					$candidates[] = [ 'type' => 'datetime', 'value' => $normalized_value ];
				}
			}

			if ( empty( $candidates ) ) {
				return [];
			}

			$start_candidate = $candidates[0];
			if ( 'datetime' === $start_candidate['type'] ) {
				$start_datetime = new DateTime( $start_candidate['value'], $timezone );
				$end_datetime   = clone $start_datetime;
				if ( isset( $candidates[1] ) && 'datetime' === $candidates[1]['type'] ) {
					$second_datetime = new DateTime( $candidates[1]['value'], $timezone );
					if ( $second_datetime > $start_datetime ) {
						$end_datetime = $second_datetime;
					} else {
						$end_datetime->modify( '+1 hour' );
					}
				} else {
					$end_datetime->modify( '+1 hour' );
				}

				return [
					'start' => [ 'dateTime' => $start_datetime->format( DateTime::RFC3339 ), 'timeZone' => $timezone_string ],
					'end'   => [ 'dateTime' => $end_datetime->format( DateTime::RFC3339 ), 'timeZone' => $timezone_string ],
				];
			}

			$start_date = new DateTime( $start_candidate['value'], $timezone );
			$end_date   = clone $start_date;
			$end_date->modify( '+1 day' );

			return [
				'start' => [ 'date' => $start_date->format( 'Y-m-d' ) ],
				'end'   => [ 'date' => $end_date->format( 'Y-m-d' ) ],
			];
		}

		public static function wordform_send_forms_data_into_googlecalendar( $forms_data = [], $calendar_info = [] ) {
			$send_info                    = [];
			$send_info['applicationSlug'] = 'googlecalendar';
			if ( ! is_array( $forms_data ) || ! array_filter( $forms_data ) ) {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'Processed submission fields are empty.';
				$send_info['comment'] = 'No WordForm submission fields found for Google Calendar.';
				return $send_info;
			}

			$calendar_id  = isset( $calendar_info['calendarId'] ) ? sanitize_text_field( (string) $calendar_info['calendarId'] ) : '';
			$access_token = self::get_googlecalendar_access_token();
			if ( empty( $calendar_id ) || empty( $access_token ) ) {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'Google Calendar configuration incomplete.';
				$send_info['comment'] = 'Google Calendar authorization or selected calendar is missing.';
				return $send_info;
			}

			$event_slot = self::extract_googlecalendar_event_slot( $forms_data );
			if ( empty( $event_slot['start'] ) || empty( $event_slot['end'] ) ) {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'Date or Datetime field not found in this form submission.';
				$send_info['comment'] = 'Google Calendar requires at least one valid Date or Datetime field in the connected form to create an event.';
				return $send_info;
			}

			$contact_properties = SftcyWordformConnectBase::extract_common_contact_properties_from_submission_fields( $forms_data );
			$fields_map         = SftcyWordformConnectBase::extract_submission_fields_map( $forms_data );
			$description_lines  = [];
			foreach ( $fields_map as $field_label => $field_value ) {
				$description_lines[] = $field_label . ': ' . $field_value;
			}

			$summary = 'WordForm Submission';
			if ( ! empty( $contact_properties['firstName'] ) ) {
				$summary .= ' - ' . $contact_properties['firstName'];
				if ( ! empty( $contact_properties['lastName'] ) ) {
					$summary .= ' ' . $contact_properties['lastName'];
				}
			} elseif ( ! empty( $contact_properties['email'] ) ) {
				$summary .= ' - ' . $contact_properties['email'];
			}

			$request_body = [
				'summary'     => $summary,
				'description' => implode( "\n", $description_lines ),
				'start'       => $event_slot['start'],
				'end'         => $event_slot['end'],
			];

			$response = wp_remote_post(
				'https://www.googleapis.com/calendar/v3/calendars/' . rawurlencode( $calendar_id ) . '/events',
				[
					'timeout' => 20,
					'headers' => [
						'Authorization' => 'Bearer ' . $access_token,
						'Accept'        => 'application/json',
						'Content-Type'  => 'application/json; charset=utf-8',
					],
					'body'    => wp_json_encode( $request_body ),
				]
			);

			if ( is_wp_error( $response ) ) {
				$send_info['status']       = 'fail';
				$send_info['reason']       = 'Google Calendar request failed.';
				$send_info['requestError'] = $response->get_error_message();
				$send_info['comment']      = 'Google Calendar API request could not be completed.';
				return $send_info;
			}

			$status_code   = (int) wp_remote_retrieve_response_code( $response );
			$response_body = wp_remote_retrieve_body( $response );
			$response_json = json_decode( $response_body, true );
			$send_info['responseStatusCode'] = $status_code;

			if ( $status_code >= 200 && $status_code < 300 ) {
				$send_info['status']  = 'success';
				$send_info['reason']  = 'Form submission data sent to Google Calendar.';
				$send_info['comment'] = 'Google Calendar event created successfully.';
				if ( is_array( $response_json ) && isset( $response_json['id'] ) ) {
					$send_info['eventId'] = sanitize_text_field( (string) $response_json['id'] );
				}
				if ( is_array( $response_json ) && isset( $response_json['htmlLink'] ) ) {
					$send_info['eventUrl'] = esc_url_raw( $response_json['htmlLink'] );
				}
			} else {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'Google Calendar response status indicates failure.';
				$send_info['comment'] = 'Google Calendar API returned non-success HTTP status.';
				if ( is_array( $response_json ) && isset( $response_json['error']['message'] ) ) {
					$send_info['responseMessage'] = substr( sanitize_textarea_field( (string) $response_json['error']['message'] ), 0, 500 );
				} else {
					$send_info['responseBody'] = substr( sanitize_textarea_field( (string) $response_body ), 0, 500 );
				}
			}

			return $send_info;
		}

		public static function is_googlecalendar_access_token_expired() {
			$current_datetime = new DateTime( 'now' );
			$token_info       = self::get_googlecalendar_token_info();
			if ( isset( $token_info['access_token'], $token_info['access_token_expire_datetime'] ) ) {
				$access_token_expired_datetime = new DateTime( $token_info['access_token_expire_datetime'] );
				return $current_datetime >= $access_token_expired_datetime;
			}
			return true;
		}

		public static function is_googlecalendar_refresh_token_expired() {
			$current_datetime = new DateTime( 'now' );
			$token_info       = self::get_googlecalendar_token_info();
			if ( isset( $token_info['refresh_token'], $token_info['refresh_token_expire_datetime'] ) && ! empty( $token_info['refresh_token_expire_datetime'] ) ) {
				$refresh_token_expired_datetime = new DateTime( $token_info['refresh_token_expire_datetime'] );
				return $current_datetime >= $refresh_token_expired_datetime;
			} elseif ( isset( $token_info['refresh_token'], $token_info['refresh_token_expire_datetime'] ) && empty( $token_info['refresh_token_expire_datetime'] ) ) {
				return false;
			}
			return true;
		}

		public static function is_googlecalendar_authentication_required() {
			return self::is_googlecalendar_refresh_token_expired();
		}

		public static function get_googlecalendar_access_token() {
			$token_info = self::get_googlecalendar_token_info();
			if ( isset( $token_info['access_token'] ) && ! empty( $token_info['access_token'] ) && ! self::is_googlecalendar_access_token_expired() ) {
				return $token_info['access_token'];
			} elseif ( isset( $token_info['access_token'] ) && ! empty( $token_info['access_token'] ) && self::is_googlecalendar_access_token_expired() ) {
				$access_token = self::fetch_new_googlecalendar_access_token();
				if ( $access_token && ! empty( $access_token ) ) {
					return $access_token;
				}
			}
			return false;
		}

		public static function fetch_new_googlecalendar_access_token() {
			$access_token       = '';
			$google_credentials = SftcyWordformConnectGooglesheet::get_google_credentials();
			$token_info         = self::get_googlecalendar_token_info();
			if ( isset( $google_credentials['clientID'], $google_credentials['clientSecret'], $token_info['refresh_token'] ) && ! empty( $google_credentials['clientID'] ) && ! empty( $google_credentials['clientSecret'] ) && ! empty( $token_info['refresh_token'] ) ) {
				$response = wp_remote_post(
					'https://oauth2.googleapis.com/token',
					[
						'timeout' => 20,
						'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded' ],
						'body'    => [
							'client_id'     => $google_credentials['clientID'],
							'client_secret' => $google_credentials['clientSecret'],
							'refresh_token' => $token_info['refresh_token'],
							'grant_type'    => 'refresh_token',
						],
					]
				);
				if ( is_wp_error( $response ) ) {
					return '';
				}
				$response_refresh_token = json_decode( wp_remote_retrieve_body( $response ), true );
				$access_token = isset( $response_refresh_token['access_token'] ) ? sanitize_text_field( (string) $response_refresh_token['access_token'] ) : '';
				$access_token_expires_in = isset( $response_refresh_token['expires_in'] ) ? absint( $response_refresh_token['expires_in'] ) : 0;
				$refresh_token_expires_in = isset( $response_refresh_token['refresh_token_expires_in'] ) ? absint( $response_refresh_token['refresh_token_expires_in'] ) : 0;
				$current_timestamp = time();
				if ( ! empty( $access_token ) ) {
					update_option( 'wordform_connect_google_calendar_token', [
						'access_token'                  => $access_token,
						'refresh_token'                 => $token_info['refresh_token'],
						'access_token_expire_datetime'  => date( 'Y-m-d H:i:s', $current_timestamp + $access_token_expires_in ),
						'refresh_token_expire_datetime' => $refresh_token_expires_in > 0 ? date( 'Y-m-d H:i:s', $current_timestamp + $refresh_token_expires_in ) : '',
						'tokeninfo_updated_datetime'    => date( 'Y-m-d H:i:s', $current_timestamp ),
					] );
				}
			}
			return $access_token;
		}

		public static function is_googlecalendar_configured_status_active() {
			global $wpdb;
			$table         = $wpdb->prefix . SftcyWordformBase::$sc_wordform_configured_application_tbl;
			$query_results = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE application_slug = %s LIMIT 1', array( $table, 'googlecalendar' ) ), ARRAY_A );
			return $query_results && isset( $query_results[0]['configured_status'] ) && 'active' === $query_results[0]['configured_status'];
		}
	}
}
