<?php
/**
 * Gravity Form Feed Settings file.
 *
 * @file class-wpsslgf-feed-settings.php
 * @package   wpsyncsheets-gravity-forms
 * @since 1.0.0
 */

GFForms::include_payment_addon_framework();

if (!defined('ABSPATH')) {
	exit;
}


/**
 * GFFeedAddOn extended Class.
 *
 * @since 1.0.0
 */
class WPSSLGF_Feed_Settings extends GFFeedAddOn
{

	/**
	 * WPSSLGF Version.
	 *
	 * @var $version
	 */
	protected $version = WPSSLGF_VERSION;
	/**
	 * Minimum Gravity Version.
	 *
	 * @var $min_gravityforms_version
	 */
	// phpcs:ignore
	protected $_min_gravityforms_version = '1.9';
	/**
	 * Slug.
	 *
	 * @var $slug
	 */
	// phpcs:ignore
	protected $_slug = 'ggspreadsheetaddon';
	/**
	 * Path.
	 *
	 * @var $path
	 */
	// phpcs:ignore
	protected $_path = 'wpsyncsheets-gravity-forms/wpsyncsheets-lite-gravity-forms.php';
	/**
	 * Path.
	 *
	 * @var $_full_path
	 */
	// phpcs:ignore
	protected $_full_path = __FILE__;
	/**
	 * Plugin Name.
	 *
	 * @var $_title
	 */
	// phpcs:ignore
	protected $_title = 'WPSyncSheets Lite For Gravity Forms';
	/**
	 * Plugin Short Title.
	 *
	 * @var $_short_title
	 */
	// phpcs:ignore
	protected $_short_title = 'WPSyncSheets Lite';
	/**
	 * Sheet setting Doc.
	 *
	 * @var $doc_sheet_setting
	 */
	protected $doc_sheet_setting = 'https://docs.wpsyncsheets.com/wpssg-google-sheets-api-settings/';
	/**
	 * Ticket generate URL.
	 *
	 * @var $submit_ticket
	 */
	protected $submit_ticket = 'https://wordpress.org/support/plugin/wpsyncsheets-gravity-forms/';
	/**
	 * Instance of WPSSLGF_Feed_Settings
	 *
	 * @var $instance
	 */
	private static $instance = null;
	/**
	 * Instance of WPSSLGF_Google_API_Functions
	 *
	 * @var $instance_api
	 */
	private static $instance_api = null;
	/**
	 * Create WPSSLGF_Feed_Settings Instance.
	 */
	public static function get_instance()
	{
		if (null === self::$instance) {
			self::$instance = new WPSSLGF_Feed_Settings();
		}
		return self::$instance;
	}

	/**
	 * Create WPSSLGF_Google_API_Functions Instance.
	 */
	public static function get_clientinstance()
	{
		if (null === self::$instance_api) {
			self::$instance_api = new WPSyncSheetsGravityForms\WPSSLGF_Google_API_Functions();
		}
		return self::$instance_api;
	}


	/**
	 * Plugin starting point. Handles hooks, loading of language files and PayPal delayed payment support.
	 */
	public function init()
	{
		parent::init();
		add_action('gform_after_submission', array($this, 'wpsslgf_after_submission'), 10, 2);
		add_action('wp_ajax_wpsslgf_reset_settings', array($this, 'wpsslgf_reset_settings'));
		add_action('wp_ajax_wpsslgf_clear_spreadsheet', array($this, 'wpsslgf_clear_spreadsheet'));
		add_action('wp_ajax_wpssg_list_googlespreadsheet_ajax', array($this, 'wpsslgf_list_googlespreadsheet_ajax'), 10);

		add_action('wp_ajax_wpssg_list_googlesheet_ajax', array($this, 'wpsslgf_list_googlesheet_ajax'), 10, 1);
		add_action('wp_ajax_wpssg_check_headers_exists', array($this, 'wpssg_check_headers_exists'), 10, 2);
		$this->get_clientinstance();
	}

	// # FEED PROCESSING -----------------------------------------------------------------------------------------------
	/**
	 * Process the feed
	 *
	 * @param array $feed The feed object to be processed.
	 * @param array $entry The entry object currently being processed.
	 * @param array $form The form object currently being processed.
	 *
	 * @return bool|void
	 */
	public function process_feed($feed, $entry, $form)
	{
		// Retrieve the name => value pairs for all fields mapped in the 'mappedFields' field map.
		$field_map = self::$instance->get_field_map_fields($feed, 'mappedFields');

		// Loop through the fields from the field map setting building an array of values to be passed to the third-party service.
		$merge_vars = array();
		foreach ($field_map as $name => $field_id) {
			// Get the field value for the specified field id.
			$merge_vars[$name] = self::$instance->get_field_value($form, $entry, $field_id);
		}
	}

	/**
	 * Enqueue admin scripts.
	 *
	 * @since  1.0
	 * @access public
	 *
	 * @return array
	 */
	public function scripts()
	{

		$scripts = array(
				array(
				'handle' => 'gform_googlespreadsheet_pluginsettings',
				'deps' => array('jquery'),
				'src' => WPSSLGF_URL . 'assets/js/wpsslgf-plugin-settings.js?d',
				'version' => self::$instance->version,
				'enqueue' => array(
						array(
						'admin_page' => array('plugin_settings', 'form_settings'),
					),
				),
			),
		);
		return array_merge(parent::scripts(), $scripts);
	}

	/**
	 * Return the stylesheets which should be enqueued.
	 *
	 * @return array
	 */
	public function styles()
	{

		$styles = array(
				array(
				'handle' => 'gform_googlespreadsheet_form_settings_css',
				'src' => WPSSLGF_URL . 'assets/css/wpsslgf-form-settings.css?ds',
				'version' => self::$instance->version,
				'enqueue' => array(
						array('admin_page' => array('form_settings')),
				),
			),
				array(
				'handle' => 'wpsslgf-wp-admin-plugin-setting',
				'src' => WPSSLGF_URL . 'assets/css/wpsslgf-admin-plugin-setting-style.css',
				'version' => self::$instance->version,
				'enqueue' => array(
						array('admin_page' => array('form_settings')),
				),
			),
		);
		return array_merge(parent::styles(), $styles);
	}

	/**
	 * Output the page header.
	 */
	public function plugin_page_header()
	{
?>
<div class="wpssw_order_top_header"> <!-- ONLY this will be hidden -->
	<div class="wpssw_top_header_content_wrapper">
		<p class="wpssw_top_header_text">
			You're using our free version. To unlock more features,
			<a href="<?php echo esc_url(WPSSLGF_BUY_PRO_VERSION_URL); ?>" target="_blank">upgrade to pro →</a>
		</p>
	</div>
	<button class="wpssw_close_btn" onclick="wc_closeTopHeader()">×</button>
</div>
		<?php
		parent::plugin_page_header();
	}

	/**
	 * Configures the settings which should be rendered on the feed edit page in the Form Settings > Feed Add-On area.
	 *
	 * @return array
	 */
	public function feed_settings_fields()
	{
		if (!self::$instance_api->checkcredenatials()) {
			$wpsslgf_error = self::$instance_api->getClient(1);
			if ('Invalid token format' === (string)$wpsslgf_error) {
				$wpsslgf_error = '<strong class="err-msg">' . esc_html__('Error: Invalid Token - ', 'wpsyncsheets-gravity-forms') . '<a href="' . esc_url(admin_url('admin.php?page=wpsyncsheets-for-gravity-forms')) . '">' . esc_html__('Click here', 'wpsyncsheets-gravity-forms') . ' </a> ' . esc_html__('to check more information.', 'wpsyncsheets-gravity-forms');
			}
			return array();
		}
		$feeddata = array();
		$check_spreadsheet_header_value = false;
		if (isset($_GET['fid']) && 0 !== (int)sanitize_text_field(wp_unslash($_GET['fid']))) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$feed_id = sanitize_text_field(wp_unslash($_GET['fid'])); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$form_id = isset($_GET['id']) ? sanitize_text_field(wp_unslash($_GET['id'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$feeddata = GFAPI::get_feed($feed_id, $form_id);
			if (isset($feeddata['meta']['spreedsheets']) && isset($feeddata['meta']['sheetselect'])) {
				$sheet_data = self::$instance->wpsslgf_check_sheet_exist($feeddata['meta']['spreedsheets'], $feeddata['meta']['sheetselect']);
				if ('' === (string)$sheet_data['spreadsheetid'] || '' === (string)$sheet_data['sheetname']) {
					$feeddata['meta']['spreedsheets'] = $sheet_data['spreadsheetid'];
					$feeddata['meta']['sheetselect'] = $sheet_data['sheetname'];
				//$result = self::$instance->update_feed_meta( $feed_id, $feeddata['meta'] );

				}
				if ('' !== $sheet_data['spreadsheetid'] && '' !== $sheet_data['sheetname']) {
					$spreadsheetid = $sheet_data['spreadsheetid'];
					$sheetname = $sheet_data['sheetname'] . '!A1:ZZ1';
					$response = self::$instance_api->get_row_list($spreadsheetid, $sheetname);

					if (empty($response->getValues())) {
						$check_spreadsheet_header_value = false;
					}
					else {
						$check_spreadsheet_header_value = true;
					}
				}
			}
		}
?>
		<?php

		$header_html = '<div class="wpssw_order_top_header">
			<div class="wpssw_top_header_content_wrapper">
				<p class="wpssw_top_header_text">
					' . esc_html__("You're using our free version. To unlock more features,", 'wpsyncsheets-gravity-forms') . '
					<a href="' . esc_url(WPSSLGF_BUY_PRO_VERSION_URL) . '" target="_blank">' . esc_html__('upgrade to pro →', 'wpsyncsheets-gravity-forms') . '</a>
				</p>
			</div>
			<button class="wpssw_close_btn" onclick="wc_closeTopHeader()">×</button>
		</div>';

		/*Feed Title Section*/
		$feed_title_section = array(
			'title' => '',
			'fields' => array(
					array(
					'name' => 'upgrade_header_html',
					'type' => 'html',
					'html' => $header_html,
				),
					array(
					'name' => 'feedName',
					'label' => esc_html__('Feed Name', 'wpsyncsheets-gravity-forms'),
					'type' => 'text',
					'required' => true,
					'class' => 'medium',
					'default_value' => self::$instance->get_default_feed_name(),
					'tooltip' => '<h6>' . esc_html__('Name', 'wpsyncsheets-gravity-forms') . '</h6>' . esc_html__('Enter a feed name to uniquely identify this setup.', 'wpsyncsheets-gravity-forms'),
				),
			),
		);
		$svg_icon = '<svg width="25" height="25" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
		<path d="M7.5 2C7.5 5.03757 5.03757 7.5 2 7.5C5.03757 7.5 7.5 9.96243 7.5 13C7.5 9.96243 9.96243 7.5 13 7.5C9.96243 7.5 7.5 5.03757 7.5 2Z" fill="#4169E1"></path>
		<path d="M14 11C14 14.866 10.866 18 7 18C10.866 18 14 21.134 14 25C14 21.134 17.134 18 21 18C17.134 18 14 14.866 14 11Z" fill="#4169E1"></path>
		<path d="M20 3C20 4.65685 18.6569 6 17 6C18.6569 6 20 7.34315 20 9C20 7.34315 21.3431 6 23 6C21.3431 6 20 4.65685 20 3Z" fill="#4169E1"></path>
		</svg>';

		/* Build base fields array. */
		$base_fields = array(
			'title' => 'Google Spreadsheet Settings',
			'fields' => array(
					array(
					'label' => 'Google Spreadsheet',
					'type' => 'radio',
					'horizontal' => true,
					'name' => 'spreadsheet_option',
					'tooltip' => 'Create or Select Google Spreadsheet',
					'choices' => array(
							array(
							'label' => 'Create New Spreadsheet',
							'value' => 'new',
							'default' => true,
						),
							array(
							'label' => 'Select Existing Spreadsheet',
							'value' => 'existing',
						),
					),
				),
					array(
					'label' => esc_html__('Select Spreadsheet', 'wpsyncsheets-gravity-forms'),
					'type' => 'select',
					'name' => 'spreedsheets',
					'tooltip' => esc_html__('Select spreadsheet associated with your google account', 'wpsyncsheets-gravity-forms'),
					'class' => 'medium',
					'choices' => array(),
				),
					array(
					'type' => 'new_spreadsheet_fun',
					'name' => 'newspreedsheets',
					'tooltip' => esc_html__('Create new Google spreadsheet into your google account', 'wpsyncsheets-gravity-forms'),
					'class' => 'ssheet',
				),
					array(
					'label' => esc_html__('Select Sheet', 'wpsyncsheets-gravity-forms'),
					'type' => 'select',
					'name' => 'sheetselect',
					'tooltip' => esc_html__('Select sheet as you have created with above selected spreadsheet', 'wpsyncsheets-gravity-forms'),
					'class' => 'medium',
					'choices' => array(),
				),
					array(
					'label' => esc_html__('Sheet Name', 'wpsyncsheets-gravity-forms'),
					'type' => 'newsheet_fun',
					'name' => 'newsheet',
					'tooltip' => esc_html__('Create new sheet into your Google Spreadsheet', 'wpsyncsheets-gravity-forms'),
					'class' => 'newsheet',
				),
					array(
					'label' => $svg_icon . ' ' . esc_html__('Use AI suggestions to automatically map your fields.', 'wpsyncsheets-gravity-forms'),
					'type' => 'headers_button',
				),
					array(
					'name' => '',
					'label' => '',
					'type' => 'note_ins',
				),
					array(
					'name' => '',
					'label' => esc_html__('View & Clear Spreadsheet', 'wpsyncsheets-gravity-forms'),
					'type' => 'view_clear_button',
					'dependency' => array($this, 'wpsslgf_check_feed'),
				),
			),
		);

		$field_mapping_fields = array(
			'title' => __('Field Mapping', 'wpsyncsheets-gravity-forms'),
			'class' => 'wpssg_field_mapping',
			'fields' => array(
					array(
					'label' => '',
					'type' => 'description',
				),
					array(
					'name' => 'mappedFields',
					'type' => 'field_map',
					'field_map' => self::$instance->wpsslgf_mapfield_for_feed_setting(),
					'merge_tags' => '',
				),
			),
		);

		/* Build Other feed fields array. */
		$other_fields = array(
			'title' => __('Additional Settings', 'wpsyncsheets-gravity-forms'),
			'fields' => array(

					array(
					'name' => '',
					'label' => '',
					'type' => 'headers_note',
				),
					array(
					'label' => esc_html__('Submission Date', 'wpsyncsheets-gravity-forms'),
					'type' => 'checkbox',
					'name' => 'submissiondate',
					'tooltip' => esc_html__('Submission Date', 'wpsyncsheets-gravity-forms'),
					'choices' => array(
							array(
							'label' => esc_html__('Enable', 'wpsyncsheets-gravity-forms'),
							'name' => 'submissiondate',
							'default_value' => 0,
						),
					),
				),
					array(
					'label' => esc_html__('Form ID', 'wpsyncsheets-gravity-forms'),
					'type' => 'checkbox',
					'name' => 'wpssg_form_id',
					'tooltip' => esc_html__('Form ID', 'wpsyncsheets-gravity-forms'),
					'choices' => array(
							array(
							'label' => esc_html__('Enable', 'wpsyncsheets-gravity-forms'),
							'name' => 'wpssg_form_id',
							'default_value' => 0,
						),
					),
				),
					array(
					'label' => esc_html__('Form Title', 'wpsyncsheets-gravity-forms'),
					'type' => 'checkbox',
					'name' => 'wpssg_form_title',
					'tooltip' => esc_html__('Form Title', 'wpsyncsheets-gravity-forms'),
					'choices' => array(
							array(
							'label' => esc_html__('Enable', 'wpsyncsheets-gravity-forms'),
							'name' => 'wpssg_form_title',
							'default_value' => 0,
						),
					),
				),
					array(
					'label' => esc_html__('Freeze Header', 'wpsyncsheets-gravity-forms'),
					'type' => 'checkbox',
					'name' => 'freezecheckbox',
					'tooltip' => esc_html__('Freeze header row (first row) of sheet', 'wpsyncsheets-gravity-forms'),
					'choices' => array(
							array(
							'label' => '',
							'name' => 'freezecheckbox',
							'default_value' => 0,
						),
					),
				),
			),
		);
		if (true === $check_spreadsheet_header_value) {

			return array($feed_title_section, $base_fields, $field_mapping_fields, $other_fields);
		//return array( $base_fields, $other_fields );
		}
		else {
			return array($feed_title_section, $base_fields);
		}
	}

	/**
	 * Check Create New spreadsheet value.
	 */
	public function wpsslgf_check_new_spreadsheet_value()
	{
		/* Get current feed. */
		$feed = self::$instance->get_current_feed();

		/* Get posted settings. */
		$posted_settings = self::$instance->get_posted_settings();

		if (!empty($posted_settings)) {
			/* Show if an action is chosen */
			if ((string)rgar($posted_settings, 'spreedsheets') === 'new' || (string)rgar($posted_settings, 'spreedsheets') === '') {
				return false;
			}
		}
		else {
			/* Show if an action is chosen */
			if ((string)rgars($feed, 'meta/spreedsheets') === 'new' || (string)rgars($feed, 'meta/spreedsheets') === '') {
				return false;
			}
		}
		return true;
	}

	/**
	 * Prepare Google Spreedsheet sheet headers for mapping fields to form fields.
	 *
	 * @access public
	 * @param string $spreadsheetid Spreadsheetid.
	 * @param string $sheetname Sheetname.
	 * @return array $choices
	 */
	public function wpssg_check_headers_exists($spreadsheetid = '', $sheetname = '')
	{
		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-gravity-forms');
			wp_die();
		}
		$spreadsheetid = '';
		$sheetname = '';
		$form_id = '';
		$feed_id = '';

		if (isset($_POST['sid'])) {
			$spreadsheetid = sanitize_text_field(wp_unslash($_POST['sid']));
		}
		if (isset($_POST['sheetname'])) {
			$sheetname = sanitize_text_field(wp_unslash($_POST['sheetname']));
		}
		if (isset($_POST['form_id'])) {
			$form_id = sanitize_text_field(wp_unslash($_POST['form_id']));
		}
		if (isset($_POST['feed_id'])) {
			$feed_id = sanitize_text_field(wp_unslash($_POST['feed_id']));
		}
		if (!empty($spreadsheetid) && !empty($sheetname)) {
			$sheetname = $sheetname . '!A1:ZZ1';
			$response = self::$instance_api->get_row_list($spreadsheetid, $sheetname);
			$values = $response->getValues();
			if (empty($response['values'])) {
				echo true;
				wp_die();
			}
			else {
				$entry_label = self::get_entry_id_header_label($feed_id, $form_id);
				if (isset($response['values'][0][0]) && strtolower($response['values'][0][0]) !== strtolower($entry_label)) {
					wp_send_json_success(
						array(
						'idlabel' => $entry_label,
					)
					);
				}
				echo false;
				wp_die();
			}
		}
		return false;
	}
	/**
	 * Create New Spreadsheet into the user's google account function
	 *
	 * @param string $field Field.
	 * @param bool   $echofield Echo or not.
	 */
	public function settings_new_spreadsheet_fun($field, $echofield = true)
	{
		$svg_icon = '<svg width="25" height="25" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
		<path d="M7.5 2C7.5 5.03757 5.03757 7.5 2 7.5C5.03757 7.5 7.5 9.96243 7.5 13C7.5 9.96243 9.96243 7.5 13 7.5C9.96243 7.5 7.5 5.03757 7.5 2Z" fill="#4169E1"></path>
		<path d="M14 11C14 14.866 10.866 18 7 18C10.866 18 14 21.134 14 25C14 21.134 17.134 18 21 18C17.134 18 14 14.866 14 11Z" fill="#4169E1"></path>
		<path d="M20 3C20 4.65685 18.6569 6 17 6C18.6569 6 20 7.34315 20 9C20 7.34315 21.3431 6 23 6C21.3431 6 20 4.65685 20 3Z" fill="#4169E1"></path>
		</svg>';

		$html =
			'<p> ' . esc_html__('Spreadsheet Name', 'wpsyncsheets-gravity-forms') . '</p>
			<input type="text" name="newspreadsheetlabel" value="" class="medium gaddon-setting gaddon-text" id="newspreadsheetlabel"><br/>
			<p> ' . esc_html__('Sheet Name', 'wpsyncsheets-gravity-forms') . ' </p>
			<input type="text" name="sheetlabel" value="" class="medium gaddon-setting gaddon-text" id="sheetlabel"><br/>
			
			<input type="checkbox" class="gaddon-setting gaddon-checkbox" id="headercheckbox" name="headercheckbox" checked="checked" disabled><span class="headercheckboxspan  ai-headers-map-label-span">' . $svg_icon . ' ' . esc_html__('Use AI suggestions to automatically map your fields.', 'wpsyncsheets-gravity-forms') . '</span><br/><br/>
			<a href="#" class="button" id="gform_google_new_spreadsheet_button">' . esc_html__('Create New Spreadsheet', 'wpsyncsheets-gravity-forms') . '</a><img src="' . esc_url(admin_url('images/spinner.gif')) . '" id="existingloader">';

		$html .= wp_nonce_field('save_general_settings', 'wpsslgf_general_settings');
		if ($echofield) {
			$allowed_html = wp_kses_allowed_html('post');
			echo wp_kses($html, $allowed_html);
		}
		return $html;
	}

	/**
	 * Create New Spreadsheet into the user's google account function
	 *
	 * @param string $field Field.
	 * @param bool   $echofield Echo or not.
	 */
	public function settings_newsheet_fun($field, $echofield = true)
	{

		$html = '<input type="text" name="newsheetlabel" value="" class="medium gaddon-setting gaddon-text" id="newsheetlabel">';

		$html .= wp_nonce_field('save_general_settings', 'wpssg_general_settings');
		if ($echofield) {
			$allowed_html = wp_kses_allowed_html('post');
			echo wp_kses($html, $allowed_html);
		}
		return $html;
	}

	/**
	 * Set instruction for the sheet headers.
	 *
	 * @param string $field Field.
	 * @param bool   $echofield Echo or not.
	 */
	public function settings_note_ins($field, $echofield = true)
	{

		$html = '<i>' . esc_html__('Note: Click here to use AI suggestions to automatically map your fields or create manually to start with Entry ID as a first header name.', 'wpsyncsheets-gravity-forms') . '</i>';

		if ($echofield) {
			$allowed_html = wp_kses_allowed_html('post');
			echo wp_kses($html, $allowed_html);
		}
		return $html;
	}
	/**
	 * No access Note.
	 *
	 * @param string $field Field.
	 * @param bool   $echofield Echo or not.
	 */
	public function settings_no_access_note($field, $echofield = true)
	{

		$html = '<p>' . esc_html__('You do not have permission to access this page.', 'wpsyncsheets-gravity-forms') . '</p>';
		if ($echofield) {
			$allowed_html = wp_kses_allowed_html('post');
			echo wp_kses($html, $allowed_html);
		}
		return $html;
	}
	/**
	 * Set instruction for the sheet headers.
	 *
	 * @param string $field Field.
	 * @param bool   $echofield Echo or not.
	 */
	public function settings_headers_note($field, $echofield = true)
	{

		$html = '<i>' . esc_html__('Note: Entry Id must have to be the first header column in the sheet.', 'wpsyncsheets-gravity-forms') . '</i>';
		if ($echofield) {
			$allowed_html = wp_kses_allowed_html('post');
			echo wp_kses($html, $allowed_html);
		}
		return $html;
	}
	/**
	 * Buy button for WPSyncSheets For Gravity Forms Pro.
	 *
	 * @param string $field Field.
	 * @param bool   $echofield Echo or not.
	 */
	public function settings_buy_pro($field, $echofield = true)
	{

		$html = '
		<div class="wpsslgf-feed-prosection">
            <div class="duc-btn1 pro-version">
                <a target="_blank" href="' . esc_url(WPSSLGF_BUY_PRO_VERSION_URL) . '" ><span class="dashicons dashicons-admin-links"></span>' . esc_html__('Upgrade To Pro', 'wpsyncsheets-gravity-forms') . '</a>
            </div>
		</div>';
		return $html;
	}
	/**
	 * Configures the synchronization button for synchronize old entries to Google Sheet .
	 *
	 * @return array
	 */
	public function settings_headers_button($field, $echofield = true)
	{

		$html = sprintf(
			' <a href="#" class="button" id="gform_google_header_button">%1$s</a><br>',
			esc_html__('Click Here', 'wpsyncsheets-gravity-forms')
		);
		$html .= '<input type="hidden" id="wpssg_set_default_headers" name="wpssg_set_default_headers" value="">';
		$html .= wp_nonce_field('save_general_settings', 'wpssg_general_settings');
		if ($echofield) {
			$allowed_html = wp_kses_allowed_html('post');
			echo wp_kses($html, $allowed_html);
		}
		return $html;
	}
	/**
	 * Configures which columns should be displayed on the feed list page.
	 *
	 * @return array
	 */
	public function feed_list_columns()
	{
		return array(
			'feedName' => esc_html__('Name', 'wpsyncsheets-gravity-forms'),
		);
	}

	/**
	 * Prevent feeds being listed or created if an authToken isn't blank.
	 *
	 * @return bool
	 */
	public function can_create_feed()
	{
		// Get the plugin settings.
		if (!self::$instance_api->getClient()) {
			return false;
		}
		$wpsslgf_google_settings = self::$instance_api->wpsslgf_option('wpssg_google_settings');
		// Access a specific setting e.g. an authToken.
		if (isset($wpsslgf_google_settings[2]) && !empty($wpsslgf_google_settings[2])) {
			return true;
		}
		else {
			return false;
		}
	}
	/**
	 * Configure Addon Message.
	 */
	public function configure_addon_message()
	{
		$settings_link = '<a href="' . esc_url(admin_url('admin.php?page=wpsyncsheets-for-gravity-forms')) . '">' . esc_html__('WPSynSheets Google API Settings', 'wpsyncsheets-gravity-forms') . '</a>.';
		return esc_html__('To get started, please configure your ', 'wpsyncsheets-gravity-forms') . $settings_link;
	}
	/**
	 * Prepare Google Spreedsheet sheet name for feed setting.
	 *
	 * @access public
	 * @return array $choices
	 */
	public function wpsslgf_sheet_for_feed_setting()
	{

		/* Build choices array. */
		$choices = array(
				array(
				'label' => esc_html__('Select a Sheet List', 'wpsyncsheets-gravity-forms'),
				'value' => '',
			),
		);

		/* Get feed settings. */
		$settings = self::$instance->is_postback() ?self::$instance->get_posted_settings() : self::$instance->get_feed(self::$instance->get_current_feed_id());

		$settings = isset($settings['meta']) ? $settings['meta'] : $settings;
		if (!isset($settings['spreedsheets']) || '' === (string)$settings['spreedsheets'] || 'new' === (string)$settings['spreedsheets']) {
			return $choices;
		}

		$response = self::$instance_api->get_sheet_listing($settings['spreedsheets']);

		foreach ($response->getSheets() as $s) {
			$sheets[] = $s['properties']['title'];
		}

		/* Add the Google Sheets to the choices array. */
		if (!empty($sheets)) {
			$i = 0;
			foreach ($sheets as $list) {

				$choices[] = array(
					'label' => $list,
					'value' => $list,
				);
				++$i;
			}
		}
		return $choices;
	}

	/**
	 * Prepare Google Spreedsheet sheet headers for mapping fields to form fields.
	 *
	 * @access public
	 * @return array $choices
	 */
	public function wpsslgf_check_spreadsheet_header_value()
	{

		$settings = self::$instance->is_postback() ?self::$instance->get_posted_settings() : self::$instance->get_feed(self::$instance->get_current_feed_id());
		$settings = isset($settings['meta']) ? $settings['meta'] : $settings;

		if (!empty($settings) && isset($settings['sheetselect'])) {
			$sheet_data = self::$instance->wpsslgf_check_sheet_exist($settings['spreedsheets'], $settings['sheetselect']);
			if ('' !== $sheet_data['spreadsheetid'] && '' !== $sheet_data['sheetname']) {
				$spreadsheetid = $settings['spreedsheets'];
				$sheetname = $settings['sheetselect'] . '!A1:ZZ1';
				$response = self::$instance_api->get_row_list($spreadsheetid, $sheetname);
				$values = $response->getValues();
				if (empty($response['values'])) {
					return true;
				}
				else {
					return false;
				}
			}
		}
	}
	/**
	 * Check Google Spreedsheet sheet headers for mapping fields to form fields.
	 *
	 * @access public
	 * @return array $choices
	 */
	public function wpsslgf_check_spreadsheet_header_values()
	{

		$settings = self::$instance->is_postback() ?self::$instance->get_posted_settings() : self::$instance->get_feed(self::$instance->get_current_feed_id());
		$settings = isset($settings['meta']) ? $settings['meta'] : $settings;

		if (!empty($settings) && isset($settings['sheetselect']) && isset($settings['spreedsheets']) && !empty($settings['spreedsheets'])) {
			$sheet_data = self::$instance->wpsslgf_check_sheet_exist($settings['spreedsheets'], $settings['sheetselect']);
			if ('' !== $sheet_data['spreadsheetid'] && '' !== $sheet_data['sheetname']) {
				$spreadsheetid = $settings['spreedsheets'];
				$sheetname = $settings['sheetselect'] . '!A1:ZZ1';
				$response = self::$instance_api->get_row_list($spreadsheetid, $sheetname);
				$values = $response->getValues();

				if (empty($response['values'])) {
					return false;
				}
				else {
					return true;
				}
			}
		}
	}
	/**
	 * Prepare Google Spreedsheet sheet headers for mapping fields to form fields.
	 *
	 * @access public
	 * @return array $choices
	 */
	public function wpsslgf_mapfield_for_feed_setting()
	{
		$settings = self::$instance->is_postback() ?self::$instance->get_posted_settings() : self::$instance->get_feed(self::$instance->get_current_feed_id());
		$settings = isset($settings['meta']) ? $settings['meta'] : $settings;
		//phpcs:ignore
		if (isset($_GET['id'])) {
			//phpcs:ignore
			$form_id = (int)sanitize_text_field(wp_unslash($_GET['id']));
			$form = RGFormsModel::get_form_meta($form_id);
		}
		$fields_array = self::$instance->wpsslgf_generate_headers($form, 'id');
		if (!empty($settings) && isset($settings['sheetselect'])) {
			$sheet_data = self::$instance->wpsslgf_check_sheet_exist($settings['spreedsheets'], $settings['sheetselect']);
			if ('' !== $sheet_data['spreadsheetid'] && '' !== $sheet_data['sheetname']) {
				$spreadsheetid = $settings['spreedsheets'];
				$sheetname = $settings['sheetselect'] . '!A1:ZZ1';
				$response = self::$instance_api->get_row_list($spreadsheetid, $sheetname);
				$values = $response->getValues();
				$choices = array();

				if (empty($response['values'])) {
					return;
				}
				else {
					$i = 0;
					foreach ($values as $row) {
						if (0 === (int)$i) {
							foreach ($row as $list) {
								if ('Submission Date' === (string)$list || 'Form ID' === (string)$list || 'Form Title' === (string)$list) {
									continue;
								}
								$choices[] = array(
									'name' => str_replace(array(' ', "'"), '_', strtolower(trim($list))),
									'label' => $list,
									'default_value' => array_search($list, $fields_array, true),
								);
							}
							return $choices;
						}
						++$i;
					}
				}
			}
			else {
				return;
			}
		}
		else {
			return;
		}
	}

	/**
	 * Prepare Google Spreedsheet sheet headers.
	 *
	 * @param string $spreadsheetid Google Spreadsheet id.
	 * @param string $sheetname Google Sheet Name.
	 * @access public
	 * @return array $row
	 */
	public function wpsslgf_get_mapfields($spreadsheetid, $sheetname)
	{
		$response = self::$instance_api->get_row_list($spreadsheetid, $sheetname);
		$values = $response->getValues();
		if (empty($values)) {
			print "No data found.\n";
		}
		else {
			$i = 0;
			foreach ($values as $row) {
				// Print columns A and E, which correspond to indices 0 and 4.
				if (0 === (int)$i) {
					return $row;
				}
				++$i;
			}
		}
	}
	/** Conver string to readable form.
	 *
	 * @param array $chars Character.
	 * @access public
	 * @return array $row
	 */
	public function wpsslgf_convert_to_readable($chars)
	{
		$encoding = ini_get('mbstring.internal_encoding');
		$str = preg_replace_callback(
			'/\\\\u([0-9a-fA-F]{4})/u',
			function ($matchval) use ($encoding) {
			return mb_convert_encoding(pack('H*', $matchval[1]), $encoding, 'UTF-16BE');
		},
			$chars
		);
		return $str;
	}
	/**
	 * Insert data into Google Spreadsheet after form submission.
	 *
	 * @param array $entry Entry Array.
	 * @param array $form Form Array.
	 * @access public
	 * @return array $row
	 */
	public function wpsslgf_after_submission($entry, $form)
	{

		if (!self::$instance_api->getClient()) {
			return;
		}

		$form_field_type = array();
		$formfeed = self::$instance->get_feeds($form['id']);
		$wpsslgf_form_data = GFAPI::get_form($form['id']);
		$form_field_type = self::$instance->wpsslgf_form_field_type($form);
		$wpsslgf_google_settings = self::$instance_api->wpsslgf_option('wpssg_google_settings');
		$formfeedcountdata = count($formfeed);

		// Access a specific setting e.g. an authToken.
		if (isset($wpsslgf_google_settings[2]) && !empty($wpsslgf_google_settings[2])) {
			try {
				for ($i = 0; $i < $formfeedcountdata; $i++) {
					$values_data = array();

					if ('1' === (string)$formfeed[$i]['is_active']) {
						$feed = $formfeed[$i]['meta'];
						$flag = 1;

						$is_condition_enabled = rgar($feed, 'feed_condition_conditional_logic') === '1';

						$logic = rgars($feed, 'feed_condition_conditional_logic_object/conditionalLogic');

						if (!empty($is_condition_enabled) && !empty($logic)) {
							$check = GFCommon::evaluate_conditional_logic($logic, $form, $entry);

							if (!$check) {
								continue;
							}
						}

						if (isset($feed['spreedsheets']) && isset($feed['sheetselect'])) {
							$sheet_data = self::$instance->wpsslgf_check_sheet_exist($feed['spreedsheets'], $feed['sheetselect']);
							if ('' === (string)$sheet_data['spreadsheetid'] || '' === (string)$sheet_data['sheetname']) {
								continue;
							}

							$formmapfieldsval[$i] = self::$instance->wpsslgf_get_mapfields($feed['spreedsheets'], $feed['sheetselect']);

							$spreadsheetid = $feed['spreedsheets'];
							$range = $feed['sheetselect'];
							$countformmapfieldsval = count($formmapfieldsval[$i]);

							$val = self::$instance->wpsslgf_prepared_headers($formmapfieldsval[$i], $feed);
							$values_data = self::$instance->wpsslgf_prepared_values($form, $val, $entry, $feed);

							$values = array($values_data);

							$allentry = self::$instance_api->get_row_list($spreadsheetid, $range . '!A:A');
							$data = $allentry->getValues();
							$requestbody = self::$instance_api->valuerangeobject($values);
							$params = self::$instance->get_row_format($feed);
							$range = $range . '!A' . (count($data) + 1);
							$param = self::$instance_api->setparamater($spreadsheetid, $range, $requestbody, $params);
							$response = self::$instance_api->updateentry($param);
						}
					}
				}
			}
			catch (Exception $e) {
				$allowed_html = wp_kses_allowed_html('post');
				echo wp_kses('Message : ' . $e->getMessage(), $allowed_html);
			}
		}
	}
	/**
	 * Return the plugin's icon for the plugin/form settings menu.
	 *
	 * @return string
	 */
	public function get_menu_icon()
	{
		$icon = wp_remote_get(WPSSLGF_URL . 'assets/images/dashicons-wpsyncsheets-black.svg');
		$body = wp_remote_retrieve_body($icon);
		return $body;
	}
	/**
	 * Prepare Google Spreadsheet list
	 *
	 * @access public
	 * @return array $sheetarray
	 */
	public function wpsslgf_list_googlespreedsheet()
	{
		$settings = self::$instance->is_postback() ?self::$instance->get_posted_settings() : self::$instance->get_feed(self::$instance->get_current_feed_id());
		$settings = isset($settings['meta']) ? $settings['meta'] : $settings;

		/* Build choices array. */
		$sheetarray = array(
				array(
				'label' => esc_html__('Select Google Spreeadsheet List', 'wpsyncsheets-gravity-forms'),
				'value' => '',
			),
		);
		$sheetarray = self::$instance_api->get_spreadsheet_listing($sheetarray);
		return $sheetarray;
	}

	/**
	 * Prepare Google Spreadsheet list
	 *
	 * @access public
	 */
	public static function wpsslgf_list_googlespreadsheet_ajax()
	{
		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-gravity-forms');
			wp_die();
		}
		$spreadsheetid = '';
		$sheetname = '';
		if (isset($_POST['id']) && isset($_POST['fid']) && 0 !== (int)sanitize_text_field(wp_unslash($_POST['fid']))) {
			$wpssg_fid = sanitize_text_field(wp_unslash($_POST['fid']));
			$form_id = sanitize_text_field(wp_unslash($_POST['id']));
			// @codingStandardsIgnoreEnd.
			$feeddata = GFAPI::get_feed($wpssg_fid, $form_id);

			$settings = $feeddata['meta'] ? $feeddata['meta'] : array();
		}
		$spreadsheetid = $settings['spreedsheets'];
		$sheetname = $settings['sheetselect'];

		/* Build choices array. */
		$sheetarray = array(
				array(
				'label' => esc_html__('Select Google Spreeadsheet', 'wpsyncsheets-gravity-forms'),
				'value' => '',
			),
		);
		$sheetarray = self::$instance_api->get_spreadsheet_listing($sheetarray);
		echo wp_json_encode(
			array(
			'id' => $spreadsheetid,
			'name' => $sheetname,
			'sheetnames' => $sheetarray,
		)
		);
		wp_die();
	}

	/**
	 * Prepare Google Sheet list
	 *
	 * @access public
	 * @param string $wpssg_sid Spreadsheetid.
	 */
	public static function wpsslgf_list_googlesheet_ajax($wpssg_sid = '')
	{
		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-gravity-forms');
			wp_die();
		}
		if (isset($_POST['sid'])) {
			$wpssg_sid = sanitize_text_field(wp_unslash($_POST['sid']));
		}
		$spreadsheetid = '';
		$sheetname = '';
		if (isset($_POST['id']) && isset($_POST['fid']) && 0 !== (int)sanitize_text_field(wp_unslash($_POST['fid']))) {
			$wpssg_fid = sanitize_text_field(wp_unslash($_POST['fid']));
			$form_id = sanitize_text_field(wp_unslash($_POST['id']));
			// @codingStandardsIgnoreEnd.
			$feeddata = GFAPI::get_feed($wpssg_fid, $form_id);

			$settings = $feeddata['meta'] ? $feeddata['meta'] : array();
		}

		$spreadsheetid = $settings['spreedsheets'];
		$sheetname = $settings['sheetselect'];
		if ('onload' === (string)$wpssg_sid) {
			$wpssg_sid = $spreadsheetid;
		}
		if ('' === (string)$wpssg_sid) {
			/* Build choices array. */
			$sheetarray = array(
					array(
					'label' => esc_html__('Select a Sheet', 'wpsyncsheets-gravity-forms'),
					'value' => '',
				),
					array(
					'label' => esc_html__('Create a new Sheet', 'wpsyncsheets-gravity-forms'),
					'value' => 'newsheet',
				),
			);
			echo wp_json_encode($sheetarray);
			wp_die();
		}
		/* Build choices array. */
		$choices = array(
				array(
				'label' => esc_html__('Select a Sheet', 'wpsyncsheets-gravity-forms'),
				'value' => '',
			),
				array(
				'label' => esc_html__('Create a new Sheet', 'wpsyncsheets-gravity-forms'),
				'value' => 'newsheet',
			),
		);

		$response = self::$instance_api->get_sheet_listing($wpssg_sid);

		foreach ($response->getSheets() as $s) {
			$sheets[] = $s['properties']['title'];
		}

		/* Add the Google Sheets to the choices array. */
		if (!empty($sheets)) {
			$i = 0;
			foreach ($sheets as $list) {

				$choices[] = array(
					'label' => $list,
					'value' => $list,
				);
				++$i;
			}
		}
		echo wp_json_encode(
			array(
			'name' => $sheetname,
			'sheetnames' => $choices,
		)
		);
		wp_die();
	}

	/**
	 * Save Feed Settings
	 *
	 * @param int   $feed_id Feed ID.
	 * @param int   $form_id Form ID.
	 * @param array $settings Settings Array.
	 * @access public
	 * @return array $sheetarray
	 */
	public function save_feed_settings($feed_id, $form_id, $settings)
	{

		if (!isset($_POST['wpssg_general_settings']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['wpssg_general_settings'])), 'save_general_settings')) {
			return false;
		}
		$spreadsheetid = isset($_POST['_gaddon_setting_spreedsheets']) ? sanitize_text_field(wp_unslash($_POST['_gaddon_setting_spreedsheets'])) : '';
		if (empty($spreadsheetid)) {
			$spreadsheetid = isset($_POST['_gform_setting_spreedsheets']) ? sanitize_text_field(wp_unslash($_POST['_gform_setting_spreedsheets'])) : '';
		}
		$sheetname = isset($_POST['_gaddon_setting_sheetselect']) ? sanitize_text_field(wp_unslash($_POST['_gaddon_setting_sheetselect'])) : '';
		if (empty($sheetname)) {
			$sheetname = isset($_POST['_gform_setting_sheetselect']) ? sanitize_text_field(wp_unslash($_POST['_gform_setting_sheetselect'])) : '';
		}
		$new_sheet = false;

		$wpssg_set_default_headers = isset($_POST['wpssg_set_default_headers']) ? sanitize_text_field(wp_unslash($_POST['wpssg_set_default_headers'])) : 0;
		$headercheckbox = (isset($_POST['headercheckbox']) && !empty($_POST['headercheckbox'])) ? 1 : 0;

		$existingvalues = array();
		$entry_label = self::get_entry_id_header_label($feed_id, $form_id);
		$form = RGFormsModel::get_form_meta($form_id);
		if (1 === (int)$wpssg_set_default_headers || 1 === (int)$headercheckbox) {
			$fields_array = self::$instance->wpsslgf_generate_headers($form, '', $feed_id);
			$settings = self::prepare_mapfields_default($settings, $form, $feed_id);
		}

		if ($feed_id > 0 && ((isset($_POST['newsheetlabel']) && !empty($_POST['newsheetlabel']) && 'newsheet' === (string)$sheetname))) {
			try {
				if (1 !== (int)$wpssg_set_default_headers && isset($settings['mappedFields']) && !empty($settings['mappedFields'])) {
					foreach ($settings['mappedFields'] as $h) {
						if (isset($h['key'])) {
							$head = ucwords(str_replace('_', ' ', $h['key']));
							if ('Entry Id' === $head) {
								$head = $entry_label;
							}
							$existingvalues[] = $head;
						}
					}
				}
			}
			catch (Exception $e) {
				return;
			}
		}
		elseif ($feed_id > 0 && (isset($_POST['createnewspreadsheet']))) {
			try {
				if (1 !== (int)$wpssg_set_default_headers) {
					foreach ($settings as $key => $h) {
						if (str_contains($key, 'mappedFields_')) {
							$head = trim(ucwords(str_replace(array('mappedFields_', '_'), ' ', $key)));
							if ('Entry Id' === $head) {
								$head = $entry_label;
							}
							$existingvalues[] = $head;
						}
					}
				}
			}
			catch (Exception $e) {
				return;
			}
		}

		if (isset($_POST['newsheetlabel']) && empty($_POST['newsheetlabel']) && 'newsheet' === (string)$sheetname) {
			$settings['spreadsheet_option'] = 'existing';
		}

		if ($feed_id) {
			$result = self::$instance->update_feed_meta($feed_id, $settings);
			$result = $feed_id;
		}
		else {
			$result = self::$instance->insert_feed($form_id, true, $settings);
		}

		if (!isset($_POST['createnewspreadsheet']) && ('' === $spreadsheetid || '' === $sheetname)) {
			$settings['spreedsheets'] = $spreadsheetid;
			$settings['sheetselect'] = $sheetname;
			$settings['spreadsheet_option'] = 'existing';
			$fid = $result;
			$result1 = self::$instance->update_feed_meta($result, $settings);
		}

		if (!isset($_POST['form_id']) || empty(sanitize_text_field(wp_unslash($_POST['form_id'])))) {
			$_POST['form_id'] = $form_id;
		}
		/*
		 * Check for create new spreadsheet request
		 *
		 */
		if (isset($_POST['createnewspreadsheet'])) {

			if (isset($_POST['newspreadsheetlabel']) && !empty($_POST['newspreadsheetlabel'])) {
				$spreadsheetname = sanitize_text_field(wp_unslash($_POST['newspreadsheetlabel']));
			}

			if (isset($_POST['sheetlabel']) && !empty($_POST['sheetlabel'])) {
				$sheetname = sanitize_text_field(wp_unslash($_POST['sheetlabel']));
			}

			// TODO: Assign values to desired properties of `requestbody`.
			$requestbody = self::$instance_api->newspreadsheetobject($spreadsheetname, $sheetname);
			$response = self::$instance_api->createspreadsheet($requestbody);
			// phpcs:ignore
			$spreadsheetid = $response->spreadsheetId;
			$range = trim($sheetname) . '!A1';

			if (empty($existingvalues)) {
				$fields_array = self::$instance->wpsslgf_generate_headers($form, '', $feed_id);
				$values = array(array_values(array_filter($fields_array)));
			}
			else {
				$values = array($existingvalues);
			}
			$requestbody = self::$instance_api->valuerangeobject($values);

			$params = self::$instance->get_row_format();
			$param = self::$instance_api->setparamater($spreadsheetid, $range, $requestbody, $params);
			$response = self::$instance_api->appendentry($param);
			$settings = self::prepare_mapfields($settings);
			$settings['spreedsheets'] = $spreadsheetid;
			$settings['sheetselect'] = $sheetname;
			$settings['spreadsheet_option'] = 'existing';
			$fid = $result;
			$result1 = self::$instance->update_feed_meta($result, $settings);
			$new_sheet = true;

			// phpcs:ignore
			print('<script>window.location.href = "admin.php?page=gf_edit_forms&view=settings&subview=ggspreadsheetaddon&id=' . $form_id . '&fid=' . $fid . '"</script>');
		}
		if (isset($_POST['newsheetlabel']) && !empty($_POST['newsheetlabel']) && 'newsheet' === (string)$sheetname) {
			$sheetname = sanitize_text_field(wp_unslash($_POST['newsheetlabel']));
			$param = array();
			$param['spreadsheetid'] = $spreadsheetid;
			$param['sheetname'] = $sheetname;
			$wpssg_response = self::$instance_api->newsheetobject($param);
			$newsettings = array();
			$settings = self::prepare_mapfields($settings);
			$settings['spreadsheetid'] = $spreadsheetid;
			$settings['sheetselect'] = $sheetname;
			$settings['spreadsheet_option'] = 'existing';
			$new_sheet = true;

			self::$instance->update_feed_meta($result, $settings);
		}
		$sheet_response = self::$instance_api->get_sheet_listing($spreadsheetid);
		if ((isset($_POST['_gaddon_setting_freezecheckbox']) && sanitize_text_field(wp_unslash($_POST['_gaddon_setting_freezecheckbox'])) !== '') || (isset($_POST['_gform_setting_freezecheckbox']) && sanitize_text_field(wp_unslash($_POST['_gform_setting_freezecheckbox'])) !== '') && 'new' !== $spreadsheetid) {

			$wpssg_freeze = isset($_POST['_gaddon_setting_freezecheckbox']) ? sanitize_text_field(wp_unslash($_POST['_gaddon_setting_freezecheckbox'])) : '';
			if (empty($wpssg_freeze) || 0 === $wpssg_freeze) {
				$wpssg_freeze = isset($_POST['_gform_setting_freezecheckbox']) ? sanitize_text_field(wp_unslash($_POST['_gform_setting_freezecheckbox'])) : '';
			}

			if ('on' === (string)$wpssg_freeze || 1 === (int)$wpssg_freeze) {
				$wpssg_freeze = 1;
			}
			else {
				$wpssg_freeze = 0;
			}
			foreach ($sheet_response->getSheets() as $key => $value) {
				if ((string)$value['properties']['title'] === $sheetname) {
					$requestbody = self::$instance_api->freezeobject($value['properties']['sheetId'], $wpssg_freeze);
					$requestobject = array();
					$requestobject['spreadsheetid'] = $spreadsheetid;
					$requestobject['requestbody'] = $requestbody;
					self::$instance_api->formatsheet($requestobject);
				}
			}
		}

		$response = self::$instance_api->get_row_list($spreadsheetid, $sheetname . '!A1:ZZ1');
		$data = $response->getValues();
		if (is_null($data) || empty($data)) {
			$data[0] = array();
		}

		if (isset($_POST['submissiondate']) || isset($_POST['wpssg_form_id']) || isset($_POST['wpssg_form_title']) || isset($_POST['paymentstatusheader']) || isset($_POST['insert_import_checkbox']) || isset($_POST['update_import_checkbox']) || isset($_POST['delete_import_checkbox'])) {

			$fields_array = $data[0];
			$update_header = false;
			if (isset($_POST['submissiondate']) && !in_array('Submission Date', $data[0], true)) {
				$fields_array[] = 'Submission Date';
				$update_header = true;
			}
			if (isset($_POST['wpssg_form_id']) && !in_array('Form ID', $data[0], true)) {
				$fields_array[] = 'Form ID';
				$update_header = true;
			}
			if (isset($_POST['wpssg_form_title']) && !in_array('Form Title', $data[0], true)) {
				$fields_array[] = 'Form Title';
				$update_header = true;
			}
			if ($update_header) {
				$range = $sheetname . '!A1';
				$values = array($fields_array);
				$requestbody = self::$instance_api->valuerangeobject($values);
				$params = self::$instance->get_row_format();
				$param = self::$instance_api->setparamater($spreadsheetid, $range, $requestbody, $params);
				$response = self::$instance_api->updateentry($param);
			}
		}
		$deleterequestarray = array();
		if (isset($_POST['headerset'])) {
			$range = $sheetname . '!A1';
			$settings = self::prepare_mapfields($settings);
			self::$instance->update_feed_meta($result, $settings);
			$form = RGFormsModel::get_form_meta($form_id);

			if (empty($existingvalues)) {
				$fields_array = self::$instance->wpsslgf_generate_headers($form, '', $feed_id);
				$values = array(array_values(array_filter($fields_array)));
			}
			else {
				$values = array($existingvalues);
			}
			$requestbody = self::$instance_api->valuerangeobject($values);

			$params = self::$instance->get_row_format();
			$param = self::$instance_api->setparamater($spreadsheetid, $range, $requestbody, $params);
			$response = self::$instance_api->updateentry($param);

			$fid = $result;
			// phpcs:ignore
			print('<script>window.location.href = "admin.php?page=gf_edit_forms&view=settings&subview=ggspreadsheetaddon&id=' . $form_id . '&fid=' . $fid . '"</script>');
		}
		return $result;
	}

	/**
	 * Enable feed duplication.
	 *
	 * @param int $id ID.
	 * @access public
	 * @return bool
	 */
	public function can_duplicate_feed($id)
	{
		return false;
	}

	/**
	 * Prepare mapfields.
	 *
	 * @param array $settings Settings Array.
	 * @access public
	 * @return array $settings
	 */
	public static function prepare_mapfields($settings)
	{
		if (isset($settings['mappedFields']) && !empty($settings['mappedFields'])) {
			foreach ($settings['mappedFields'] as $key => $value) {
				$settings['mappedFields_' . $value['key']] = $value['value'];
			}
		}
		return $settings;
	}
	/**
	 * Prepare default mapfields.
	 *
	 * @param array $settings Settings Array.
	 * @access public
	 * @return array $settings
	 */
	public static function prepare_mapfields_default($settings, $form, $feed_id)
	{
		if (isset($settings['mappedFields']) && !empty($settings['mappedFields'])) {
			unset($settings['mappedFields']);
			foreach ($settings as $key => $h) {
				if (str_contains($key, 'mappedFields_')) {
					unset($settings[$key]);
				}
			}
			$fields_array = self::$instance->wpsslgf_generate_headers($form, 'id', $feed_id);
			foreach ($fields_array as $field_id => $field_label) {
				$field_label_val = str_replace(self::$field_replace_parameters, '_', strtolower(trim($field_label)));
				$settings['mappedFields'][] = array(
					'key' => $field_label_val,
					'custom_key' => '',
					'value' => $field_id,
					'custom_value' => '',
				);

				$settings['mappedFields_' . $field_label_val] = $field_id;
			}
		}
		return $settings;
	}

	/**
	 * Heading row for field map table.
	 *
	 * @since  2.2
	 * @access public
	 *
	 * @uses GFAddOn::field_map_title()
	 *
	 * @return string
	 */
	public function field_map_table_header()
	{
		return '<thead>
			<tr>
				<th>' . esc_html__('Sheet Headers', 'wpsyncsheets-gravity-forms') . '</th>
				<th>' . esc_html__('Form Field', 'wpsyncsheets-gravity-forms') . '</th>
			</tr>
		</thead>';
	}
	/**
	 * Generate headers.
	 *
	 * @param array  $form Form Array.
	 * @param string $format Return with id.
	 */
	public function wpsslgf_generate_headers($form, $format = '')
	{
		$fields_array = array();
		$fields_array['id'] = 'Entry Id';
		if (is_array($form['fields'])) {
			foreach ($form['fields'] as $field) {
				if (1 === (int)$field['displayOnly']) {
					continue;
				}
				if ('checkbox' === (string)$field['type']) {
					$fields_array[$field->id] = GFCommon::get_label($field, $field->id);
				}
				elseif (isset($field['inputs']) && is_array($field['inputs']) && !empty($field['inputs'])) {

					foreach ($field['inputs'] as $input) {
						if (!isset($input['isHidden'])) {
							$fields_array[$input['id']] = GFCommon::get_label($field, $input['id']);
						}
						elseif (isset($input['isHidden']) && 1 !== $input['isHidden']) {
							$fields_array[$input['id']] = GFCommon::get_label($field, $input['id']);
						}
					}
				}

				if ('list' === (string)$field['type'] && is_array($field['choices']) && !empty($field['choices'])) {
					foreach ($field['choices'] as $inx => $choice) {
						if (!empty($choice['text'])) {
							$fields_array[$field->id . '.' . $inx] = $choice['text'];
						}
					}
				}
				elseif (isset($field) && is_object($field) && !isset($field['inputs'])) {
					$fields_array[$field->id] = GFCommon::get_label($field, $field->id);
				}
			}
		}

		if ('id' === (string)$format) {
			return $fields_array;
		}
		else {
			return array_values($fields_array);
		}
	}

	/**
	 * Check Field is display only or not.
	 *
	 * @param array $form Form Array.
	 */
	public function wpsslgf_form_field_type($form)
	{
		$fields_array = array();
		if (is_array($form['fields'])) {
			foreach ($form['fields'] as $field) {
				if (1 === (int)$field['displayOnly']) {
					continue;
				}
				$fields_array[$field->id] = $field['type'];
			}
		}
		return $fields_array;
	}
	/**
	 * Reset Google API Settings
	 */
	public static function wpsslgf_reset_settings()
	{
		if (!current_user_can('edit_wpsyncsheets_gravity_forms_lite_main_settings')) {
			echo esc_html__('You do not have permission to access this page.', 'wpsyncsheets-gravity-forms');
			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-gravity-forms');
			wp_die();
		}
		try {
			$wpsslgf_google_settings_value = self::$instance_api->wpsslgf_option('wpssg_google_settings');
			$settings = array();
			foreach ($wpsslgf_google_settings_value as $key => $value) {
				$settings[$key] = '';
			}
			self::$instance_api->wpsslgf_update_option('wpssg_google_settings', $settings);
			self::$instance_api->wpsslgf_update_option('wpssg_google_accessToken', '');
		}
		catch (Exception $e) {
			$allowed_html = wp_kses_allowed_html('post');
			echo wp_kses($e->getMessage(), $allowed_html);
		}
		echo 'successful';
		wp_die();
	}
	/**
	 * Change the row format of spreadsheet.
	 *
	 * @param array $settings An array containing the sheet object to change the row format of spreadsheet.
	 */
	public function get_row_format($settings = array())
	{
		if (isset($settings['row_format']) && 'userenter' === (string)$settings['row_format']) {
			$params = array('valueInputOption' => 'USER_ENTERED');
		}
		else {
			$params = array('valueInputOption' => 'RAW');
		}
		return $params;
	}
	/**
	 * Prepare Header List.
	 *
	 * @param array $formmapfieldsval An array containing the form fields.
	 * @param array $feed An array form.
	 */
	public function wpsslgf_prepared_headers($formmapfieldsval, $feed)
	{
		$countformmapfieldsval = count($formmapfieldsval);
		$val = array();
		for ($j = 0; $j < $countformmapfieldsval; $j++) {
			if ('Submission Date' === (string)$formmapfieldsval[$j]) {
				$val[$j] = 'Submission Date';
				continue;
			}
			if ('Form ID' === (string)$formmapfieldsval[$j]) {
				$val[$j] = 'Form ID';
				continue;
			}
			if ('Form Title' === (string)$formmapfieldsval[$j]) {
				$val[$j] = 'Form Title';
				continue;
			}
			$fieldname = str_replace(array(' ', '.'), '_', strtolower(trim($formmapfieldsval[$j])));
			if (isset($feed['mappedFields_' . $fieldname])) {
				$val[$j] = $feed['mappedFields_' . $fieldname];
			}
		}
		return $val;
	}
	/**
	 * Description.
	 *
	 * @return array
	 */
	public function settings_description()
	{
		$html = esc_html__('Define the form fields mapping on which columns in your Google Spreadsheet.', 'wpsyncsheets-gravity-forms');
		return $html;
	}
	/**
	 * Prepare Value for insert in Google Spreadsheet.
	 *
	 * @param array $form An array form.
	 * @param array $val An array containing the form fields.
	 * @param array $entry Gravity Form Entry.
	 * @param array $feed Feed Array.
	 *
	 * @return array.
	 */
	public function wpsslgf_prepared_values($form, $val, $entry, $feed)
	{

		$last_key = '';
		$countval = count($val);
		$wpsslgf_form_data = GFAPI::get_form($form['id']);
		$form_field_type = self::$instance->wpsslgf_form_field_type($form);
		$values_data = array();

		for ($k = 0; $k < $countval; $k++) {

			if (!isset($val[$k])) {
				$values_data[$k] = '';
				continue;
			}
			if ('Form ID' === (string)$val[$k] && isset($feed['wpssg_form_id']) && $feed['wpssg_form_id']) {
				$values_data[$k] = isset($form['id']) ? $form['id'] : '';
				continue;
			}
			if ('Form Title' === (string)$val[$k] && isset($feed['wpssg_form_title']) && $feed['wpssg_form_title']) {
				$values_data[$k] = isset($wpsslgf_form_data['title']) ? $wpsslgf_form_data['title'] : '';
				continue;
			}
			if ('Submission Date' === (string)$val[$k] && isset($feed['submissiondate']) && $feed['submissiondate']) {
				if (isset($feed['submissiondate']) && !empty($feed['submissiondate'])) {
					$default_format = self::$instance_api->wpsslgf_option('date_format') . ' ' . self::$instance_api->wpsslgf_option('time_format');
					$date_val = GFCommon::format_date($entry['date_created'], false, $default_format, false);
					$values_data[$k] = $date_val;

				}
				else {
					$values_data[$k] = '';
				}
				continue;
			}

			$num = $val[$k];
			$is_explode = 0;
			if (false !== strpos($num, '.')) {
				$fid = explode('.', $num);
				$num = $fid[0];
				$is_explode = 1;
			}

			if (!empty($num) && array_key_exists($num, $form_field_type)) {
				if ('checkbox' === (string)$form_field_type[$num] && 0 === (int)$is_explode) {
					$field = GFFormsModel::get_field($form, $num);
					$checkbox_value = '';
					foreach ($field['inputs'] as $choice) {
						if (!empty($entry[$choice['id']])) {
							$checkbox_value .= $entry[$choice['id']] . ',';
						}
					}
					$values_data[$k] = rtrim($checkbox_value, ',');
					continue;
				}
				elseif ('list' === (string)$form_field_type[$num]) {
					if ('' === (string)$entry[$num] || null === $entry[$num]) {
						$values_data[$k] = '';
					}
					else {
						$last_key = $num;
						$wpsslgf_form_field = GFFormsModel::get_field($wpsslgf_form_data, $num);
						$is_enablecolumns = isset($wpsslgf_form_field['enableColumns']) ? $wpsslgf_form_field['enableColumns'] : 0;
						// phpcs:ignore
						$list_array = array();
						$list_array = maybe_unserialize($entry[$num]);
						if (isset($list_array[0]) && !empty($list_array[0]) && 1 === (int)$is_enablecolumns) {
							if (0 === (int)$is_explode) {
								$list_row_array = array();
								foreach ($list_array as $list_rows) {
									$list_row_array[] = implode(',', $list_rows);
								}
								$list_row = implode('|', $list_row_array);
								$values_data[$k] = $list_row;
							}
							else {
								$listkeys = array_keys($list_array[0]);
								$list_row_array = array();

								$list_columns = array();
								foreach ($wpsslgf_form_field['choices'] as $choice) {
									$list_columns[] = isset($choice['value']) ? $choice['value'] : '';
								}

								foreach ($list_columns as $ldata) {
									$list_row_array[] = in_array($ldata, $listkeys, true) ? implode(',', array_column($list_array, $ldata)) : '';
								}
								if (false !== strpos($val[$k], '.')) {
									$list_field_id = explode('.', $val[$k]);
									$values_data[$k] = isset($list_row_array[$list_field_id[1]]) ? $list_row_array[$list_field_id[1]] : '';
								}
							}
						}
						elseif (!empty($list_array)) {
							$values_data[$k] = implode(',', $list_array);
						}
						else {
							$values_data[$k] = '';
						}
					}
					continue;
				}
				elseif ('name' === (string)$form_field_type[$num] && 0 === (int)$is_explode) {
					$values_data[$k] = $this->get_full_name($entry, $num);
					continue;
				}
				elseif ('address' === (string)$form_field_type[$num] && 0 === (int)$is_explode) {
					$address_arr = array();
					$address = '';
					foreach ($entry as $field_key => $field_val) {
						if (1 === strpos('"' . $field_key, $num . '.')) {
							$address_arr[$field_key] = $field_val;
						}
					}
					$address_arr = array_filter($address_arr);
					ksort($address_arr);
					$address = implode(',', $address_arr);
					$values_data[$k] = $address;
					continue;
				}
				elseif ('fileupload' === (string)$form_field_type[$num] && 0 === (int)$is_explode) {
					if (isset($entry[$val[$k]]) && (!empty($entry[$val[$k]]))) {
						$wpsslgf_url = json_decode($entry[$val[$k]]);
						$wpsslgf_url_val = '';
						if (null === $wpsslgf_url) { // check if it was invalid json string.
							$wpsslgf_url_val = $entry[$val[$k]];
						}

						if (is_array($wpsslgf_url)) {
							$wpsslgf_url_val = implode(',', $wpsslgf_url);
						}
						$wpsslgf_url_val = str_replace(array('[', ']', '"'), '', $wpsslgf_url_val);
						$values_data[$k] = $wpsslgf_url_val;
					}
					else {
						$values_data[$k] = '';
					}
					continue;
				}
			}
			if ('form_title' === (string)$val[$k]) {
				$values_data[$k] = isset($wpsslgf_form_data['title']) ? $wpsslgf_form_data['title'] : '';
				continue;
			}
			if (!isset($entry[$val[$k]]) || '' === (string)$entry[$val[$k]] || null === $entry[$val[$k]]) {
				$values_data[$k] = '';
				continue;
			}
			elseif ((isset($form_field_type[$num]) && 'date' === (string)$form_field_type[$num]) || 'date_created' === (string)$val[$k]) {
				if ((bool)strtotime($entry[$val[$k]])) {
					$date_format = self::$instance_api->wpsslgf_option('date_format') . ' ' . self::$instance_api->wpsslgf_option('time_format');

					if (isset($form_field_type[$num]) && 'date' === (string)$form_field_type[$num]) {
						//phpcs:ignore
						$values_data[$k] = date($date_format, strtotime($entry[$val[$k]]));
					}
					else {
						$values_data[$k] = GFCommon::format_date($entry[$val[$k]], false, $date_format, false);
					}
				}
				else {
					$values_data[$k] = $entry[$val[$k]];
				}
			}
			elseif (isset($form_field_type[$val[$k]]) && 'multiselect' === (string)$form_field_type[$val[$k]]) {
				$wpsslgf_multiselect = json_decode($entry[$val[$k]]);
				$wpsslgf_multiselect_val = '';
				if (null === $wpsslgf_multiselect) { // check if it was invalid json string.
					$wpsslgf_multiselect_val = $entry[$val[$k]];
				}
				if (is_array($wpsslgf_multiselect)) {
					$wpsslgf_multiselect_val = implode(',', $wpsslgf_multiselect);
				}
				$values_data[$k] = str_replace(array('[', ']', '"', ','), array('', '', '', ', '), self::$instance->wpsslgf_convert_to_readable($wpsslgf_multiselect_val));
			}
			else {
				$values_data[$k] = self::$instance->wpsslgf_convert_to_readable($entry[$val[$k]]);
			}
		}
		return $values_data;
	}
	/**
	 * Convert to Integer.
	 *
	 * @param string $data Entry ids array.
	 */
	public function wpsslgf_convert_int($data)
	{
		$data = array_map(
			function ($element) {
			return (is_numeric($element) ? (int)$element : $element);
		},
			$data
		);
		return $data;
	}

	/**
	 * Convert to String.
	 *
	 * @param string $data Entry ids array.
	 */
	public function wpsslgf_convert_string($data)
	{
		$data = array_map(
			function ($element) {
			return (is_string($element) ? (string)$element : $element);
		},
			$data
		);
		return $data;
	}
	/**
	 * Check spreadsheet and sheet exist or not.
	 *
	 * @param string $spreadsheetid Spreadsheet ID.
	 * @param string $sheetname Sheet Name.
	 */
	public function wpsslgf_check_sheet_exist($spreadsheetid, $sheetname)
	{
		$spreadsheets = self::$instance->wpsslgf_list_googlespreedsheet();
		$spreadsheet_list = array_column($spreadsheets, 'value');
		$data = array();
		$data['spreadsheetid'] = '';
		$data['sheetname'] = '';
		if ('' !== $spreadsheetid && 'new' !== $spreadsheetid && in_array($spreadsheetid, $spreadsheet_list, true)) {
			$data['spreadsheetid'] = $spreadsheetid;
			$response = self::$instance_api->get_sheet_listing($spreadsheetid);
			foreach ($response->getSheets() as $s) {
				$sheets[] = $s['properties']['title'];
			}
			if (!empty($sheetname) && in_array($sheetname, $sheets, true)) {
				$data['sheetname'] = $sheetname;
			}
		}
		return $data;
	}

	/**
	 * Clear the Spreadsheet.
	 */
	public function wpsslgf_clear_spreadsheet()
	{

		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-gravity-forms');
			wp_die();
		}
		if (isset($_POST['form_id'])) {
			$form_id = (int)sanitize_text_field(wp_unslash($_POST['form_id']));
		}
		if (isset($_POST['fid'])) {
			$wpsslgf_fid = (int)sanitize_text_field(wp_unslash($_POST['fid']));
		}

		$syncformfeed = RGFormsModel::get_form_meta($form_id);
		$formfeed = self::$instance->get_feeds($form_id);
		$form_field_type = self::$instance->wpsslgf_form_field_type($syncformfeed);

		foreach ($formfeed as $feedsetting) {
			if ((int)$feedsetting['id'] === $wpsslgf_fid) {
				$settings = $feedsetting['meta'];
			}
		}

		$spreadsheetid = $settings['spreedsheets'];
		$sheetname = $settings['sheetselect'];
		$total = self::$instance_api->get_row_list($spreadsheetid, $sheetname);
		if ($total->getValues() && !is_null($total->getValues())) {
			$total_headers = count($total['values'][0]);
			$last_column = self::$instance->wpsslgf_get_column_index($total_headers);
			try {
				$range = $sheetname . '!A2:' . $last_column . '100000';
				$requestbody = self::$instance_api->clearobject();
				$param = array();
				$param['spreadsheetid'] = $spreadsheetid;
				$param['sheetname'] = $range;
				$param['requestbody'] = $requestbody;
				$response = self::$instance_api->clear($param);
			}
			catch (Exception $e) {
				$allowed_html = wp_kses_allowed_html('post');
				echo wp_kses('Message : ' . $e->getMessage(), $allowed_html);
			}
		}

		echo esc_html('successful');
		wp_die();
	}
	/**
	 * Return Character based on gven number
	 *
	 * @param int $number Number.
	 */
	public static function wpsslgf_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;
	}
	/**
	 * Configures the View and Clear Spreadsheet button .
	 *
	 * @param string $field Field.
	 * @param bool   $echofield Echo or not.
	 * @return array
	 */
	public function settings_view_clear_button($field, $echofield = true)
	{
		$view_icon = '<svg width="19" height="19" viewBox="0 0 19 14" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-right:6px;"> <path d="M9.49967 10.8334C10.5413 10.8334 11.4268 10.4688 12.1559 9.73962C12.8851 9.01046 13.2497 8.12504 13.2497 7.08337C13.2497 6.04171 12.8851 5.15629 12.1559 4.42712C11.4268 3.69796 10.5413 3.33337 9.49967 3.33337C8.45801 3.33337 7.57259 3.69796 6.84342 4.42712C6.11426 5.15629 5.74967 6.04171 5.74967 7.08337C5.74967 8.12504 6.11426 9.01046 6.84342 9.73962C7.57259 10.4688 8.45801 10.8334 9.49967 10.8334ZM9.49967 9.33337C8.87467 9.33337 8.34343 9.11462 7.90593 8.67712C7.46843 8.23962 7.24967 7.70837 7.24967 7.08337C7.24967 6.45837 7.46843 5.92712 7.90593 5.48962C8.34343 5.05212 8.87467 4.83337 9.49967 4.83337C10.1247 4.83337 10.6559 5.05212 11.0934 5.48962C11.5309 5.92712 11.7497 6.45837 11.7497 7.08337C11.7497 7.70837 11.5309 8.23962 11.0934 8.67712C10.6559 9.11462 10.1247 9.33337 9.49967 9.33337ZM9.49967 13.3334C7.4719 13.3334 5.62467 12.7674 3.95801 11.6355C2.29134 10.5035 1.08301 8.98615 0.333008 7.08337C1.08301 5.1806 2.29134 3.66324 3.95801 2.53129C5.62467 1.39935 7.4719 0.833374 9.49967 0.833374C11.5275 0.833374 13.3747 1.39935 15.0413 2.53129C16.708 3.66324 17.9163 5.1806 18.6663 7.08337C17.9163 8.98615 16.708 10.5035 15.0413 11.6355C13.3747 12.7674 11.5275 13.3334 9.49967 13.3334ZM9.49967 11.6667C11.0691 11.6667 12.5101 11.2535 13.8226 10.4271C15.1351 9.60073 16.1386 8.48615 16.833 7.08337C16.1386 5.6806 15.1351 4.56601 13.8226 3.73962C12.5101 2.91323 11.0691 2.50004 9.49967 2.50004C7.93023 2.50004 6.48926 2.91323 5.17676 3.73962C3.86426 4.56601 2.86079 5.6806 2.16634 7.08337C2.86079 8.48615 3.86426 9.60073 5.17676 10.4271C6.48926 11.2535 7.93023 11.6667 9.49967 11.6667Z" fill="currentColor"></path> </svg>';
		$clear_icon = '<svg width="19" height="19" viewBox="0 0 19 19" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-right:6px;"> <path d="M8.66674 8.66671H10.3334V2.83337C10.3334 2.59726 10.2535 2.39935 10.0938 2.23962C9.9341 2.0799 9.73619 2.00004 9.50008 2.00004C9.26397 2.00004 9.06605 2.0799 8.90633 2.23962C8.7466 2.39935 8.66674 2.59726 8.66674 2.83337V8.66671ZM3.66674 12H15.3334V10.3334H3.66674V12ZM2.45841 17H4.50008V15.3334C4.50008 15.0973 4.57994 14.8993 4.73966 14.7396C4.89938 14.5799 5.0973 14.5 5.33341 14.5C5.56952 14.5 5.76744 14.5799 5.92716 14.7396C6.08688 14.8993 6.16674 15.0973 6.16674 15.3334V17H8.66674V15.3334C8.66674 15.0973 8.7466 14.8993 8.90633 14.7396C9.06605 14.5799 9.26397 14.5 9.50008 14.5C9.73619 14.5 9.9341 14.5799 10.0938 14.7396C10.2535 14.8993 10.3334 15.0973 10.3334 15.3334V17H12.8334V15.3334C12.8334 15.0973 12.9133 14.8993 13.073 14.7396C13.2327 14.5799 13.4306 14.5 13.6667 14.5C13.9029 14.5 14.1008 14.5799 14.2605 14.7396C14.4202 14.8993 14.5001 15.0973 14.5001 15.3334V17H16.5417L15.7084 13.6667H3.29174L2.45841 17ZM16.5417 18.6667H2.45841C1.91674 18.6667 1.47924 18.4514 1.14591 18.0209C0.812577 17.5903 0.715354 17.1112 0.854243 16.5834L2.00008 12V10.3334C2.00008 9.87504 2.16327 9.48268 2.48966 9.15629C2.81605 8.8299 3.20841 8.66671 3.66674 8.66671H7.00008V2.83337C7.00008 2.13893 7.24313 1.54865 7.72924 1.06254C8.21535 0.57643 8.80563 0.333374 9.50008 0.333374C10.1945 0.333374 10.7848 0.57643 11.2709 1.06254C11.757 1.54865 12.0001 2.13893 12.0001 2.83337V8.66671H15.3334C15.7917 8.66671 16.1841 8.8299 16.5105 9.15629C16.8369 9.48268 17.0001 9.87504 17.0001 10.3334V12L18.1459 16.5834C18.3265 17.1112 18.2466 17.5903 17.9063 18.0209C17.566 18.4514 17.1112 18.6667 16.5417 18.6667Z" fill="currentColor"></path> </svg>';
		$download_icon = '<svg xmlns="http://www.w3.org/2000/svg" width="19" height="19" viewBox="0 0 24 24" style="margin-right:6px;"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 3.33c2.98 1.72 5 4.96 5 8.66 0 5.52-4.48 10-10 10 -5.53 0-10-4.48-10-10 0-3.71 2.01-6.94 5-8.67m1 8.66l4 4m0 0l4-4m-4 4v-14"></path></svg>';

		$html = sprintf(
			'<a href="#" class="button" id="gform_google_view_button" target="_blank">%1$s %2$s</a>',
			$view_icon,
			esc_html__('View', 'wpsyncsheets-gravity-forms')
		);

		$html .= sprintf(
			'<a href="#" class="button" id="gform_google_clear_button">%1$s %2$s</a>',
			$clear_icon,
			esc_html__('Clear', 'wpsyncsheets-gravity-forms')
		);
		$html .=
			'<img src="' . esc_url(admin_url('images/spinner.gif')) . '" id="clearloader"><span id="cleartext">' . esc_html__('Clearing...', 'wpsyncsheets-gravity-forms') . '</span>';
		$html .= sprintf(
			'<a href="#" class="button" id="gform_google_download_button" target="_blank">%1$s %2$s</a>',
			$download_icon,
			esc_html__('Download', 'wpsyncsheets-gravity-forms')
		);
		$html .= wp_nonce_field('save_general_settings', 'wpssg_general_settings');
		if ($echofield) {
			$allowed_html = wp_kses_allowed_html('post');
			$allowed_html['svg'] = array(
				'width' => true,
				'height' => true,
				'viewbox' => true,
				'fill' => true,
				'xmlns' => true,
				'stroke' => true,
				'stroke-width' => true,
				'stroke-linecap' => true,
				'stroke-linejoin' => true,
				'style' => true,
			);
			$allowed_html['path'] = array(
				'd' => true,
				'fill' => true,
				'stroke' => true,
				'stroke-width' => true,
				'stroke-linecap' => true,
				'stroke-linejoin' => true,
			);
			$allowed_html['circle'] = array(
				'cx' => true,
				'cy' => true,
				'r' => true,
			);
			$allowed_html['polyline'] = array('points' => true);
			$allowed_html['line'] = array(
				'x1' => true,
				'y1' => true,
				'x2' => true,
				'y2' => true,
			);

			echo wp_kses($html, $allowed_html);
		}
		return $html;
	}
	/**
	 * Check feed is saved or not.
	 *
	 * @access public
	 */
	public function wpsslgf_check_feed()
	{
		// @codingStandardsIgnoreStart.
		if (isset($_GET['id']) && isset($_GET['fid']) && 0 !== (int)sanitize_text_field(wp_unslash($_GET['fid']))) {
			$wpssg_fid = sanitize_text_field(wp_unslash($_GET['fid']));
			$form_id = sanitize_text_field(wp_unslash($_GET['id']));
			// @codingStandardsIgnoreEnd.
			$feeddata = GFAPI::get_feed($wpssg_fid, $form_id);

			$settings = $feeddata['meta'] ? $feeddata['meta'] : array();

			if (isset($settings['spreedsheets']) && isset($settings['sheetselect'])) {
				$sheet_data = self::$instance->wpsslgf_check_sheet_exist($settings['spreedsheets'], $settings['sheetselect']);
				if ('' !== (string)$sheet_data['spreadsheetid'] && '' !== (string)$sheet_data['sheetname']) {
					return true;
				}
			}
			return false;
		}
		else {
			return false;
		}
	}
	public static function get_entry_id_header_label($feed_id = 0, $form_id = 0)
	{
		// Default label for Entry ID.
		$entry_label = 'Entry ID';
		if ($feed_id && $form_id) {
			// Allow filter to change per feed.
			$entry_label = apply_filters(
				'wpssg_filter_entry_id_header_label', // phpcs:ignore.
				$entry_label,
				$feed_id,
				$form_id
			);
		}
		return $entry_label;
	}
}