<?php
if (!defined('ABSPATH')) {
	exit;
}

/**
 * WPSSLWP_Service Class
 *
 * @package wpsyncsheets-wpforms
 */

/**
 * WPSyncSheets Lite For WPForms integration.
 *
 * @since 1.1.0
 * @package wpsyncsheets-wpforms
 */
if (class_exists('WPForms_Provider')) {
	class WPSSLWP_Service extends WPForms_Provider
	{
		/**
		 * Plugin Version
		 *
		 * @var $version
		 */
		public $version = WPSSLWP_VERSION;
		/**
		 * Plugin Slug
		 *
		 * @var $slug
		 */
		public $slug = 'wpsyncsheets-wpforms';
		/**
		 * Plugin Name
		 *
		 * @var $name
		 */
		public $name = 'WPSyncSheets Lite For WPForms';
		/**
		 * Plugin Short-Title
		 *
		 * @var $short_title
		 */
		public $short_title = 'WPSyncSheets';
		/**
		 * Plugin Icon
		 *
		 * @var $icon
		 */
		public $icon = WPSSLWP_URL . 'assets/images/addon-icon-wpsyncsheets.svg';
		/**
		 * Instance of class.
		 *
		 * @var $instance Instance variable of class.
		 */
		private static $instance = null;
		/**
		 * Instance of WPSSLWP_Google_API_Functions class.
		 *
		 * @var $instance_api Instance variable of WPSSLWP_Google_API_Functions class.
		 */
		private static $instance_api = null;
		/**
		 * Instance of Google API service.
		 *
		 * @var $instance_service Instance variable of Google API service.
		 */
		private static $instance_service = null;
		/**
		 * Get an instance of this class.
		 *
		 * @return instance
		 */
		public static function get_instance()
		{
			if (null === self::$instance) {
				self::$instance = new WPSSLWP_Service();
			}
			return self::$instance;
		}
		/**
		 * Get an instance of WPSSLWP_Google_API_Functions class.
		 *
		 * @return WPSSLWP_Google_API_Functions class instance
		 */
		public static function get_clientinstance()
		{
			if (null === self::$instance_api) {
				self::$instance_api = new WPSyncSheets_WPForms\WPSSLWP_Google_API_Functions();
			}
			return self::$instance_api;
		}
		/**
		 * Initialize.
		 *
		 * @since 1.0
		 */
		public function init()
		{
			add_action('wpforms_builder_save_form', array($this, 'wpsslwp_save_settings'), 10, 2);
			add_action('wp_ajax_wpsslwp_reset_settings', array($this, 'wpsslwp_reset_settings'));
			add_action('wp_ajax_wpsslwp_clear_sheet', array($this, 'wpsslwp_clear_sheet'), 50, 1);
			$this->get_clientinstance();
		}
		/**
		 * Function to save WPSyncsheets Lite for WPForms plugin settings
		 *
		 * @since 1.0
		 * @param int   $form_id .
		 * @param array $data .
		 */
		public function wpsslwp_save_settings($form_id = '', $data = array())
		{
			
			if (isset($data['wpsswpf_settings']['wpsyncsheets-wpforms']['enable'])) {

				if (!isset($data['wpsslwp_general_settings']) || !wp_verify_nonce($data['wpsslwp_general_settings'], 'save_general_settings')) {
					wp_send_json_error(esc_html__('Something went wrong while saving the form.', 'wpsyncsheets-wpforms'));
				}

				$wpsslwp_existingsheets = array();
				$wpsslwp_sheetheaders = array();
				$sheet_headers = array();
				$wpsslwp_settings = $data['wpsswpf_settings'][$this->slug];
				$wpsslwp_spreadsheet_id = (isset($wpsslwp_settings['is_createanew_spreadsheet']) && 1 === (int)$wpsslwp_settings['is_createanew_spreadsheet']) ? 'new' : $wpsslwp_settings['spreadsheet_id'];
				$wpsslwp_sheet_name = isset($wpsslwp_settings['sheetname']) ? trim($wpsslwp_settings['sheetname']) : '';
				if (empty($wpsslwp_spreadsheet_id) || empty($wpsslwp_sheet_name)) {
					wp_send_json_error(esc_html__('Add spreadsheet and sheet details.', 'wpsyncsheets-wpforms'));
				}
				$data['wpsswpf_settings'][$this->slug]['sheetname'] = $wpsslwp_sheet_name;
				$wpsslwp_newspreadsheet = '';
				$update_form_data = 1;

				$is_sheet_headers_enabled = false;

				foreach ($wpsslwp_settings as $skey => $sval) {
					if (substr($skey, 0, 13) === 'sheetheaders-') {
						$is_sheet_headers_enabled = true;
						break;
					}
				}
				if ( false === $is_sheet_headers_enabled ) {
					wp_send_json_error(esc_html__('Please select at least one sheet header to continue.', 'wpsyncsheets-wpforms'));
				}
				
				if ('new' === (string)$wpsslwp_spreadsheet_id) {
					$wpsslwp_newspreadsheet = 'new';
					$wpsslwp_newsheetname = $wpsslwp_settings['newspreadsheetname'];
					$wpsslwp_newsheetname = trim($wpsslwp_newsheetname);
					$requestbody = self::$instance_api->newspreadsheetobject($wpsslwp_newsheetname, $wpsslwp_sheet_name);
					$response = self::$instance_api->createspreadsheet($requestbody);
					// phpcs:ignore
					$wpsslwp_spreadsheet_id = $response->spreadsheetId;
					$wpsslwp_range = "'" . trim($wpsslwp_sheet_name) . "'!A1";
					$data['wpsswpf_settings'][$this->slug]['spreadsheet_id'] = $wpsslwp_spreadsheet_id;
					$data['wpsswpf_settings'][$this->slug]['newspreadsheetname'] = '';
					$data['wpsswpf_settings'][$this->slug]['is_createanew_spreadsheet'] = 0;
					$wpsslwp_settings['spreadsheet_id'] = $wpsslwp_spreadsheet_id;
					$update_form_data = 1;

				}


				$response = self::$instance_api->get_sheet_listing($wpsslwp_spreadsheet_id);
				$wpsslwp_existingsheets = self::$instance_api->get_sheet_list($response);

				$wpsslwp_old_header_order = self::$instance_api->wpsslwp_option('wpsswp_active_headers', '', $form_id);
				$wpsslwp_old_header_order = isset($wpsslwp_old_header_order[0]) ? $wpsslwp_old_header_order[0] : array();

				$wpsslwp_sheet_headers = array();
				$wpsslwp_form_fields = isset($data['fields']) ? $data['fields'] : array();
				$wpsslwp_sheetheaders_array_withid = self::wpsslwp_prepare_header($wpsslwp_form_fields, $form_id, true);
				$wpsslwp_version = self::$instance_api->wpsslwp_option('wpsswp_form_version', '', $form_id);

				if (!array_key_exists($wpsslwp_sheet_name, $wpsslwp_existingsheets)) {
					$param = array();
					$param['spreadsheetid'] = $wpsslwp_spreadsheet_id;
					$param['sheetname'] = $wpsslwp_sheet_name;
					$wpsslwp_response = self::$instance_api->newsheetobject($param);
					$wpsslwp_range = "'" . trim($wpsslwp_sheet_name) . "'!A1";
					if ('new' === (string)$wpsslwp_newspreadsheet) {
						$wpsslwp_deleteresponse = self::$instance_api->deletesheetobject($param);
					}
					$response = self::$instance_api->get_sheet_listing($wpsslwp_spreadsheet_id);
					$wpsslwp_existingsheets = self::$instance_api->get_sheet_list($response);
				}
				foreach ($wpsslwp_settings as $key => $val) {
					if (substr($key, 0, 13) === 'sheetheaders-') {
						$wpsslwp_header_key = substr($key, 13);

						if (1 !== (int)$val) {
							$wpsslwp_sheetheaders[$wpsslwp_header_key] = trim($val);
							$data['wpsswpf_settings'][$this->slug][$key] = 1;
							$update_form_data = 1;
						}
						else {
							if (!empty($wpsslwp_version) && true === array_key_exists($wpsslwp_header_key, $wpsslwp_old_header_order)) {
								$wpsslwp_sheetheaders[$wpsslwp_header_key] = trim($wpsslwp_old_header_order[$wpsslwp_header_key]);
							}
							elseif (true === array_key_exists($wpsslwp_header_key, $wpsslwp_sheetheaders_array_withid)) {
								$headername = strtolower(trim($wpsslwp_sheetheaders_array_withid[$wpsslwp_header_key]));

								if (in_array($headername, array_map('strtolower', $wpsslwp_old_header_order), true)) {
									$wpsslwp_old_key = array_search($headername, array_map('strtolower', $wpsslwp_old_header_order), true);
									$headername = $wpsslwp_old_header_order[$wpsslwp_old_key];

									$wpsslwp_sheetheaders[$wpsslwp_header_key] = $headername;
								}
								else {

									$wpsslwp_sheetheaders[$wpsslwp_header_key] = trim($wpsslwp_sheetheaders_array_withid[$wpsslwp_header_key]);
								}
							}
							else {
								$wpsslwp_sheetheaders[$wpsslwp_header_key] = ucfirst(trim(str_replace('-', ' ', substr($key, 13))));
							}
						}
					}
				}

				$data['wpsswp_settings']['wpsswp'] = $data['wpsswpf_settings'][$this->slug];
				wpforms()->form->update($form_id, $data);

				if (!isset($wpsslwp_sheetheaders['submission_date']) && isset($data['wpsswp_settings']['wpsswp']['submission_date']) && 1 === (int)$data['wpsswp_settings']['wpsswp']['submission_date']) {
					$wpsslwp_sheetheaders['submission_date'] = 'Submission Date';
				}
				if (!isset($wpsslwp_sheetheaders['submission_time']) && isset($data['wpsswp_settings']['wpsswp']['submission_time']) && 1 === (int)$data['wpsswp_settings']['wpsswp']['submission_time']) {
					$wpsslwp_sheetheaders['submission_time'] = 'Submission Time';
				}
				$wpsslwp_sheetid = '';
				if (array_key_exists($wpsslwp_sheet_name, $wpsslwp_existingsheets)) {
					$wpsslwp_sheetid = $wpsslwp_existingsheets[$wpsslwp_sheet_name];
				}

				$wpsslwp_active_headers = $wpsslwp_sheetheaders;

				if ($wpsslwp_version) {
					foreach ($wpsslwp_sheetheaders as $header_key => $header_val) {
						if (true === array_key_exists($header_key, $wpsslwp_old_header_order) && $header_val !== $wpsslwp_old_header_order[$header_key]) {
							$wpsslwp_old_header_order[$header_key] = $header_val;
						}
					}
				}
				else {
					$sheet = "'" . $wpsslwp_sheet_name . "'!A1:ZZ1";
					$all_entry = self::$instance_api->get_row_list($wpsslwp_spreadsheet_id, $sheet);
					$entrydata = $all_entry->getValues();
					$sheet_headers = isset($entrydata[0]) ? $entrydata[0] : array();

					foreach ($sheet_headers as $sheet_header) {
						$sheet_header = strtolower($sheet_header);
						if (in_array($sheet_header, array_map('strtolower', $wpsslwp_old_header_order), true) && in_array($sheet_header, array_map('strtolower', $wpsslwp_sheet_headers), true)) {
							$wpsslwp_old_header_key = array_search($sheet_header, array_map('strtolower', $wpsslwp_old_header_order), true);
							$wpsslwp_sheet_header_key = array_search($sheet_header, array_map('strtolower', $wpsslwp_sheet_headers), true);
							$header_value = $wpsslwp_sheet_headers[$wpsslwp_sheet_header_key];
							$wpsslwp_old_header_order[$wpsslwp_old_header_key] = $header_value;
						}
					}
				}

				$wpsslwp_sheetheaders = array_values($wpsslwp_sheetheaders);
				$wpsslwp_old_header_order = array_values($wpsslwp_old_header_order);

				if ($wpsslwp_old_header_order !== $wpsslwp_sheetheaders) {
					// Delete deactivate column from sheet.
					$wpsslwp_column = array_diff($wpsslwp_old_header_order, $wpsslwp_sheetheaders);

					if (!$wpsslwp_column) {
						$wpsslwp_column = array();
					}
					if (!empty($wpsslwp_column)) {
						$wpsslwp_column = array_reverse($wpsslwp_column, true);
						$deleterequestarray = array();
						foreach ($wpsslwp_column as $columnindex => $columnval) {
							unset($wpsslwp_old_header_order[$columnindex]);
							$wpsslwp_old_header_order = array_values($wpsslwp_old_header_order);
							if ($wpsslwp_sheetid) {
								$param = array();
								$startindex = $columnindex;
								$endindex = $columnindex + 1;
								$param = self::$instance_api->prepare_param($wpsslwp_sheetid, $startindex, $endindex);
								$deleterequestarray[] = self::$instance_api->deleteDimensionrequests($param);
							}
						}
						try {
							if (!empty($deleterequestarray)) {
								$param = array();
								$param['spreadsheetid'] = $wpsslwp_spreadsheet_id;
								$param['requestarray'] = $deleterequestarray;
								$wpsslwp_response = self::$instance_api->updatebachrequests($param);
							}
						}
						catch (Exception $e) {
							wpforms_log('WPSyncSheets For WPForms Error', $e->getMessage(), array('type' => 'error'));
						}
					}
				}

				if ($wpsslwp_old_header_order !== $wpsslwp_sheetheaders) {
					$requestarray = array();
					foreach ($wpsslwp_sheetheaders as $key => $hname) {
						$wpsslwp_startindex = array_search($hname, $wpsslwp_old_header_order, true);

						if (false !== $wpsslwp_startindex && (isset($wpsslwp_old_header_order[$key]) && $wpsslwp_old_header_order[$key] !== $hname)) {
							unset($wpsslwp_old_header_order[$wpsslwp_startindex]);

							$wpsslwp_old_header_order = array_merge(array_slice($wpsslwp_old_header_order, 0, $key), array(0 => $hname), array_slice($wpsslwp_old_header_order, $key, count($wpsslwp_old_header_order) - $key));

							$wpsslwp_endindex = $wpsslwp_startindex + 1;
							$wpsslwp_destindex = $key;

							if ($wpsslwp_sheetid) {
								$param = array();
								$param = self::$instance_api->prepare_param($wpsslwp_sheetid, $wpsslwp_startindex, $wpsslwp_endindex);
								$param['destindex'] = $wpsslwp_destindex;
								$requestarray[] = self::$instance_api->moveDimensionrequests($param);
							}
						}
						elseif (false === $wpsslwp_startindex) {
							$wpsslwp_old_header_order = array_merge(array_slice($wpsslwp_old_header_order, 0, $key), array(0 => $hname), array_slice($wpsslwp_old_header_order, $key, count($wpsslwp_old_header_order) - $key));
							if ($wpsslwp_sheetid) {
								$param = array();
								$wpsslwp_startindex = $key;
								$wpsslwp_endindex = $key + 1;
								$param = self::$instance_api->prepare_param($wpsslwp_sheetid, $wpsslwp_startindex, $wpsslwp_endindex);

								$requestarray[] = self::$instance_api->insertdimensionrequests($param);
							}
						}
					}

					if (!empty($requestarray)) {
						$param = array();
						$param['spreadsheetid'] = $wpsslwp_spreadsheet_id;
						$param['requestarray'] = $requestarray;
						$wpsslwp_response = self::$instance_api->updatebachrequests($param);
					}
				}
				if ($wpsslwp_sheetid) {
					$wpsslwp_range = "'" . trim($wpsslwp_sheet_name) . "'!A1";
					$values = array($wpsslwp_sheetheaders);
					$param_arr['values'] = $values;
					$param_arr['inputoption'] = 'USER_ENTERED';
					$param_arr['spreadsheet_id'] = $wpsslwp_spreadsheet_id;
					$param_arr['range'] = $wpsslwp_range;
					$param = self::set_parameter($param_arr);
					$wpsslwp_response = self::$instance_api->updateentry($param);
				}

				if (!array_key_exists($wpsslwp_sheet_name, $wpsslwp_existingsheets)) {

					$values = array($wpsslwp_sheetheaders);
					$param_arr['values'] = $values;
					$param_arr['inputoption'] = 'USER_ENTERED';
					$param_arr['spreadsheet_id'] = $wpsslwp_spreadsheet_id;
					$param_arr['range'] = $wpsslwp_range;
					$param = self::set_parameter($param_arr);
					$response = self::$instance_api->appendentry($param);
				}
				if (isset($wpsslwp_settings['freeze_headers'])) {
					$wpsslwp_freeze = 1;
				}
				else {
					$wpsslwp_freeze = 0;
				}
				$response = self::$instance_api->get_sheet_listing($wpsslwp_spreadsheet_id);
				$existingsheetsnames = self::$instance_api->get_sheet_list($response);
				$sheetid = $existingsheetsnames[$wpsslwp_sheet_name];
				foreach ($response->getSheets() as $key => $value) {
					if ($wpsslwp_sheet_name === (string)$value['properties']['title']) {
						$requestbody = self::$instance_api->freezeobject($value['properties']['sheetId'], $wpsslwp_freeze);
						$requestobject = array();
						$requestobject['spreadsheetid'] = $wpsslwp_spreadsheet_id;
						$requestobject['requestbody'] = $requestbody;
						self::$instance_api->formatsheet($requestobject);
					}
				}
				update_post_meta($form_id, 'wpsswp_form_version', WPSSLWP_VERSION);
				update_post_meta($form_id, 'wpsswp_active_headers', $wpsslwp_active_headers);
				update_post_meta($form_id, 'wpsswp_form_settings', $wpsslwp_settings);
				return;
			}
		}
		/**
		 * Process and submit entry to provider.
		 *
		 * @since 1.1.0
		 *
		 * @param array $fields WPForms form array of fields.
		 * @param array $entry .
		 * @param array $form_data .
		 * @param int   $entry_id .
		 */
		public function process_entry($fields, $entry, $form_data, $entry_id)
		{
			if (!self::$instance_api->checkcredenatials()) {
				return;
			}
			$error = false;
			// Check if wpsslwp exists.
			if (empty($form_data['wpsswpf_settings'][$this->slug])) {
				return;
			}
			// Check required wpsslwp settings.
			$wpsslwp_settings = $form_data['wpsswpf_settings'][$this->slug];
			if (!isset($wpsslwp_settings['enable']) || 1 !== (int)$wpsslwp_settings['enable'] || empty($wpsslwp_settings['spreadsheet_id'])) {
				return;
			}
			$wpsslwp_spreadsheet_id = $wpsslwp_settings['spreadsheet_id'];
			$wpsslwp_sheet_name = $wpsslwp_settings['sheetname'];

			if (empty($wpsslwp_spreadsheet_id) || empty($wpsslwp_sheet_name) || 'new' === (string)$wpsslwp_spreadsheet_id) {
				return;
			}
			$wpsslwp_spreadsheet_list = self::list_googlespreedsheet();
			$response = self::$instance_api->get_sheet_listing($wpsslwp_spreadsheet_id);
			$sheets = array();
			foreach ($response->getSheets() as $s) {
				$sheets[] = $s['properties']['title'];
			}
			if ((!empty($wpsslwp_spreadsheet_id) && !array_key_exists($wpsslwp_spreadsheet_id, $wpsslwp_spreadsheet_list)) || (!empty($wpsslwp_sheet_name) && !in_array($wpsslwp_sheet_name, $sheets, true))) {
				return;
			}

			$wpsslwp_data_value = array();
			$wpsslwp_data_value = self::wpsslwp_prepare_header_values($fields, $form_data);
			$wpsslwp_version = self::$instance_api->wpsslwp_option('wpsswp_form_version', '', $form_data['id']);

			if ($wpsslwp_version) {
				$wpsslwp_active_headers = self::$instance_api->wpsslwp_option('wpsswp_active_headers', '', $form_data['id']);
				$wpsslwp_active_headers = isset($wpsslwp_active_headers[0]) ? $wpsslwp_active_headers[0] : array();
				$datekey = array_search('Submission Date', array_values($wpsslwp_active_headers), true);
				$timekey = array_search('Submission Time', array_values($wpsslwp_active_headers), true);
			}
			else {
				$sheet = "'" . $wpsslwp_sheet_name . "'!A1:ZZ1";
				$allentry = self::$instance_api->get_row_list($wpsslwp_spreadsheet_id, $sheet);
				$data = $allentry->getValues();
				$sheet_headers = $data[0];
				$datekey = array_search('Submission Date', $sheet_headers, true);
				$timekey = array_search('Submission Time', $sheet_headers, true);
			}

			if (isset($wpsslwp_settings['submission_date'])) {
				$wpsslwp_format = get_option('date_format');
				if ($datekey) {
					$wpsslwp_data_value[$datekey] = date_i18n($wpsslwp_format);
				}
				else {
					$wpsslwp_data_value[] = date_i18n($wpsslwp_format);
				}
			}
			elseif (false !== $datekey) {
				$wpsslwp_data_value[$datekey] = '';
			}
			if (isset($wpsslwp_settings['submission_time'])) {
				$wpsslwp_format = get_option('time_format');
				if ($timekey) {
					$wpsslwp_data_value[$timekey] = date_i18n($wpsslwp_format);
				}
				else {
					$wpsslwp_data_value[] = date_i18n($wpsslwp_format);
				}
			}
			elseif ($timekey) {
				$wpsslwp_data_value[$timekey] = '';
			}
			ksort($wpsslwp_data_value);
			$wpsslwp_data_value = array_values($wpsslwp_data_value);
			$response = self::$instance_api->get_sheet_listing($wpsslwp_spreadsheet_id);
			$wpsslwp_existingsheets = self::$instance_api->get_sheet_list($response);
			if (!array_key_exists($wpsslwp_sheet_name, $wpsslwp_existingsheets)) {
				wpforms_log(
					esc_html__('WPSyncSheets Lite For WPForms : Sheet not exist', 'wpsyncsheets-wpforms'),
					$fields
				);
				return;
			}
			$sheet = "'" . $wpsslwp_sheet_name . "'!A:Z";
			$allentry = self::$instance_api->get_row_list($wpsslwp_spreadsheet_id, $sheet);
			$data = $allentry->getValues();
			$count_data = 2;
			if(!empty($data) && is_array($data)){
				$data = array_map(
					function ($element) {
					if (isset($element['0'])) {
						return $element['0'];
					}
					else {
						return '';
					}
				},
					$data
				);
				$count_data = (count($data) + 1);
			}else{
				$data = array();
			}
			
			$values = array($wpsslwp_data_value);
			$wpsslwp_rangetoupdate = "'" . trim($wpsslwp_sheet_name) . "'!A" . $count_data;
			$param_arr['values'] = $values;
			$param_arr['inputoption'] = 'USER_ENTERED';
			$param_arr['spreadsheet_id'] = $wpsslwp_spreadsheet_id;
			$param_arr['range'] = $wpsslwp_rangetoupdate;
			$param = self::set_parameter($param_arr);

			$wpsslwp_response = self::$instance_api->updateentry($param);
		}
		/**
		 * Wraps the builder content with the required markup.
		 *
		 * @since 1.0.0
		 */

		public function builder_output()
		{
			if (!current_user_can('edit_wpsyncsheets_wpforms_lite_form_settings')) { ?>
			<div class="wpforms-panel-content-section wpforms-panel-content-section-<?php echo esc_attr($this->slug); ?>"
				id="<?php echo esc_attr($this->slug); ?>-provider">
				<?php $this->builder_output_before(); ?>
				<div class="wpforms-panel-content-section-title">
					<div class="wpss-header-left">
						<div class="wpss-logo-section">
							<img src="<?php echo esc_url(WPSSLWP_URL . 'assets/images/logo.svg?ver='); ?><?php echo esc_attr(WPSSLWP_VERSION); ?>">
						</div>			
					</div>
					<div class="wpss-header-right">
						<ul class="wpss-header-links">
							<li id="wpssBtn">
								<span class="dashicons dashicons-admin-links"></span>
								<a target="_blank" href="<?php echo esc_url(WPSSLWP_BUY_PRO_VERSION_URL); ?>" class='documentation-btn'>
									<?php echo esc_html__('Upgrade To Pro', 'wpsyncsheets-wpforms'); ?>
								</a>
							</li>
						</ul>
					</div>
				</div>
				<div class="wpsslwp-provider-connections-wrap wpsslwp-clear">
					<div class="wpsslwp-provider-connections wpsslwp-element">
						<?php echo esc_html__('You do not have permission to access this page.', 'wpsyncsheets-wpforms'); ?>
					</div>
				</div>
			</div>
			<?php
			}
			else {
				$wpsslwp_google_settings_value = self::$instance_api->wpsslwp_option('wpsswp_google_settings');
				$wpsslwp_error = '';

				if (isset($wpsslwp_google_settings_value[2]) && !empty($wpsslwp_google_settings_value[2])) {
					if (!self::$instance_api->getClient()) {
						$wpsslwp_error = self::$instance_api->getClient(1);
						if ('Invalid token format' === (string)$wpsslwp_error || 'invalid_grant' === (string)$wpsslwp_error) {
							$wpsslwp_error = '<div class="error token_error" style="width: 100%;
    padding: 8px;"><p><strong class="err-msg">' . esc_html__('Error: Invalid Token - Revoke Token with below settings and try again.', 'wpsyncsheets-wpforms') . '</strong></p></div>';

						}
						else {
							$wpsslwp_error = '<div class="error token_error" style="width: 100%;
    padding: 8px;"><p><strong class="err-msg">Error: ' . $wpsslwp_error . '</strong></p></div>';
						}
					}
				}
				else {
					$wpsslwp_error = esc_html__('Please genearate authentication code from ', 'wpsyncsheets-wpforms') . '<strong>' . esc_html__('Google API Settings', 'wpsyncsheets-wpforms') . '</strong> ';
					$wpsslwp_error .= "<a href='" . esc_url('admin.php?page=wpsyncsheets-for-wpforms') . "'>" . esc_html__(' Click', 'wpsyncsheets-wpforms') . '</a>';
				}
				if (!empty($wpsslwp_error)) {
					$allowed_html = wp_kses_allowed_html('post');
					echo '<div class="wpforms-panel-content-section wpforms-panel-content-section-' . esc_attr($this->slug) . '"
					id="' . esc_attr($this->slug) . '-provider">
					' . wp_kses($this->builder_output_before(), $allowed_html) . '
						<div class="wpforms-panel-content-section-title">
							<div class="wpss-header-left">
								<div class="wpss-logo-section">
									<img src="' . esc_url(WPSSLWP_URL . 'assets/images/logo.svg?ver=') . '' . esc_attr(WPSSLWP_VERSION) . '">
								</div>			
							</div>
							<div class="wpss-header-right">
								<ul class="wpss-header-links">
									<li id="wpssBtn">
										<span class="dashicons dashicons-admin-links"></span>
										<a target="_blank" href="' . esc_url(WPSSLWP_BUY_PRO_VERSION_URL) . '" class="documentation-btn">
											' . esc_html__('Upgrade To Pro', 'wpsyncsheets-wpforms') . '
										</a>
									</li>
								</ul>
							</div>
						</div>
						<div class="wpsslwp-provider-connections-wrap wpsslwp-clear">
							<div class="wpsslwp-provider-connections wpsslwp-element">
								' . wp_kses($wpsslwp_error, $allowed_html) . '
							</div>
						</div>
					</div>';
					return;
				}
?>
			<div class="wpforms-panel-content-section wpforms-panel-content-section-<?php echo esc_attr($this->slug); ?>"
				id="<?php echo esc_attr($this->slug); ?>-provider">
				<?php $this->builder_output_before(); ?>
				<div class="wpforms-panel-content-section-title">
					<div class="wpss-header-left">
						<div class="wpss-logo-section">
							<img src="<?php echo esc_url(WPSSLWP_URL . 'assets/images/logo.svg?ver='); ?><?php echo esc_attr(WPSSLWP_VERSION); ?>">
						</div>			
					</div>
					<div class="wpss-header-right">
						<ul class="wpss-header-links">
							<li id="wpssBtn">
								<span class="dashicons dashicons-admin-links"></span>
								<a target="_blank" href="<?php echo esc_url(WPSSLWP_BUY_PRO_VERSION_URL); ?>" class='documentation-btn'>
									<?php echo esc_html__('Upgrade To Pro', 'wpsyncsheets-wpforms'); ?>
								</a>
							</li>
						</ul>
					</div>
				</div>
				<div class="wpforms-provider-connections-wrap wpforms-clear">
					<div class="wpforms-provider-connections wpsswp-element">
						<?php $this->builder_content(); ?>
					</div>
				</div>
			</div>
			<?php
			}
		}

		/**
		 * Display content inside the panel content area.
		 *
		 * @since 1.0.0
		 */
		public function builder_content()
		{

			if (!isset($this->form_data['id'])) {
				echo esc_html__('Plase save the form fields first.', 'wpsyncsheets-wpforms');
				return;
			}

			$wpsslwp_spreadsheet_list = self::list_googlespreedsheet();
			$select = array();
			foreach ($wpsslwp_spreadsheet_list as $spredsheet_key => $spredsheet_val) {
				$select[$spredsheet_key] = $spredsheet_val;
			}
			$exclude_field_type = array('html', 'pagebreak', 'divider', 'credit-card');
			$wpsslwp_sheetheaders = array();
			$wpsslwp_saved_form_fields = $this->form_data;
			$wpsslwp_form_fields = $this->form_data['fields'];
			$is_freeze_header = 0;
			$wpsslwp_savedsheetheaders = array();
			$display_date = 0;
			$display_time = 0;

			$wpsslwp_sheetheaders = self::wpsslwp_prepare_header($wpsslwp_form_fields, $this->form_data['id'], true);

			$wpsslwp_sheetheaders_withid = '';
			$wpsslwp_sheetheaders_withid = wp_json_encode($wpsslwp_sheetheaders);

			$this->form_data['wpsswpf_settings'][$this->slug]['sheet_headers_withid'] = $wpsslwp_sheetheaders_withid;
			$wpsslwp_sheetheaders_array_withid = $wpsslwp_sheetheaders;
			$wpsslwp_savedsheetheaders = array();
			$form_id = $this->form_data['id'];
			$wpsslwp_version = self::$instance_api->wpsslwp_option('wpsswp_form_version', '', $form_id);
			$wpsslwp_active_headers = self::$instance_api->wpsslwp_option('wpsswp_active_headers', '', $form_id);
			$wpsslwp_active_headers = isset($wpsslwp_active_headers[0]) ? $wpsslwp_active_headers[0] : array();

			if (isset($wpsslwp_saved_form_fields['wpsswpf_settings'][$this->slug])) {
				$wpsslwp_settings = $wpsslwp_saved_form_fields['wpsswpf_settings'][$this->slug];

				foreach ($wpsslwp_settings as $skey => $sval) {
					if (substr($skey, 0, 13) === 'sheetheaders-') {
						$wpsslwp_header_key = trim(substr($skey, 13));

						$wpsslwp_headername = '';
						if ($wpsslwp_version) {
							if (true === array_key_exists($wpsslwp_header_key, $wpsslwp_sheetheaders_array_withid)) {
								$wpsslwp_headername = trim($wpsslwp_sheetheaders_array_withid[$wpsslwp_header_key]);
							}
						}
						else {
							$wpsslwp_header_key = strtolower(trim(str_replace('-', ' ', $wpsslwp_header_key)));

							if (in_array($wpsslwp_header_key, array_map('strtolower', $wpsslwp_sheetheaders_array_withid), true)) {

								$wpsslwp_header_key = array_search($wpsslwp_header_key, array_map('strtolower', $wpsslwp_sheetheaders_array_withid), true);
								$wpsslwp_headername = ucfirst(strtolower($wpsslwp_sheetheaders_array_withid[$wpsslwp_header_key]));
							}
						}
						if (!empty($wpsslwp_headername)) {
							$wpsslwp_savedsheetheaders[$wpsslwp_header_key] = $wpsslwp_headername;
						}
					}
					if ('submission_date' === (string)$skey && 1 === (int)$sval) {
						$display_date = 1;
					}
					if ('submission_time' === (string)$skey && 1 === (int)$sval) {
						$display_time = 1;
					}
					if ('freeze_headers' === (string)$skey && 1 === (int)$sval) {
						$is_freeze_header = 1;
					}
				}
			}

			$temp_array = array();
			foreach ($wpsslwp_sheetheaders as $sh_key => $sh) {
				if (!in_array(strtolower($sh), array_map('strtolower', $wpsslwp_savedsheetheaders), true)) {
					$wpsslwp_savedsheetheaders[$sh_key] = $sh;
					$temp_array[$sh_key] = $sh;
				}
			}

			$spreadsheet_id = '';
			if (isset($wpsslwp_saved_form_fields['wpsswpf_settings']['wpsyncsheets-wpforms']['spreadsheet_id'])) {
				$spreadsheet_id = $wpsslwp_saved_form_fields['wpsswpf_settings']['wpsyncsheets-wpforms']['spreadsheet_id'];
			}
			if (!empty($spreadsheet_id) && !array_key_exists($spreadsheet_id, $wpsslwp_spreadsheet_list)) {
				$this->form_data['wpsswpf_settings']['wpsyncsheets-wpforms']['spreadsheet_id'] = '';
				$this->form_data['wpsswpf_settings']['wpsyncsheets-wpforms']['sheetname'] = '';
				$spreadsheet_id = '';
			}
			elseif (!empty($spreadsheet_id)) {
				$response = self::$instance_api->get_sheet_listing($spreadsheet_id);
				$sheet_names = array();
				foreach ($response->getSheets() as $s) {
					$sheet_names[] = $s['properties']['title'];
				}
				if (isset($wpsslwp_saved_form_fields['wpsswpf_settings']['wpsyncsheets-wpforms']['sheetname']) && !empty($wpsslwp_saved_form_fields['wpsswpf_settings']['wpsyncsheets-wpforms']['sheetname']) && !in_array($wpsslwp_saved_form_fields['wpsswpf_settings']['wpsyncsheets-wpforms']['sheetname'], $sheet_names, true)) {
					$this->form_data['wpsswpf_settings']['wpsyncsheets-wpforms']['sheetname'] = '';
				}
			}
			$not_newspreadsheet = '';
			if (empty($wpsslwp_saved_form_fields['wpsswpf_settings']['wpsyncsheets-wpforms']['newspreadsheetname'])) {
				$not_newspreadsheet = 1;
			}
			$sheetname = isset($this->form_data['wpsswpf_settings']['wpsyncsheets-wpforms']['sheetname']) ? $this->form_data['wpsswpf_settings']['wpsyncsheets-wpforms']['sheetname'] : '';
?>
			<div class="generalSetting-section pt-0 enable-generalSetting-section">
					<div class="generalSetting-left">
						<div class="wpforms-panel-field">
							<label>
								<?php echo esc_html__('WPSyncSheets Settings', 'wpsyncsheets-wpforms'); ?>							
							</label>
						</div>
						<p><?php echo esc_html__('Enable this option to automatically create customized spreadsheets and sheets for efficient entry management & seamless functionality.', 'wpsyncsheets-wpforms'); ?></p>
					</div>
					<div class="generalSetting-right">
						<?php wpforms_panel_field(
				'checkbox',
				$this->slug,
				'enable',
				$this->form_data,
				'',
				array(
				'parent' => 'wpsswpf_settings',
				'class' => 'custom-swap custom-text span-checkbox-switch',
			)
			); ?>
					</div>
			</div>

			<div class="generalSetting-section googleSpreadsheet-section entry_spreadsheet_row" style="">
				<div class="generalSetting-left">
					<div class="wpforms-panel-field">
						<label><?php echo esc_html__('Google Spreadsheet Settings', 'wpsyncsheets-wpforms'); ?></label>
					</div>
					<p><?php echo esc_html__('Your chosen Google Spreadsheet automatically generates a sheet with customized headers based on the below-mentioned settings. Whenever a new entry is placed, WPSyncSheets creates a new row to accommodate it with the spreadsheet.', 'wpsyncsheets-wpforms'); ?></p>
					<div class="createanew-radio">
						<div class="createanew-radio-box">
							<input type="radio" name="spreadsheetselection" value="new" id="createanew">
							<label for="createanew">Create New Spreadsheet</label>
						</div>
						<div class="createanew-radio-box">
							<input type="radio" name="spreadsheetselection" value="existing" id="existing" checked="checked">
							<label for="existing">Select Existing Spreadsheet</label>
						</div>
					<?php
			wpforms_panel_field(
				'checkbox',
				$this->slug,
				'is_createanew_spreadsheet',
				$this->form_data,
				'',
				array(
				'parent' => 'wpsswpf_settings',
			)
			);
?>
					</div>		
					<div id="wpsyncsheets-wpforms_spreadsheet_container" class="spreadsheet-form">
						<?php
			wpforms_panel_field(
				'select',
				$this->slug,
				'spreadsheet_id',
				$this->form_data,
				'',
				array(
				'options' => $select,
				'input_class' => 'spreadsheet_id',
				'class' => 'custom-text',
				'parent' => 'wpsswpf_settings',
			)
			);
?>								
					</div>	
					<div valign="top" id="newsheet" class="newsheetinput spreadsheet-form entry_spreadsheet_inputrow">
						<?php
			wpforms_panel_field(
				'text',
				$this->slug,
				'newspreadsheetname',
				$this->form_data,
				'',
				array(
				'parent' => 'wpsswpf_settings',
				'class' => 'custom-text',
				'placeholder' => esc_html__('Enter Spreadsheet name', 'wpsyncsheets-wpforms'),
			)
			);
?>
					</div>	
					<?php
			wpforms_panel_field(
				'text',
				$this->slug,
				'sheetname',
				$this->form_data,
				'',
				array(
				'parent' => 'wpsswpf_settings',
				'class' => 'custom-text',
				'placeholder' => esc_html__('Enter Sheet Name', 'wpsyncsheets-wpforms'),
			)
			);
?>		
				</div>
			</div>

			<div class="generalSetting-section sheetHeaders-section wpss_spreadsheet_row">
				<div class="td-wpss-headers">
					<div class='wpss_headers'>
						<div class="generalSetting-sheet-headers-row">
							<div class="generalSetting-left">
								<h4><?php echo esc_html__('Sheet Headers', 'wpsyncsheets-wpforms'); ?></h4>
								<p><?php echo esc_html__('If you disable any sheet headers, they will be automatically removed from the current spreadsheet. You can always re-enable the headers you need, save the settings, and update the spreadsheet with the latest data. Clear the existing spreadsheet and click the "Click to Sync" button to initiate the sync process.', 'wpsyncsheets-wpforms'); ?></p>
							</div>
						</div>
						<div class="selectall-btnset">
							<button type="button" class="wpss-button wpss-button-primary wpss-selectall" id="selectall"><?php echo esc_html__('Select All', 'wpsyncsheets-wpforms'); ?></button>                
							<button type="button" class="wpss-button wpss-button-secondary wpss-selectnone" id="selectnone"><?php echo esc_html__('Select None', 'wpsyncsheets-wpforms'); ?></button>
						</div>
						<div class="sheetHeaders-main">
							<ul id="sortable" class="ui-sortable sheetHeaders-box sortable-headers-list">
								<?php
			// Add Submission Date and Submission Time in sheet headers
			$wpsslwp_savedsheetheaders['submission_date'] = 'Submission Date';
			$wpsslwp_savedsheetheaders['submission_time'] = 'Submission Time';

			$wpsslwp_savedsheetheaders = array_unique($wpsslwp_savedsheetheaders);
			foreach ($wpsslwp_savedsheetheaders as $header_key => $header) {
				$is_active = 1;

				if (in_array($header, $temp_array, true)) {
					$is_active = 0;
				}
				if (('submission_date' === $header_key) || ('submission_time' === $header_key)) {
					$header_key_new = $header_key;
					if (isset($wpsslwp_settings)) {
						$is_active = isset($wpsslwp_settings[$header_key]) ? (int)$wpsslwp_settings[$header_key] : 0;
					}
				}
				else {
					$header_key_new = 'sheetheaders-' . $header_key;
				}
?>
								<li class="default-order-sheet ui-state-default">
									<?php wpforms_panel_field(
					'checkbox',
					$this->slug,
					$header_key_new,
					$this->form_data,
					$header,
					array(
					'default' => $is_active,
					'parent' => 'wpsswpf_settings',
					'class' => 'custom-swap custom-sort-headers',
					'input_class' => 'headers_chk',
				)
				); ?>
									<label for="wpsswp-<?php echo esc_attr('sheetheaders-' . $header_key); ?>">
										<span class="sheet-left">
											<span class="wootextfield"><?php echo esc_html($header); ?></span>
											<span class="ui-icon ui-icon-pencil wpss-tooltio-link disabled-pro-version">
												<span class="pencil-icon">
													<svg width="12" height="12" viewBox="0 0 13 13" fill="none" xmlns="http://www.w3.org/2000/svg">
													<path d="M1.33333 11.6668H2.26667L8.01667 5.91677L7.08333 4.98343L1.33333 10.7334V11.6668ZM10.8667 4.9501L8.03333 2.1501L8.96667 1.21677C9.22222 0.961213 9.53611 0.833435 9.90833 0.833435C10.2806 0.833435 10.5944 0.961213 10.85 1.21677L11.7833 2.1501C12.0389 2.40566 12.1722 2.71399 12.1833 3.0751C12.1944 3.43621 12.0722 3.74455 11.8167 4.0001L10.8667 4.9501ZM9.9 5.93343L2.83333 13.0001H0V10.1668L7.06667 3.1001L9.9 5.93343Z" fill="#64748B"/>
													</svg>
												</span>
												<span class="check-icon">
													<svg xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 26 26" width="12" height="12">
														<path d="M 22.566406 4.730469 L 20.773438 3.511719 C 20.277344 3.175781 19.597656 3.304688 19.265625 3.796875 L 10.476563 16.757813 L 6.4375 12.71875 C 6.015625 12.296875 5.328125 12.296875 4.90625 12.71875 L 3.371094 14.253906 C 2.949219 14.675781 2.949219 15.363281 3.371094 15.789063 L 9.582031 22 C 9.929688 22.347656 10.476563 22.613281 10.96875 22.613281 C 11.460938 22.613281 11.957031 22.304688 12.277344 21.839844 L 22.855469 6.234375 C 23.191406 5.742188 23.0625 5.066406 22.566406 4.730469 Z" fill="#64748B"/></svg>
												</span>
												<span class="tooltip-text edit-tooltip">Upgrade To Pro</span>
												<span class="tooltip-text update-tooltip">Update</span>
											</span>
										</span>
										<span class="sheet-right">
											<span class="checkbox-switch-new"></span>
											<span class="ui-icon ui-icon-caret-2-n-s wpss-tooltio-link disabled-pro-version">
												<svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">
												<mask id="mask0_384_3228" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="17" height="16">
												<rect x="0.5" width="16" height="16" fill="#D9D9D9"/>
												</mask>
												<g mask="url(#mask0_384_3228)">
												<path d="M5.95875 13.67C5.55759 13.67 5.21418 13.5272 4.92851 13.2415C4.64284 12.9558 4.5 12.6124 4.5 12.2113C4.5 11.8101 4.64284 11.4667 4.92851 11.181C5.21418 10.8953 5.55759 10.7525 5.95875 10.7525C6.35991 10.7525 6.70332 10.8953 6.98899 11.181C7.27466 11.4667 7.4175 11.8101 7.4175 12.2113C7.4175 12.6124 7.27466 12.9558 6.98899 13.2415C6.70332 13.5272 6.35991 13.67 5.95875 13.67ZM10.335 13.67C9.93384 13.67 9.59043 13.5272 9.30476 13.2415C9.01909 12.9558 8.87625 12.6124 8.87625 12.2113C8.87625 11.8101 9.01909 11.4667 9.30476 11.181C9.59043 10.8953 9.93384 10.7525 10.335 10.7525C10.7362 10.7525 11.0796 10.8953 11.3652 11.181C11.6509 11.4667 11.7937 11.8101 11.7937 12.2113C11.7937 12.6124 11.6509 12.9558 11.3652 13.2415C11.0796 13.5272 10.7362 13.67 10.335 13.67ZM5.95875 9.29375C5.55759 9.29375 5.21418 9.15091 4.92851 8.86524C4.64284 8.57957 4.5 8.23616 4.5 7.835C4.5 7.43384 4.64284 7.09043 4.92851 6.80476C5.21418 6.51909 5.55759 6.37625 5.95875 6.37625C6.35991 6.37625 6.70332 6.51909 6.98899 6.80476C7.27466 7.09043 7.4175 7.43384 7.4175 7.835C7.4175 8.23616 7.27466 8.57957 6.98899 8.86524C6.70332 9.15091 6.35991 9.29375 5.95875 9.29375ZM10.335 9.29375C9.93384 9.29375 9.59043 9.15091 9.30476 8.86524C9.01909 8.57957 8.87625 8.23616 8.87625 7.835C8.87625 7.43384 9.01909 7.09043 9.30476 6.80476C9.59043 6.51909 9.93384 6.37625 10.335 6.37625C10.7362 6.37625 11.0796 6.51909 11.3652 6.80476C11.6509 7.09043 11.7937 7.43384 11.7937 7.835C11.7937 8.23616 11.6509 8.57957 11.3652 8.86524C11.0796 9.15091 10.7362 9.29375 10.335 9.29375ZM5.95875 4.9175C5.55759 4.9175 5.21418 4.77466 4.92851 4.48899C4.64284 4.20332 4.5 3.85991 4.5 3.45875C4.5 3.05759 4.64284 2.71418 4.92851 2.42851C5.21418 2.14284 5.55759 2 5.95875 2C6.35991 2 6.70332 2.14284 6.98899 2.42851C7.27466 2.71418 7.4175 3.05759 7.4175 3.45875C7.4175 3.85991 7.27466 4.20332 6.98899 4.48899C6.70332 4.77466 6.35991 4.9175 5.95875 4.9175ZM10.335 4.9175C9.93384 4.9175 9.59043 4.77466 9.30476 4.48899C9.01909 4.20332 8.87625 3.85991 8.87625 3.45875C8.87625 3.05759 9.01909 2.71418 9.30476 2.42851C9.59043 2.14284 9.93384 2 10.335 2C10.7362 2 11.0796 2.14284 11.3652 2.42851C11.6509 2.71418 11.7937 3.05759 11.7937 3.45875C11.7937 3.85991 11.6509 4.20332 11.3652 4.48899C11.0796 4.77466 10.7362 4.9175 10.335 4.9175Z" fill="#64748B"/>
												</g>
												</svg>
												<span class="tooltip-text">Upgrade To Pro</span>
											</span>
										</span>
									</label>
								</li>
								<?php
			}?>
							</ul>
						</div>
					</div>
				</div>
				<?php
			wp_nonce_field('save_general_settings', 'wpsslwp_general_settings');
			wpforms_panel_field(
				'text',
				$this->slug,
				'sheet_headers_withid',
				$this->form_data,
				esc_html__('Sheet Headers Id', 'wpsyncsheets-wpforms'),
				array(
				'parent' => 'wpsswpf_settings',
				'class' => 'wpf-disable-field',
				'readonly' => true,
			)
			);
			?>
			</div>


			<div class="generalSetting-section">
				<div class="generalSetting-left">
					<div class="wpforms-panel-field">
						<label><?php echo esc_html__('Freeze Header', 'wpsyncsheets-wpforms'); ?></label>
					</div>
					<p><?php echo esc_html__('By enabling this feature, the first row containing the header (or title) information will remain fixed at the top of the sheet even while scrolling down, providing easy access to essential details.', 'wpsyncsheets-wpforms'); ?></p>
				</div>
				<div class="generalSetting-right">
					<?php
			wpforms_panel_field(
				'checkbox',
				$this->slug,
				'freeze_headers',
				$this->form_data,
				'',
				array(
				'default' => $is_freeze_header,
				'parent' => 'wpsswpf_settings',
				'class' => 'custom-swap span-checkbox-switch',
			)
			);
?>
				</div>
			</div>

			<div class="generalSetting-section">
				<div class="generalSetting-left">
					<div class="wpforms-panel-field">
						<label><?php echo esc_html__('Row Input Format Option', 'wpsyncsheets-wpforms'); ?><span class="wpss-tooltio-link tooltip-right">
								<span class="tooltip-text"><a target="_blank" href="<?php echo esc_url(WPSSLWP_BUY_PRO_VERSION_URL); ?>" class="upgrade-class-link">Upgrade To Pro</a></span>
							</span></label>
					</div>
					<p><?php echo esc_html__('This option allows you to specify how the input data should be interpreted. For further information, refer to the provided Link for more details, ', 'wpsyncsheets-wpforms'); ?><a href="https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption" target="_blank">click here.</a></p>
				</div>
			</div>
			<?php if (WPSSLWP_Dependencies::wpsslwp_is_wpforms_plugin_active(true)) { ?>
				<div class="generalSetting-section synctr entry_spreadsheet_row" style="">
					<div class="generalSetting-left">
						<div class="wpforms-panel-field">
							<label>
								<span class="wpss-tooltio-link tooltip-right">
									Sync Entries<span class="tooltip-text"><a target="_blank" href="<?php echo esc_url(WPSSLWP_BUY_PRO_VERSION_URL); ?>" class="upgrade-class-link">Upgrade To Pro</a></span>
								</span>
							</label>
						</div>
						<p><?php echo esc_html__("By clicking the 'Click to Sync' button, all entries that are not already present in the sheet will be appended. The existing entries in the sheet will not be updated, providing a seamless synchronization process.", 'wpsyncsheets-wpforms'); ?></p>
						<div class="sync-button-box">              
							<a class="wpss-button wpss-button-secondary disabled-pro-version" href="#" id="wpsswp_sync_entries" data-form-id="" >
								<?php echo esc_html__('Click to Sync', 'wpsyncsheets-wpforms'); ?>
							</a>
						</div>
					</div>
				</div>
			<?php
			}?>
	<?php
		}
		/**
		 * Reset Google API Settings
		 */
		public static function wpsslwp_reset_settings()
		{

			if (!current_user_can('edit_wpsyncsheets_wpforms_lite_main_settings')) {
				echo esc_html__('You do not have permission to access this page.', 'wpsyncsheets-wpforms');
				die();
			}

			if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'save_api_settings')) {
				echo esc_html__('Sorry, your nonce did not verifyy.', 'wpsyncsheets-wpforms');
				wp_die();
			}

			try {
				$wpsslwp_google_settings = self::$instance_api->wpsslwp_option('wpsswp_google_settings');
				$settings = array();
				foreach ($wpsslwp_google_settings as $key => $value) {
					$settings[$key] = '';
				}
				self::$instance_api->wpsslwp_update_option('wpsswp_google_settings', $settings);
				self::$instance_api->wpsslwp_update_option('wpsswp_google_accessToken', '');
			}
			catch (Exception $e) {
				echo esc_html('Message: ' . $e->getMessage());
			}
			echo esc_html('successful');
			wp_die();
		}
		/**
		 * Prepare Google Spreadsheet list
		 *
		 * @access public
		 * @return array $wpsslwp_sheetarray
		 */
		public static function list_googlespreedsheet()
		{
			$sheetarray = array(
				'' => __('Select Google Spreeadsheet List', 'wpsyncsheets-wpforms'),
			);
			$sheetarray = self::$instance_api->get_spreadsheet_listing($sheetarray);
			return $sheetarray;
		}
		/**
		 * Create Sheet Headers array
		 *
		 * @access public
		 * @param array  $form_data form setting array.
		 * @param string $changeto In which case string need to change.
		 * @param bool   $with_key in which format header array need to return.
		 * @return array $wpsslwp_sheetheaders
		 */
		public static function sheetheaders_value($form_data = array(), $changeto = 'ucfirst', $with_key = false)
		{

			if (!$form_data) {
				return array();
			}
			$wpsslwp_headername = '';
			$wpsslwp_sheetheaders = array();
			$wpsslwp_settings = isset($form_data['wpsswpf_settings']['wpsyncsheets-wpforms']) ? $form_data['wpsswpf_settings']['wpsyncsheets-wpforms'] : array();
			$form_id = isset($form_data['id']) ? $form_data['id'] : '';
			$wpsslwp_version = self::$instance_api->wpsslwp_option('wpsswp_form_version', '', $form_id);
			$wpsslwp_active_headers = self::$instance_api->wpsslwp_option('wpsswp_active_headers', '', $form_id);
			$wpsslwp_active_headers = isset($wpsslwp_active_headers[0]) ? $wpsslwp_active_headers[0] : array();
			foreach ($wpsslwp_settings as $key => $val) {
				if (substr($key, 0, 13) === 'sheetheaders-') {
					$wpsslwp_header_key = substr($key, 13);
					$wpsslwp_headername = '';

					if ($wpsslwp_version) {
						if (true === array_key_exists($wpsslwp_header_key, $wpsslwp_active_headers)) {
							$wpsslwp_headername = $changeto(trim($wpsslwp_active_headers[$wpsslwp_header_key]));
						}
					}
					else {
						$wpsslwp_headername = $changeto(trim(str_replace('-', ' ', $wpsslwp_header_key)));
					}
					if ($with_key) {
						$wpsslwp_sheetheaders[$wpsslwp_header_key] = $wpsslwp_headername;
					}
					else {
						$wpsslwp_sheetheaders[] = $wpsslwp_headername;
					}
				}
			}

			return $wpsslwp_sheetheaders;
		}
		/**
		 * Set parameters for batchupdate request
		 *
		 * @access public
		 * @param array $param_arr array of parameters.
		 * @return array $param
		 */
		public static function set_parameter($param_arr = array())
		{
			$wpsslwp_requestbody = self::$instance_api->valuerangeobject($param_arr['values']);
			$wpsslwp_inputoption = $param_arr['inputoption'];
			if (!$wpsslwp_inputoption) {
				$wpsslwp_inputoption = 'USER_ENTERED';
			}
			$wpsslwp_params = array('valueInputOption' => $wpsslwp_inputoption);
			$param = self::$instance_api->setparamater($param_arr['spreadsheet_id'], $param_arr['range'], $wpsslwp_requestbody, $wpsslwp_params);
			return $param;
		}
		/**
		 * Function to clear spreadsheet.
		 *
		 * @since 1.0
		 */
		public static function wpsslwp_clear_sheet()
		{

			if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'save_general_settings')) {
				echo esc_html__('Sorry, your nonce did not verify.', 'wpsyncsheets-wpforms');
				wp_die();
			}
			$form_id = isset($_POST['form_id']) ? sanitize_text_field(wp_unslash($_POST['form_id'])) : '';

			if (empty($form_id)) {
				echo 'save_setting';
				wp_die();
			}
			$form_data = self::$instance_api->wpsslwp_option('wpsswp_form_settings', '', $form_id);
			if (empty($form_data) || !isset($form_data[0]['spreadsheet_id']) || !isset($form_data[0]['sheetname'])) {
				echo 'save_setting';
				wp_die();
			}
			$wpsslwp_active_headers = self::$instance_api->wpsslwp_option('wpsswp_active_headers', '', $form_id);

			$wpsslwp_spreadsheetid = $form_data[0]['spreadsheet_id'];
			$sheetname = $form_data[0]['sheetname'];
			$sheet = "'" . $sheetname . "'";

			$response = self::$instance_api->get_row_list($wpsslwp_spreadsheetid, $sheet);
			if (!is_null($response->getValues())) {
				$total_headers = count($response['values'][0]);
				$last_column = self::wpsslwp_get_column_index($total_headers);

				try {
					$range = "'" . $sheetname . "'!A2:" . $last_column . '100000';
					$requestbody = self::$instance_api->clearobject();
					$param = array();
					$param['spreadsheetid'] = $wpsslwp_spreadsheetid;
					$param['sheetname'] = $range;
					$param['requestbody'] = $requestbody;
					$response = self::$instance_api->clear($param);
				}
				catch (Exception $e) {
					wpforms_log('WPSyncSheets For WPForms Error', $e->getMessage(), array('type' => 'error'));
				}
			}
			echo 'successful';
			wp_die();
		}
		/**
		 * Get column index
		 *
		 * @since 1.0
		 * @param int $number .
		 * @return string $letter
		 */
		public static function wpsslwp_get_column_index($number)
		{
			if ($number <= 0) {
				return null;
			}
			$temp;
			$letter = '';
			while ($number > 0) {
				$temp = ($number - 1) % 26;
				$letter = chr($temp + 65) . $letter;
				$number = ($number - $temp - 1) / 26;
			}
			return $letter;
		}
		/**
		 * Check header exists or not
		 *
		 * @access public
		 * @param string $header header name.
		 * @param array  $headers_list headers array.
		 * @return string $header
		 */
		public static function wpsslwp_check_header($header, $headers_list)
		{
			if (!$header || !$headers_list) {
				return;
			}
			$formatted_header = '';
			if (in_array($header, $headers_list, true)) {
				$formatted_header = $header;
				$count = 1;
				while (in_array($formatted_header, $headers_list, true)) {
					$formatted_header = $header . '(' . $count . ')';
					$count++;
				}
				return $formatted_header;
			}
			else {
				return $header;
			}
		}
		/**
		 * Prepare headers array
		 *
		 * @access public
		 * @param array $wpsslwp_form_fields form fields.
		 * @param int   $form_id form id array.
		 * @param bool  $with_key return key value pair of sheet headers if true by default false.
		 * @return array $wpsslwp_sheetheaders
		 */
		public static function wpsslwp_prepare_header($wpsslwp_form_fields, $form_id, $with_key = false)
		{
			$wpsslwp_sheetheaders = array();

			$exclude_field_type = array('html', 'pagebreak', 'divider', 'credit-card');
			if (!$form_id) {
				// phpcs:ignore
				$form_id = isset($_GET['form_id']) ? sanitize_text_field($_GET['form_id']) : '';
			}
			if (!$form_id || !$wpsslwp_form_fields) {
				return;
			}
			$wpsslwp_version = self::$instance_api->wpsslwp_option('wpsswp_form_version', '', $form_id);
			$form_data = self::$instance_api->wpsslwp_option('wpsswp_form_settings', '', $form_id);
			$wpsslwp_active_headers = self::$instance_api->wpsslwp_option('wpsswp_active_headers', '', $form_id);

			$wpsslwp_active_headers = isset($wpsslwp_active_headers[0]) ? $wpsslwp_active_headers[0] : array();
			$headers_list = isset($form_data[0]['sheet_headers_withid']) ? json_decode($form_data[0]['sheet_headers_withid'], true) : array();
			$field_ids = array();
			foreach ($wpsslwp_form_fields as $field) {
				$field_ids[] = (int)$field['id'];
			}

			$header_field_ids = is_array($headers_list) ? array_keys($headers_list) : array();

			foreach ($headers_list as $fieldid => $fieldval) {
				if (!in_array((int)$fieldid, $field_ids, true)) {
					if (!empty($wpsslwp_version) && false === array_key_exists($fieldid, $wpsslwp_active_headers)) {
						unset($headers_list[$fieldid]);
					}
					elseif (empty($wpsslwp_version) && !in_array($fieldval, $wpsslwp_active_headers, true)) {
						unset($headers_list[$fieldid]);
					}
				}
				if (!empty($wpsslwp_version) && !in_array((int)$fieldid, $field_ids, true) && false !== array_key_exists($fieldid, $wpsslwp_active_headers)) {
					$wpsslwp_form_fields[$fieldid] = array(
						'id' => $fieldid,
						'label' => $wpsslwp_active_headers[$fieldid],
						'type' => 'text',
					);
				}
			}

			foreach ($wpsslwp_form_fields as $field) {
				$field_id = $field['id'];
				if (isset($field['type']) && !in_array($field['type'], $exclude_field_type, true)) {
					if (!empty($wpsslwp_version) && true === array_key_exists($field_id, $wpsslwp_active_headers)) {
						$wpsslwp_sheetheaders[$field_id] = $wpsslwp_active_headers[$field_id];
					}
					else {
						if (isset($field['label']) && !empty($field['label'])) {
							$wpsslwp_sheetheaders[$field_id] = trim($field['label']);
						}
						elseif (isset($field['placeholder']) && !empty($field['placeholder'])) {
							$wpsslwp_sheetheaders[$field_id] = trim($field['placeholder']);
						}
						else {
							$field_type = ucfirst(trim($field['type']));
							if (!empty($headers_list)) {
								if (true === array_key_exists($field_id, $headers_list)) {
									$wpsslwp_sheetheaders[$field_id] = $headers_list[$field_id];
								}
								else {
									$header = '';
									$header = self::wpsslwp_check_header($field_type, $headers_list);
									$wpsslwp_sheetheaders[$field_id] = $header;
									$headers_list[$field_id] = $header;
								}
							}
							else {
								$wpsslwp_sheetheaders[$field_id] = self::wpsslwp_check_header($field_type, $wpsslwp_sheetheaders);
							}
						}
					}
				}
			}
			if ($with_key) {
				return $wpsslwp_sheetheaders;
			}
			return array_values($wpsslwp_sheetheaders);
		}
		/**
		 * Prepare header value array
		 *
		 * @access public
		 * @param array $fields form fields.
		 * @param array $form_data form settings array.
		 * @return array $wpsslwp_data_value
		 */
		public static function wpsslwp_prepare_header_values($fields, $form_data)
		{
			$wpsslwp_sheetheaders = array();
			$wpsslwp_settings = isset($form_data['wpsswpf_settings']['wpsyncsheets-wpforms']) ? $form_data['wpsswpf_settings']['wpsyncsheets-wpforms'] : array();
			$wpsslwp_sheetheaders = self::sheetheaders_value($form_data, 'strtolower', true);
			$wpsslwp_sheetheaders_withid = isset($wpsslwp_settings['sheet_headers_withid']) ? (array)json_decode($wpsslwp_settings['sheet_headers_withid'], true) : array();
			if (empty($wpsslwp_sheetheaders_withid)) {
				$wpsslwp_sheetheaders_withid = self::wpsslwp_prepare_header($fields, $form_data['id'], true);
			}

			$wpsslwp_data_value = array();
			$wpsslwp_version = self::$instance_api->wpsslwp_option('wpsswp_form_version', '', $form_data['id']);
			foreach ($wpsslwp_sheetheaders as $wpsslwp_headerkey => $wpsslwp_headername) {
				$exist = 0;
				foreach ($fields as $skey => $sval) {

					if ($wpsslwp_version) {
						$field_id = isset($sval['id']) ? $sval['id'] : false;

						if (false !== $field_id && $wpsslwp_headerkey === $field_id) {
							$wpsslwp_data_value[] = html_entity_decode($sval['value']);
							$exist = 1;
						}
					}
					else {
						if (!empty($sval['name'])) {
							if (trim(strtolower(str_replace('-', ' ', $sval['name']))) === trim($wpsslwp_headername)) {
								$wpsslwp_data_value[] = html_entity_decode($sval['value']);
								$exist = 1;
							}
						}
						else {
							$field_id = isset($sval['id']) ? $sval['id'] : '';
							if (isset($form_data['fields'][$field_id])) {
								$field = $form_data['fields'][$field_id];
								$field_name = '';
								if (isset($wpsslwp_sheetheaders_withid[$field_id])) {
									$field_name = trim($wpsslwp_sheetheaders_withid[$field_id]);
								}
								if (!empty($field_name) && trim(strtolower(str_replace('-', ' ', $field_name))) === trim($wpsslwp_headername)) {
									$wpsslwp_data_value[] = html_entity_decode($sval['value']);
									$exist = 1;
								}
							}
						}
					}
				}
				if (!$exist) {
					$wpsslwp_data_value[] = '';
				}
			}
			return $wpsslwp_data_value;
		}

		/**
		 * Add provider to the Settings Integrations tab.
		 *
		 *
		 * @param array $active   Array of active connections.
		 * @param array $settings Array of all connections settings.
		 */
		public function integrations_tab_options($active, $settings)
		{

			$wpss_google_settings_value = self::$instance_api->wpsslwp_option('wpsswp_google_settings');

			if (!empty($wpss_google_settings_value[2]) && !self::$instance_api->checkcredenatials()) {
				$wpss_error = true;
			}
			if (false === $wpss_error && !empty($wpss_google_settings_value[2])) {
				$connected_api = true;
			}
			$connected = !empty($active[$this->slug]);
			if ($connected_api && $connected) {
				$settings[$this->slug] = 1;
			}

			$accounts = !empty($settings[$this->slug]) ? $settings[$this->slug] : [];
			$class = $connected && $accounts ? 'connected' : '';
			$arrow = 'right';

			$connected_api = false;

			// This lets us highlight a specific service by a special link.
			if (!empty($_GET['wpforms-integration'])) { //phpcs:ignore
				if ($this->slug === $_GET['wpforms-integration']) { //phpcs:ignore
					$class .= ' focus-in';
					$arrow = 'down';
				}
				else {
					$class .= ' focus-out';
				}
			}

?>
		<div id="wpforms-integration-<?php echo esc_attr($this->slug); ?>" class="wpforms-settings-provider wpforms-clear <?php echo esc_attr($this->slug); ?> <?php echo esc_attr($class); ?>">

			<div class="wpforms-settings-provider-header wpforms-clear" data-provider="<?php echo esc_attr($this->slug); ?>">

				<div class="wpforms-settings-provider-logo">
					<i class="fa fa-chevron-<?php echo esc_attr($arrow); ?>"></i>
					<img src="<?php echo esc_url($this->icon); ?>">
				</div>

				<div class="wpforms-settings-provider-info">
					<h3><?php echo esc_html($this->name); ?></h3>
					<p>
						<?php
			printf( /* translators: %s - provider name. */
				esc_html__('Integrate %s with WPForms', 'wpsyncsheets-wpforms'),
				esc_html($this->name)
			);
?>
					</p>
					<br>
					<br>
										
					<span class="connected-indicator green"><i class="fa fa-check-circle-o"></i>&nbsp;<?php esc_html_e('Connected', 'wpsyncsheets-wpforms'); ?></span>
				</div>
			</div>
			<div class="wpforms-settings-provider-accounts" id="provider-<?php echo esc_attr($this->slug); ?>">
				<a class="wpss-button-primary" href="<?php echo esc_html(admin_url('admin.php?page=wpsyncsheets-for-wpforms&tab=wpsslwp-nav-googleapi')); ?>">Google API Settings</a>
			</div>
		</div>
		<?php
		}
	}
	new WPSSLWP_Service();
}