<?php
/**
 * WPSSLC_Service Class
 *
 * @package contactsheets-lite
 */
if (!defined('ABSPATH')) {
	exit; // Exit if accessed directly
}
/**
 * WPSSLC_Google_API class.
 *
 * @since 1.0.0
 */
class WPSSLC_Service
{
	/**
	 * Instance of class.
	 *
	 * @var $wpsslc_instance Instance variable of class.
	 */
	private static $wpsslc_instance = null;
	/**
	 * Instance of WPSSLC_Google_API_Functions class.
	 *
	 * @var $wpsslc_instance_api Instance variable of WPSSLC_Google_API_Functions class.
	 */
	private static $wpsslc_instance_api = null;
	/**
	 * Instance of Google API service.
	 *
	 * @var $wpsslc_instance_service Instance variable of Google API service.
	 */
	private static $wpsslc_instance_service = null;
	/**
	 * Allowed Tags.
	 *
	 * @var $allowed_tags.
	 */
	private $allowed_tags = array('text', 'email', 'url', 'file', 'tel', 'number', 'range', 'date', 'textarea', 'select', 'checkbox', 'radio', 'acceptance', 'quiz');
	/**
	 * Get an instance of this class.
	 *
	 * @return instance
	 */
	public static function get_instance()
	{
		if (null === self::$wpsslc_instance) {
			self::$wpsslc_instance = new WPSSLC_Service();
		}
		return self::$wpsslc_instance;
	}
	/**
	 * Get an instance of WPSSLC_Google_API_Functions class.
	 *
	 * @return WPSSLC_Google_API_Functions class instance
	 */
	public static function get_clientinstance()
	{
		if (null === self::$wpsslc_instance_api) {
			self::$wpsslc_instance_api = new ContactsheetsLite\WPSSLC_Google_API_Functions();
		}
		return self::$wpsslc_instance_api;
	}
	/**
	 *  Set things up.
	 *
	 *  @since 1.0
	 */
	public function __construct()
	{

		// Add new tab to contact form 7 editors panel.
		add_filter('wpcf7_editor_panels', array($this, 'wpsslc_editor_panels'));
		add_action('wpcf7_after_save', array($this, 'wpsslc_save_settings'));
		add_action('wpcf7_before_send_mail', array($this, 'wpsslc_wpcf7_before_send_mail'), 10);
		add_action('wpcf7_before_send_mail', array($this, 'wpsslc_save_to_google_spreadsheets'), 50, 1);
		add_action('wpcf7_before_send_mail', array($this, 'wpssc_save_cf7_submission'));

		add_action('wp_ajax_wpsslc_reset_settings', array($this, 'wpsslc_reset_settings'));
		add_action('wp_ajax_wpsslc_clear_sheet', array($this, 'wpsslc_clear_sheet'));

		add_action('wp_ajax_wpsslc_get_sheets_list', array($this, 'wpsslc_get_sheetslist'));

		$this->get_clientinstance();
	}
	public function wpssc_save_cf7_submission($contact_form)
	{

		// Start timer immediately
		$start_time = microtime(true);

		$form_id = $contact_form->id();

		$db_enabled = get_post_meta($form_id, 'wpssc_enable_db_save', true);

		if ('yes' !== $db_enabled) {
			return;
		}

		global $wpdb;

		if (!$contact_form instanceof WPCF7_ContactForm) {
			return;
		}

		$submission = WPCF7_Submission::get_instance();
		$uploaded_files = $submission ? $submission->uploaded_files() : [];

		if (!$submission) {
			return;
		}

		$posted_data = $submission->get_posted_data();

		if (empty($posted_data) || !is_array($posted_data)) {
			return;
		}

		$form_id = $contact_form->id();
		$table_name = $wpdb->prefix . 'wpssc_form_entry';

		// Generate next data_id per form
		$option_key = 'wpssc_form_entry_' . $form_id;

		// Initialize counter only if not exists
		if (false === get_option($option_key)) {
			update_option($option_key, 1);
		}

		// Get current counter
		$data_id = (int)get_option($option_key, 1);
		// Increment for next time
		update_option($option_key, $data_id + 1);

		foreach ($posted_data as $field_name => $value) {

			// Skip CF7 system fields
			if (0 === strpos($field_name, '_')) {
				continue;
			}

			// Handle file upload
			if (isset($uploaded_files[$field_name])) {

				$file = $uploaded_files[$field_name];

				// Handle multiple files
				if (is_array($file)) {

					$filenames = [];

					foreach ($file as $single_file) {

						if (is_string($single_file) && file_exists($single_file)) {
							$filenames[] = sanitize_file_name(basename($single_file));
						}

					}

					$value = !empty($filenames) ? implode(', ', $filenames) : '';

				}
				// Handle single file
				elseif (is_string($file) && file_exists($file)) {

					$value = sanitize_file_name(basename($file));

				}
				else {

					$value = '';

				}

			}
			else {

				// Handle arrays (checkbox)
				if (is_array($value)) {
					$value = implode(', ', array_map('sanitize_text_field', $value));
				}
				else {
					$value = sanitize_text_field($value);
				}
			}

			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- CF7 submission insert; write-only operation, caching not applicable.
			$wpdb->insert(
				$table_name,
			[
				'cf7_id' => $form_id,
				'data_id' => $data_id,
				'name' => sanitize_key($field_name),
				'value' => $value
			],
			['%d', '%d', '%s', '%s']
			);
		}

		// Save submit time
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Submit time insert; write-only operation, caching not applicable.
		$wpdb->insert(
			$table_name,
		[
			'cf7_id' => $form_id,
			'data_id' => $data_id,
			'name' => 'submit_time',
			'value' => current_time('mysql')
		],
		['%d', '%d', '%s', '%s']
		);
		// Save IP
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- IP address insert; write-only operation, caching not applicable.
		$wpdb->insert(
			$table_name,
		[
			'cf7_id' => $form_id,
			'data_id' => $data_id,
			'name' => 'submit_ip',
			'value' => isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : ''
		],
		['%d', '%d', '%s', '%s']
		);
		// Save User Agent
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- User-agent insert; write-only operation, caching not applicable.
		$wpdb->insert(
			$table_name,
		[
			'cf7_id' => $form_id,
			'data_id' => $data_id,
			'name' => 'user_agent',
			'value' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : ''

		],
		['%d', '%d', '%s', '%s']
		);
		// Save Page URL
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Page URL insert; write-only operation, caching not applicable.
		$wpdb->insert(
			$table_name,
		[
			'cf7_id' => $form_id,
			'data_id' => $data_id,
			'name' => 'page_url',
			'value' => isset($_SERVER['HTTP_REFERER']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_REFERER'])) : ''
		],
		['%d', '%d', '%s', '%s']
		);

		$submission_speed_ms = round((microtime(true) - $start_time) * 1000, 2);

		// Save _db_submission_speed_ms
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- DB speed metric insert; write-only operation, caching not applicable.
		$wpdb->insert(
			$table_name,
		[
			'cf7_id' => $form_id,
			'data_id' => $data_id,
			'name' => '_db_submission_speed_ms',
			'value' => $submission_speed_ms
		],
		['%d', '%d', '%s', '%s']
		);
	}

	/**
	 * Add new tab to contact form 7 editors panel.
	 *
	 * @since 1.0
	 *
	 * @param array $panels .
	 * @return array
	 */
	public function wpsslc_editor_panels($panels)
	{
		$panels['google-sheets'] = array(
			'title' => __('WPSyncSheets Lite Settings', 'contactsheets-lite'),
			'callback' => array($this, 'wpsslc_editor_panel_google_sheet'),
		);

		return $panels;
	}

	/**
	 * Set Google sheet settings with contact form
	 *
	 * @since 1.0
	 *
	 * @param object $post The post object to be processed.
	 */
	public function wpsslc_save_settings($post)
	{

		if (!isset($_POST['wpsslc_sheet_settings']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['wpsslc_sheet_settings'])), 'save_sheet_settings')) {
			return;
		}
		if (!isset($_POST['wpsslc_all_settings'])) {
			update_post_meta($post->id(), 'wpssc_all_settings', 'no');
			return;
		}
		else {
			update_post_meta($post->id(), 'wpssc_all_settings', sanitize_text_field(wp_unslash($_POST['wpsslc_all_settings'])));
		}
		$newsheet = '';

		if (isset($_POST['spreadsheetselection']) && 'new' === sanitize_text_field(wp_unslash($_POST['spreadsheetselection']))) {
			$newsheet = 'new';

			$_POST['wpsslc']['spreadsheetname'] = 'new'; // force spreadsheet to be treated as NEW .
		}

		if (!isset($_POST['wpsslc']['spreadsheetname']) || empty(sanitize_text_field(wp_unslash($_POST['wpsslc']['spreadsheetname'])))) {
			return;
		}
		$post_data = self::get_form_data($post->id());
		$form_fields = self::single_array($post_data);
		$wpsslc_cf_sheet = array();
		$active_header = array();

		$entry_id_in_current_headers = false;

		if (isset($_POST['header_shortcode_0'])) {
			$shortcode = sanitize_text_field(wp_unslash($_POST['header_shortcode_0']));
			if ('entry-id' === $shortcode) {
				$entry_id_in_current_headers = true;
			}
		}

		$db_enabled = isset($_POST['wpssc_enable_db_save'])
			? sanitize_text_field(wp_unslash($_POST['wpssc_enable_db_save']))
			: '';
		update_post_meta($post->id(), 'wpssc_enable_db_save', $db_enabled);

		if ('yes' === (string)$db_enabled || $entry_id_in_current_headers) {
			if (!in_array('entry-id', $form_fields, true)) {
				array_unshift($form_fields, 'entry-id');
			}
		}

		array_push($form_fields, 'IP-address');
		array_push($form_fields, 'page-URL');
		array_push($form_fields, 'submission-date');
		array_push($form_fields, 'submission-time');


		if ('new' === $newsheet) {

			$_POST['wpsslc']['spreadsheetname'] = isset($_POST['new_spreadsheetname']) ? sanitize_text_field(wp_unslash($_POST['new_spreadsheetname'])) : '';
			$_POST['wpsslc']['sheetname'] = isset($_POST['new_sheetname']) ? sanitize_text_field(wp_unslash($_POST['new_sheetname'])) : '';


			$requestbody = self::$wpsslc_instance_api->newspreadsheetobject(sanitize_text_field(wp_unslash($_POST['new_spreadsheetname'])), sanitize_text_field(wp_unslash($_POST['new_sheetname'])));

			$response = self::$wpsslc_instance_api->createspreadsheet($requestbody);
			$spreadsheetname = $response['spreadsheetId'];
			$_POST['wpsslc']['spreadsheetname'] = $response['spreadsheetId'];
			$_POST['new_sheetname'] = '';
		}

		$mapping = array();
		$spreadsheetname = isset($_POST['wpsslc']['spreadsheetname']) ? sanitize_text_field(wp_unslash($_POST['wpsslc']['spreadsheetname'])) : '';


		if (isset($_POST['new_sheetname']) && !empty($_POST['new_sheetname'])) {

			$param = array();
			$param['spreadsheetid'] = $spreadsheetname;
			$param['sheetname'] = sanitize_text_field(wp_unslash($_POST['new_sheetname']));
			$sheetname = $param['sheetname'];
			if (self::wpsslc_check_existing_sheet($param)) {
				$wpsslc_error_setting = 'A sheet with the name "' . $sheetname . '" already exists. Please enter another name.';

				$_POST['wpsslc']['sheetname'] = '';
				update_post_meta($post->id(), 'wpssc_cf_settings', array_map('sanitize_text_field', wp_unslash($_POST['wpsslc'])));
				update_post_meta($post->id(), 'wpssc_error_settings', $wpsslc_error_setting);
				return;
			}
			$_POST['wpsslc']['sheetname'] = sanitize_text_field(wp_unslash($_POST['new_sheetname']));
			$wpsslc_response = self::$wpsslc_instance_api->newsheetobject($param);
		}

		$sheetname = isset($_POST['wpsslc']['sheetname']) ? sanitize_text_field(wp_unslash($_POST['wpsslc']['sheetname'])) : '';
		$sheetarray = self::wpsslc_list_googlespreedsheet();

		if (isset($_POST['header_value_0'])) {

			$wpsslc_existingsheets = array();
			$response = self::$wpsslc_instance_api->get_sheet_listing($spreadsheetname);
			$wpsslc_existingsheets = self::$wpsslc_instance_api->get_sheet_list($response);
			$range = trim($sheetname) . '!A1';
			$wpsslc_sheetid = isset($wpsslc_existingsheets[$sheetname]) ? $wpsslc_existingsheets[$sheetname] : '';

			if (!empty($wpsslc_sheetid)) {
				$headers = array();
				$active_header = array();

				$previous_active_headers = self::$wpsslc_instance_api->wpsslc_option('wpssc_active_headers', '', $post->id());
				$wpsslc_neworder = array();
				$wpsslc_total_mapping_fields = isset($_POST['wpsslc_total_mapping_fields']) ? absint($_POST['wpsslc_total_mapping_fields']) : count($form_fields);
				$not_active_headers = array();
				$deleterequestarray = array();
				$requestarray = array();

				for ($i = 0; $i < $wpsslc_total_mapping_fields; $i++) {
					if (isset($_POST['header_value_' . $i])) {
						$header_shortcode = isset($_POST['header_shortcode_' . $i]) ? sanitize_text_field(wp_unslash($_POST['header_shortcode_' . $i])) : '';
						if ('IP Address' === $header_shortcode || 'Page URL' === $header_shortcode) {
							$header_shortcode = strtolower(str_replace(' ', '-', $header_shortcode));
						}

						if ('Submission Date' === $header_shortcode || 'Submission Time' === $header_shortcode) {
							$header_shortcode = strtolower(str_replace(' ', '-', $header_shortcode));
						}

						if (isset($_POST['active_header_value_' . $i])) {
							$wpsslc_neworder[] = $header_shortcode;
							$headers[] = sanitize_text_field(wp_unslash($_POST['header_value_' . $i]));
							$active_header[$header_shortcode] = 1;
						}
						else {
							$not_active_headers[$header_shortcode] = sanitize_text_field(wp_unslash($_POST['header_value_' . $i]));
							continue;
						}
						$mapping[$header_shortcode] = sanitize_text_field(wp_unslash($_POST['header_value_' . $i]));
					}
				}
				if (!empty($not_active_headers)) {
					$mapping = $mapping + $not_active_headers;
				}

				if (isset($previous_active_headers[0])) {
					$wpsslc_old_header_order = array_keys($previous_active_headers[0]);
				}
				else {
					$wpsslc_old_header_order = array();
				}

				$wpsslc_column = array_diff($wpsslc_old_header_order, $wpsslc_neworder);

				if (!empty($wpsslc_column)) {
					$wpsslc_column = array_reverse($wpsslc_column, true);
					foreach ($wpsslc_column as $columnindex => $columnval) {
						unset($wpsslc_old_header_order[$columnindex]);
						$wpsslc_old_header_order = array_values($wpsslc_old_header_order);
						if (array_key_exists($sheetname, $wpsslc_existingsheets)) {

							$param = array();
							$param['sheetid'] = $wpsslc_sheetid;
							$param['startindex'] = $columnindex;
							$param['endindex'] = $columnindex + 1;
							$deleterequestarray[] = self::$wpsslc_instance_api->deleteDimensionrequests($param);
						}
					}
				}
				try {
					if (!empty($deleterequestarray)) {
						$param = array();
						$param['spreadsheetid'] = $spreadsheetname;
						$param['requestarray'] = $deleterequestarray;

						$wpsslc_response = self::$wpsslc_instance_api->updatebachrequests($param);
					}
				}
				catch (Exception $e) {
					echo esc_html('Message: ' . $e->getMessage());
				}
				if ($wpsslc_old_header_order !== $wpsslc_neworder) {
					foreach ($wpsslc_neworder as $key => $hname) {
						$wpsslc_startindex = array_search($hname, $wpsslc_old_header_order, true);

						if (false !== $wpsslc_startindex && (isset($wpsslc_old_header_order[$key]) && $wpsslc_old_header_order[$key] !== $hname)) {
							unset($wpsslc_old_header_order[$wpsslc_startindex]);
							$wpsslc_old_header_order = array_merge(array_slice($wpsslc_old_header_order, 0, $key), array(0 => $hname), array_slice($wpsslc_old_header_order, $key, count($wpsslc_old_header_order) - $key));
							$wpsslc_endindex = $wpsslc_startindex + 1;
							$wpsslc_destindex = $key;

							if (array_key_exists($sheetname, $wpsslc_existingsheets)) {

								$param = array();
								$param['sheetid'] = $wpsslc_sheetid;
								$param['startindex'] = $wpsslc_startindex;
								$param['endindex'] = $wpsslc_endindex;
								$param['destindex'] = $wpsslc_destindex;

								$requestarray[] = self::$wpsslc_instance_api->moveDimensionrequests($param);
							}
						}
						elseif (false === $wpsslc_startindex) {

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

							if (array_key_exists($sheetname, $wpsslc_existingsheets)) {
								$param = array();
								$param['sheetid'] = $wpsslc_sheetid;
								$param['startindex'] = $key;
								$param['endindex'] = $key + 1;
								$requestarray[] = self::$wpsslc_instance_api->insertdimensionrequests($param);
							}
						}
					}

					if (!empty($requestarray)) {
						$param = array();
						$param['spreadsheetid'] = $spreadsheetname;
						$param['requestarray'] = $requestarray;
						$wpsslc_response = self::$wpsslc_instance_api->updatebachrequests($param);
					}
				}

				$range = trim($sheetname) . '!A1';
				$values = array($headers);
				$requestbody = self::$wpsslc_instance_api->valuerangeobject($values);
				$params = array(
					'valueInputOption' => 'RAW',
				);

				$param = self::$wpsslc_instance_api->setparamater($spreadsheetname, $range, $requestbody, $params);
				$response = self::$wpsslc_instance_api->updateentry($param);

			}
			update_post_meta($post->id(), 'wpssc_active_headers', $active_header);
		}

		update_post_meta($post->id(), 'wpssc_cf_settings', array_map('sanitize_text_field', wp_unslash($_POST['wpsslc'])));

		update_post_meta($post->id(), 'field_mapping_settings', $mapping);

		if (isset($_POST['freeze_header'])) {
			$freeze = 1;
		}
		else {
			$freeze = 0;
		}

		if (!empty($spreadsheetname) && !empty($sheetname)) {
			try {

				$response = self::$wpsslc_instance_api->get_sheet_listing($spreadsheetname);

				// If Google API failed
				if (empty($response) || !is_object($response) || !method_exists($response, 'getSheets')) {
					return;
				}

				$google_sheets = $response->getSheets();

				if (empty($google_sheets) || !is_array($google_sheets)) {
					return;
				}

				foreach ($google_sheets as $sheet_obj) {

					// Make sure we have a proper Google Sheet object
					if (!is_object($sheet_obj) || !method_exists($sheet_obj, 'getProperties')) {
						continue;
					}

					$properties = $sheet_obj->getProperties();

					if (!is_object($properties)) {
						continue;
					}

					$title = method_exists($properties, 'getTitle') ? (string)$properties->getTitle() : '';
					$sheet_id = method_exists($properties, 'getSheetId') ? $properties->getSheetId() : null;

					// Compare safely
					if ($title === (string)$sheetname && null !== $sheet_id) {

						$requestbody = self::$wpsslc_instance_api->freezeobject($sheet_id, $freeze);

						$requestobject = array(
							'spreadsheetid' => $spreadsheetname,
							'requestbody' => $requestbody,
						);

						// Prevent another fatal if Google fails again
						try {
							self::$wpsslc_instance_api->formatsheet($requestobject);
						}
						catch (Throwable $e) {
							if (defined('WP_DEBUG') && WP_DEBUG) {
								error_log('WPSyncSheets format error: ' . $e->getMessage()); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
							}
						}

					}
				}

			}
			catch (Throwable $e) {
				if (defined('WP_DEBUG') && WP_DEBUG) {
					// This prevents Contact Form 7 editor or submission from crashing
					error_log('WPSyncSheets fatal prevented: ' . $e->getMessage()); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
				}
			}
		}
		if (isset($_POST['freeze_header'])) {
			update_post_meta($post->id(), 'freeze_header', sanitize_text_field(wp_unslash($_POST['freeze_header'])));
		}
		else {
			update_post_meta($post->id(), 'freeze_header', '');
		}

	}
	public function wpssc_is_sheet_sync_active($form_id)
	{

		if ('no' === (string)get_post_meta($form_id, 'wpssc_all_settings', true)) {
			return;
		}

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

		$db_enabled = get_post_meta($form_id, 'wpssc_enable_db_save', true);

		$settings = self::$wpsslc_instance_api->wpsslc_option(
			'wpssc_cf_settings',
			'',
			$form_id
		);

		$sheet_enabled = (
			!empty($settings[0]['spreadsheetname']) &&
			!empty($settings[0]['sheetname'])
			);

		return ('yes' === $db_enabled && $sheet_enabled);
	}

	public function wpssc_delete_entries_from_sheet($form_id, $data_ids = array())
	{

		if (empty($data_ids)) {
			return;
		}
		$active_headers = get_post_meta($form_id, 'wpssc_active_headers');
		if (empty($active_headers) || !is_array($active_headers)) {
			$active_headers = array();
		}
		if (!isset($active_headers[0]) || !is_array($active_headers[0])) {
			$active_headers[0] = array();
		}
		if (!array_key_exists('entry-id', $active_headers[0])) {
			return;
		}

		$form_data = self::$wpsslc_instance_api->wpsslc_option('wpssc_cf_settings', '', $form_id);

		if (empty($form_data[0]['spreadsheetname']) || empty($form_data[0]['sheetname'])) {
			return;
		}

		$spreadsheet_id = $form_data[0]['spreadsheetname'];
		$sheet_name = $form_data[0]['sheetname'];

		// Get sheet listing to find sheet ID
		$response = self::$wpsslc_instance_api->get_sheet_listing($spreadsheet_id);
		$sheets = self::$wpsslc_instance_api->get_sheet_list($response);

		if (!isset($sheets[$sheet_name])) {
			return;
		}

		$sheet_id = $sheets[$sheet_name];

		// Get all rows
		$rows_data = self::$wpsslc_instance_api->get_row_list($spreadsheet_id, $sheet_name);
		$rows = $rows_data->getValues();

		if (empty($rows)) {
			return;
		}

		$delete_requests = array();
		$row_indexes = array();

		foreach ($rows as $index => $row) {

			// Skip header row
			if (0 === $index) {
				continue;
			}

			// Assuming Entry ID is first column
			if (isset($row[0]) && in_array((int)$row[0], $data_ids, true)) {
				$row_indexes[] = $index;
			}
		}

		if (empty($row_indexes)) {
			return;
		}

		// VERY IMPORTANT: delete from bottom to top
		rsort($row_indexes);

		foreach ($row_indexes as $row_index) {

			$param = array(
				'sheetid' => $sheet_id,
				'startindex' => $row_index,
				'endindex' => $row_index + 1,
			);

			$delete_requests[] = self::$wpsslc_instance_api->deleteDimensionrequests($param, 'ROWS');
		}


		if (!empty($delete_requests)) {

			$batch_param = array(
				'spreadsheetid' => $spreadsheet_id,
				'requestarray' => $delete_requests,
			);
			self::$wpsslc_instance_api->updatebachrequests($batch_param);
		}
	}
	/**
	 * Function - Run before sending mail.
	 *
	 * @since 1.0
	 */
	public function wpsslc_wpcf7_before_send_mail()
	{
		self::$wpsslc_instance_api->getClient();
	}
	/**
	 * Function - To send contact form data to google spreadsheet.
	 *
	 * @param object $form .
	 * @since 1.0
	 */
	public function wpsslc_save_to_google_spreadsheets($form)
	{

		// Start timer immediately
		$start_time = microtime(true);

		// get form data.
		$form_id = $form->id();

		$update_and_return = false;

		global $wpdb;

		$db_enabled = get_post_meta($form_id, 'wpssc_enable_db_save', true);
		$current_id = '';

		if ('yes' === $db_enabled) {

			$option_key = 'wpssc_form_entry_' . $form_id;

			// Get current sequential number (default 1)
			$current_id = (int)get_option($option_key, 1);

			// Use this as entry id
			if ($current_id > 1) {
				$current_id--;
			}
		}

		if ('no' === (string)get_post_meta($form_id, 'wpssc_all_settings', true)) {
			$update_and_return = true;
		}

		if (!$update_and_return && !self::$wpsslc_instance_api->checkcredenatials()) {
			$update_and_return = true;
		}
		if (!$update_and_return && !self::$wpsslc_instance_api->getClient()) {
			$update_and_return = true;
		}
		if ($update_and_return) {
			if ('yes' === $db_enabled && !empty($current_id)) {
				$this->wpssc_update_submission_status($form_id, $current_id, $start_time, 'skipped');
			}
			return;
		}
		try {
			$submission = WPCF7_Submission::get_instance();

			$form_data = self::$wpsslc_instance_api->wpsslc_option('wpssc_cf_settings', '', $form_id);
			$mapping_data = get_post_meta($form_id, 'field_mapping_settings');
			$active_headers = self::$wpsslc_instance_api->wpsslc_option('wpssc_active_headers', '', $form_id);
			if (empty($mapping_data) || !is_array($mapping_data)) {
				$mapping_data = array();
			}
			if (empty($active_headers) || !is_array($active_headers)) {
				$active_headers = array();
			}
			if (!isset($active_headers[0]) || !is_array($active_headers[0])) {
				$active_headers[0] = array();
			}
			$data = array();

			$sheetarray = self::wpsslc_list_googlespreedsheet();
			if (isset($form_data[0]['spreadsheetname']) && !empty($form_data[0]['spreadsheetname']) && !array_key_exists($form_data[0]['spreadsheetname'], $sheetarray)) {
				$form_data[0]['spreadsheetname'] = '';
				$form_data[0]['sheetname'] = '';
			}
			elseif (isset($form_data[0]['spreadsheetname']) && !empty($form_data[0]['spreadsheetname'])) {
				$sheetname = self::sheet_for_form_setting($form_data);
				if (isset($form_data[0]['sheetname']) && !empty($form_data[0]['sheetname']) && !in_array($form_data[0]['sheetname'], $sheetname, true)) {
					$form_data[0]['spreadsheetname'] = '';
					$form_data[0]['sheetname'] = '';
				}
			}
			// if contact form sheet name and tab name is not empty than send data to spreedsheet.
			if ($submission && (!empty($form_data[0]['spreadsheetname'])) && (!empty($form_data[0]['sheetname'])) && !empty(array_filter($mapping_data))) {
				$posted_data = $submission->get_posted_data();
				$file_data = $submission->uploaded_files();
				$field_data = self::get_form_data($form_id);

				if (!function_exists('wp_handle_upload')) {
					require_once ABSPATH . 'wp-admin/includes/file.php';
				}
				global $wpsslc_input_quiz_array;
				$wpsslc_input_quiz_array = array();
				array_walk_recursive(
					$field_data,
					function ($value, $key) {
					global $wpsslc_input_quiz_array;
					if ('quiz' === (string)$key) {
						$wpsslc_input_quiz_array[] = $value;
					}
				}
				);

				foreach ($mapping_data[0] as $key => $val) {
					if ($active_headers) {
						if (!array_key_exists($key, $active_headers[0])) {
							continue;
						}
					}
					if ('entry-id' === (string)$key) {
						if ('yes' === $db_enabled) {
							$data[] = $current_id;
						}
						else {
							$data[] = '';
						}
						continue;
					}
					if ('IP-address' === (string)$key) {

						if (isset($_SERVER['HTTP_CLIENT_IP']) && !empty(sanitize_text_field(wp_unslash($_SERVER['HTTP_CLIENT_IP'])))) {
							$data[] = sanitize_text_field(wp_unslash($_SERVER['HTTP_CLIENT_IP']));
						}
						elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty(sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR'])))) {
							$data[] = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']));
						}
						else {
							$data[] = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '';
						}
						continue;
					}
					if ('page-URL' === (string)$key) {
						$data[] = isset($_SERVER['HTTP_REFERER']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_REFERER'])) : '';
						continue;
					}

					if ('submission-date' === (string)$key) {
						$data[] = date_i18n(get_option('date_format'));
						continue;
					}
					if ('submission-time' === (string)$key) {
						$data[] = date_i18n(get_option('time_format'));
						continue;
					}

					if (in_array($key, $wpsslc_input_quiz_array, true)) {
						// @codingStandardsIgnoreStart.
						if (isset($_POST[$key])) {
							$data[] = sanitize_text_field(wp_unslash($_POST[$key]));
						// @codingStandardsIgnoreEnd.
						}
						else {
							$data[] = '';
						}
						continue;
					}

					if (!isset($posted_data[$key])) {
						$data[] = '';
						continue;
					}

					if (is_array($posted_data[$key])) {
						$data[] .= implode(',', $posted_data[$key]);
					}
					else {
						$field_type = self::search_forkey($key, $field_data);
						if ('file' === (string)$field_type) {
							if (!empty($file_data[$key])) {
								$data[] = basename($file_data[$key][0]);
							}
							else {
								$data[] = '';
							}
							continue;
						}
						if ('acceptance' === (string)$field_type) {
							if (1 === (int)$posted_data[$key]) {
								$data[] = 'Yes';
							}
							else {
								$data[] = 'No';
							}
							continue;
						}
						$data[] = $posted_data[$key];
					}
				}


				$values = array($data);
				$requestbody = self::$wpsslc_instance_api->valuerangeobject($values);
				$params = array(
					'valueInputOption' => 'USER_ENTERED',
				);
				$param = self::$wpsslc_instance_api->setparamater($form_data[0]['spreadsheetname'], $form_data[0]['sheetname'], $requestbody, $params);

				$response = self::$wpsslc_instance_api->appendentry($param);

				if ('yes' === $db_enabled && !empty($current_id)) {

					$success = (!empty($response) && !is_wp_error($response));

					if ($success) {
						$this->wpssc_update_submission_status($form_id, $current_id, $start_time, 'success');
					}
					else {
						$this->wpssc_update_submission_status($form_id, $current_id, $start_time, 'failed');
					}

				}

			}
			else {
				if ('yes' === $db_enabled && !empty($current_id)) {
					$this->wpssc_update_submission_status($form_id, $current_id, $start_time, 'skipped');
				}
			}
		}
		catch (Exception $e) {
			if ('yes' === $db_enabled && !empty($current_id)) {
				$this->wpssc_update_submission_status($form_id, $current_id, $start_time, 'failed');
			}
		}
	}
	public function wpssc_update_submission_status($form_id, $data_id, $start_time, $status)
	{

		if (empty($data_id)) {
			return;
		}

		global $wpdb;

		$table_name = $wpdb->prefix . 'wpssc_form_entry';

		// Calculate time in ms
		$submission_speed_ms = round((microtime(true) - $start_time) * 1000, 2);

		// Save status
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Google Sheet status insert; write-only operation, caching not applicable.
		$wpdb->insert(
			$table_name,
			array(
			'cf7_id' => $form_id,
			'data_id' => $data_id,
			'name' => '_is_status',
			'value' => $status
		),
			array('%d', '%d', '%s', '%s')
		);

		// Save Google submission speed
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Google speed metric insert; write-only operation, caching not applicable.
		$wpdb->insert(
			$table_name,
			array(
			'cf7_id' => $form_id,
			'data_id' => $data_id,
			'name' => '_google_submission_speed_ms',
			'value' => $submission_speed_ms
		),
			array('%d', '%d', '%s', '%s')
		);
	}

	/**
	 * Google sheet settings page
	 *
	 * @since 1.0
	 */

	public function wpsslc_editor_panel_google_sheet($post)
	{
?>
		<div id="informationdivwpsslc" class="postbox wpsslc-upgrade-pro-informationdiv">
			<div class="inside">
				<img src="<?php echo esc_url(plugin_dir_url(__FILE__) . '../assets/images/logo.svg'); ?>">
				<ul>
					<li><?php echo esc_html(__('Edit Sheet Headers', 'contactsheets-lite')); ?></li>
					<li><?php echo esc_html(__('Sorting Sheet Headers', 'contactsheets-lite')); ?></li>
					<li><?php echo esc_html(__('User Agent & Submission Time Sheet Headers', 'contactsheets-lite')); ?></li>
					<li><?php echo esc_html(__('Special Mail Tags Options', 'contactsheets-lite')); ?></li>
					<li><?php echo esc_html(__('6+ Third Party Plugins Compatibility', 'contactsheets-lite')); ?></li>
				</ul>
				<a class="button button-primary" target="_blank" href="<?php echo esc_url(WPSSLC_PRO_VERSION_URL); ?>">
					<span class="dashicons dashicons-admin-links"></span>
					<?php echo esc_html(__('Upgrade To Pro', 'contactsheets-lite')); ?>
				</a>
			</div>
		</div>
		<?php
		if (!current_user_can('edit_wpsyncsheets_contact_form_7_lite_form_settings')) {
			echo '<p>' . esc_html__('You do not have permission to access this page.', 'contactsheets-lite') . '</p>';
		}
		else {
			// @codingStandardsIgnoreStart.
			if (isset($_GET['post'])) {

				$form_id = sanitize_text_field(wp_unslash($_GET['post']));
				// @codingStandardsIgnoreEnd.
				$form_data = self::$wpsslc_instance_api->wpsslc_option('wpssc_cf_settings', '', $form_id);
				if (empty($form_data) || !is_array($form_data)) {
					$form_data = array();
				}
				$wpsslc_google_settings_value = self::$wpsslc_instance_api->wpsslc_option('wpssc_google_settings');

				$wpsslc_error = '';

				if (isset($wpsslc_google_settings_value[2]) && !empty($wpsslc_google_settings_value[2])) {
					if (!self::$wpsslc_instance_api->getClient()) {
						$wpsslc_error = self::$wpsslc_instance_api->getClient(1);
						if ('Invalid token format' === (string)$wpsslc_error) {

							$wpsslc_error = '<strong class="err-msg">' . esc_html__('Error: Invalid Token - ', 'contactsheets-lite') . '<a href="' . esc_url(admin_url('admin.php?page=wpsyncsheets-for-contact-form-7')) . '">' . esc_html__('Click here</a> to check more information.', 'contactsheets-lite') . '';

						}
						else {

							$wpsslc_error = '<strong class="err-msg">Error: ' . $wpsslc_error . '</strong>';

						}
					}
				}
				else {
					echo '<div class="gs-fields wpssc-gs-fields vertical-tabs">
					<div class="generalSetting-section">
						<p class="wpssc-save-settings-message">';
					echo '<strong class="err-msg">' . esc_html__('Please genearate authentication code from', 'contactsheets-lite') . '</strong>'; ?> <?php echo esc_html__('Google API Settings', 'contactsheets-lite'); ?><strong>
						<a href='<?php echo esc_url('admin.php?page=wpsyncsheets-for-contact-form-7'); ?>'> <?php echo esc_html__('Click here', 'contactsheets-lite'); ?></a></strong>
					<?php
					echo '</p>
						</div>
					</div>';
					return;
				}
				if (!empty($wpsslc_error)) {
					$allowed_html = wp_kses_allowed_html('post');
					echo wp_kses($wpsslc_error, $allowed_html);
					return;
				}

				$sheetarray = self::wpsslc_list_googlespreedsheet();
				$wpsslc_spreadsheetname = '';
				$wpsslc_sheetname = '';
				if (isset($form_data[0]) && isset($form_data[0]['spreadsheetname'])) {
					$wpsslc_spreadsheetname = $form_data[0]['spreadsheetname'];
				}
				if (isset($form_data[0]) && isset($form_data[0]['sheetname'])) {
					$wpsslc_sheetname = $form_data[0]['sheetname'];
				}
				if (!empty($wpsslc_spreadsheetname) && !array_key_exists($wpsslc_spreadsheetname, $sheetarray)) {
					$wpsslc_spreadsheetname = '';
					$wpsslc_sheetname = '';
				}
				$sheetname_array = array();
				if ('new' !== (string)$wpsslc_spreadsheetname && '' !== (string)$wpsslc_spreadsheetname) {
					$sheetname_array = self::sheet_for_form_setting($form_data);
				}
				if (isset($sheetname_array)) {
					if (in_array($wpsslc_sheetname, $sheetname_array, true)) {
						$checkheaders = self::wpsslc_check_spreadsheet_header_value($form_id);
					}
					else {
						$wpsslc_sheetname = '';
					}
				}

				$db_enabled = get_post_meta($form_id, 'wpssc_enable_db_save', true);
?>
				<form method="post" id="googlesetting">
					<?php wp_nonce_field('save_sheet_settings', 'wpsslc_sheet_settings');
				$wpsslc_error_setting = get_post_meta($form_id, 'wpssc_error_settings', true);
				if ($wpsslc_error_setting) {
					update_post_meta($post->id(), 'wpssc_error_settings', '');
				}
?>
					<div class="gs-fields wpsslc-gs-fields vertical-tabs">

						<div class="wpsslc_all_settings">
							<div class="generalSetting-left">
								<div class="contactforms-panel-field">
									<label><?php echo esc_html(__('WPSyncSheets Settings', 'contactsheets-lite')); ?></label>
								</div>
								<p><?php echo esc_html__('Enable this option to automatically create customized spreadsheets and sheets for efficient entry management & seamless functionality.', 'contactsheets-lite'); ?></p>
							</div>
							<div class="generalSetting-right">
							<label>
								<input type="checkbox" name="wpsslc_all_settings" id="wpsslc_all_settings" value="yes" 
								<?php
				$wpsslc_all_settings = get_post_meta($form_id, 'wpssc_all_settings', true);
				if ('yes' === (string)$wpsslc_all_settings && !empty($form_data)) {
					echo 'checked=checked';
				}
?>
								><span class="checkbox-switch"></span>  							
							</label>
						    </div>
						</div>

						<div class="all_settings_div">
								<div class="generalSetting-section googleSpreadsheet-section entry_spreadsheet_row">
									<div class="generalSetting-left">
										<div class="google-settings-panel">
											<h4><?php echo esc_html__('Google Spreadsheet Settings', 'contactsheets-lite'); ?></h4>
											<p><?php echo esc_html__('Upon assigning a Google Spreadsheet, it will automatically generate the sheet, populated with specified sheet headers. Additionally, whenever form is submitted, WPSyncSheets add new rows dynamically to keep everything up to date.', 'contactsheets-lite'); ?></p>
											
											<div class="createanew-radio">
												<div class="createanew-radio-box">
													<input type="radio" name="spreadsheetselection" value="new" id="createanew" 
													<?php
				if (empty($wpsslc_spreadsheetname)) {
					echo 'checked';
				}
?> >
													<label for="createanew">Create New Spreadsheet</label>
												</div>
												<div class="createanew-radio-box">
													<input type="radio" name="spreadsheetselection" value="existing" id="existing"
													<?php
				if (!empty($wpsslc_spreadsheetname)) {
					echo 'checked';
				}
?>
													>
													<label for="existing">Select Existing Spreadsheet</label>
												</div>
											</div>
											<div id="wpsslcform_spreadsheet_container" class="spreadsheet-form">
												<select name="wpsslc[spreadsheetname]" id="spreadsheetid"  style="min-width:150px;" class="">
													<?php
				if (!empty($sheetarray)) {
					foreach ($sheetarray as $key => $val) {
						if (isset($wpsslc_spreadsheetname) && $wpsslc_spreadsheetname === $key) {
?>
																<option value="<?php echo esc_attr($key); ?>" selected><?php echo esc_html($val); ?></option>
																<?php
						}
						else {
?>
																<option value="<?php echo esc_attr($key); ?>"><?php echo esc_html($val); ?></option>
																<?php
						}
					}
				}
?>
												</select>

												<?php if (!empty($wpsslc_spreadsheetname) && 'new' !== $wpsslc_spreadsheetname) { ?>
													<span class="sheet-btns"> 
														<a id="view_spreadsheet" target="_blank" href="<?php echo esc_url('https://docs.google.com/spreadsheets/d/' . $wpsslc_spreadsheetname); ?>" class="wpss-button wpss-tooltio-link view_spreadsheet">
															<span class="view-icon"></span>
															<span class="tooltip-text">View Spreadsheet</span>
														</a>
														
														<a id="clear_spreadsheet" data-form-id="<?php echo esc_attr($form_id); ?>" href="javascript:void(0)" class="wpss-button wpss-tooltio-link wpsyncsheets-contactforms-clear-button" data-form-id="47359">
															<span class="clear-icon"></span>
															<span class="tooltip-text">Clear Spreadsheet</span> 
														</a><img src="<?php dirname(__FILE__); ?>images/spinner.gif" id="clearloader">

														<a id="down_spreadsheet" target="_blank" href="<?php echo esc_url('https://docs.google.com/spreadsheets/d/' . $wpsslc_spreadsheetname . '/export'); ?>" class="wpss-button wpss-tooltio-link down_spreadsheet">
															<span class="download-icon"></span>
															<span class="tooltip-text">Download Spreadsheet</span>
														</a> 
													</span>
												<?php
				}?>
											</div>
											<p class="custom-sheet">
												<input type="hidden" id="prev_selected_sheet" value="<?php echo esc_html($wpsslc_spreadsheetname); ?>" />
												<select name="wpsslc[sheetname]" id="sheetname" >
													<option value=""><?php echo esc_html__('Select Sheet', 'contactsheets-lite'); ?></option>
													<?php
				if (!empty($sheetname_array)) {
					foreach ($sheetname_array as $key => $val) {
						if ($wpsslc_sheetname === $val) {
?>
																<option value="<?php echo esc_attr($val); ?>" selected><?php echo esc_html($val); ?></option>
																<?php
						}
						else {
?>
																<option value="<?php echo esc_attr($val); ?>"><?php echo esc_html($val); ?></option>
																<?php
						}
					}
				}
?>
													<option value="new"><?php echo esc_html__('Create New Sheet', 'contactsheets-lite'); ?></option>
												</select>
											</p>
											<div valign="top" id="wpsslcform_newsheet" class="newsheetinput spreadsheet-form wpsslcform_spreadsheet_inputrow custom-new-sheet-div">
												<p class="custom-new-sheet">
													<input type="text" name="new_spreadsheetname" id="new_spreadsheetname" placeholder="<?php echo esc_html__('Enter Spreadsheet Name', 'contactsheets-lite'); ?>" class="input-text">
												</p>
												<p class=" new_sheetname">
													<input type="text" name="new_sheetname" id="new_sheetname" placeholder="<?php echo esc_html__('Enter Sheet name', 'contactsheets-lite'); ?>" class="input-text">
												</p>	
											</div>
										</div>
										<p class="wpsslc_error_setting"><?php echo esc_html($wpsslc_error_setting); ?></p>
									</div>
								</div>
								<div class="generalSetting-section sheetHeaders-section wpss_spreadsheet_row wpsslcform_spreadsheet_row">
									<div class="td-wpsslc-headers">
										<div class="wpsslc_headers">
											<div class="generalSetting-sheet-headers-row">
												<div class="generalSetting-left">
													<h4><?php echo esc_html__('Sheet Headers', 'contactsheets-lite'); ?></h4>
													<p><?php echo esc_html__('Any disabled sheet headers will be automatically removed from the current spreadsheet. Re-enable the desired headers, save the settings, and your spreadsheet will be updated with the latest headers.', 'contactsheets-lite'); ?></p>
												</div>
											</div>
											<div class="selectall-btnset">
												<button type="button" class="wpsslc-button wpsslc-button-primary" id="selectall"><?php echo esc_html__('Select All', 'contactsheets-lite'); ?></button>                
												<button type="button" class="wpsslc-button wpsslc-button-secondary" id="selectnone"><?php echo esc_html__('Select None', 'contactsheets-lite'); ?></button>
											</div>

												<?php
				// phpcs:ignore 
				$post_data = isset($_GET['post']) ?self::get_form_data($_GET['post']) : array();
				$form_fields = self::single_array($post_data);
				$mapping_fields = get_post_meta($form_id, 'field_mapping_settings', true);
				$active_headers = get_post_meta($form_id, 'wpssc_active_headers');
				$freeze = get_post_meta($form_id, 'freeze_header', true);
				$new_headers = array();

				if (empty($active_headers) || !is_array($active_headers)) {
					$active_headers = array();
				}
				if (!isset($active_headers[0]) || !is_array($active_headers[0])) {
					$active_headers[0] = array();
				}
				if (empty($mapping_fields) || !is_array($mapping_fields)) {
					$mapping_fields = array();
				}
				if ('yes' === (string)$db_enabled || empty($mapping_fields)) {
					array_unshift($form_fields, 'entry-id');
					if (!array_key_exists('entry-id', $active_headers[0])) {
						$active_headers[0]['entry-id'] = '1';
					}
					if (!array_key_exists('entry-id', $mapping_fields)) {
						$mapping_fields = array('entry-id' => 'Entry ID') + $mapping_fields;
					}
				}
				else {
					if (array_key_exists('entry-id', $active_headers[0])) {
						array_unshift($form_fields, 'entry-id');
					}
				}


				if (!empty($mapping_fields)) {
					foreach ($mapping_fields as $key => $value) {
						if (in_array($key, array('entry-id', 'IP-address', 'page-URL', 'submission-date', 'submission-time'), true)) {
							continue;
						}
						if (!in_array($key, $form_fields, true)) {
							if (isset($active_headers[0]) && array_key_exists($key, $active_headers[0])) {
								continue;
							}
							unset($mapping_fields[$key]);
							continue;
						}
						if (isset($active_headers[0]) && false === array_key_exists($key, $active_headers[0])) {
							$field_name = ucwords(preg_replace('/[^A-Za-z0-9\-]/', ' ', $key));
							$field_name = ucwords(str_replace('-', ' ', $field_name));
							$mapping_fields[$key] = $field_name;
						}
					}
				}

				array_push($form_fields, 'IP-address');
				array_push($form_fields, 'page-URL');
				array_push($form_fields, 'submission-date');
				array_push($form_fields, 'submission-time');

				$class = array_key_exists('entry-id', $active_headers[0])
					? 'wpssc-ui-entryid-sortable'
					: 'wpssc-ui-no-entryid-sortable';

				if (!empty($mapping_fields)) {

					$saved_fields = array_keys($mapping_fields);

					$newaddedfield = array_values(array_diff($form_fields, $saved_fields));
					$newaddedfield_count = count($newaddedfield);

					for ($i = 0; $i < $newaddedfield_count; $i++) {
						$field = ucwords(preg_replace('/[^A-Za-z0-9\-]/', ' ', $newaddedfield[$i]));
						$field = ucwords(str_replace('-', ' ', $field));
						$mapping_fields[$newaddedfield[$i]] = $field;
					}

					$j = 0;

					$total_mapping_fields = count($mapping_fields);
					echo '<input type="hidden" name=wpsslc_total_mapping_fields value="' . esc_html($total_mapping_fields) . '">';
					echo '<ul class="sheet-headers ui-sortable wpsslc-ui-sortable ' . esc_html($class) . '" id="sortable">';


					foreach ($mapping_fields as $shorcode => $header_title) {

						$is_active = '';
						if ($active_headers) {
							if (array_key_exists($shorcode, $active_headers[0])) {
								$is_active = 'checked';
							}
						}
						else {
							$is_active = 'checked';
						}
?>
													<li class="default-form-sheet ui-state-default ui-sortable-handle">				
														<label for="c_<?php echo esc_attr($j); ?>">
															<span class="orderSheet-left">
																<span class="contacttextfield">
																	<?php echo esc_html($header_title); ?>
																</span>
																<?php if ('entry-id' !== $shorcode) { ?>						
																<span class="ui-icon ui-icon-pencil wpss-tooltio-link disabled-pro-version">
																	<span class="pencil-icon">
																		<span class="edit-pencil-icon"></span>
																	</span>
																	<span class="tooltip-text edit-tooltip">Upgrade To Pro</span>
																</span>
																<?php
						}?>
															</span>
															<span class="orderSheet-right">
																<input type="checkbox" class="<?php if ('entry-id' !== $shorcode) {
							echo 'wpsslc_active';
						}?>" id="c_<?php echo esc_attr($j); ?>" name="active_header_value_<?php echo esc_attr($j); ?>" value="1" <?php echo esc_attr($is_active); ?> >
																<?php if ('entry-id' !== $shorcode) { ?>
																<span class="checkbox-switch-new"></span>
																
																<span class="ui-icon ui-icon-caret-2-n-s wpss-tooltio-link disabled-pro-version">
																	<span class="drag-drop-icon"></span>
																	<span class="tooltip-text">Upgrade To Pro</span>
																</span>
																<?php
						}?>
																<input type="hidden" class="header_shortcode" name="header_shortcode_<?php echo esc_attr($j); ?>" value="<?php echo esc_attr($shorcode); ?>"/>
																<input type="hidden" class="header_value" name="header_value_<?php echo esc_attr($j); ?>" value="<?php echo esc_attr($header_title); ?>"/>
															</span>
														</label>
														<span class="fieldsmap">
															<?php
						echo esc_html__('Map Field : ', 'contactsheets-lite') . esc_html($shorcode);
?>
														</span>
													</li>
												<?php $j++;
					}?> 
												</ul>
												<?php
				}
				else { ?>
												<ul class="sheet-headers ui-sortable wpsslc-ui-sortable <?php echo esc_html($class); ?>" id="sortable">
													<?php
					$is_active = 'checked';
					$form_fields_count = count($form_fields);
					for ($i = 0; $i < $form_fields_count; $i++) {
						$field = ucwords(preg_replace('/[^A-Za-z0-9\-]/', ' ', $form_fields[$i]));
						$field = ucwords(str_replace('-', ' ', $field));
?>
													<li class="default-form-sheet ui-state-default ui-sortable-handle">
														<label for="c_<?php echo esc_attr($i); ?>">
															<span class="orderSheet-left">
																<span class="contacttextfield"><?php echo esc_html($field); ?></span>
															
																<span class="pencil-icon">
																	<span class="edit-pencil-icon"></span>
																</span>
															</span>
															<span class="orderSheet-right">
																<input type="checkbox" class="wpsslc_active" id="c_<?php echo esc_attr($i); ?>" name="active_header_value_<?php echo esc_attr($i); ?>" value="1" <?php echo esc_attr($is_active); ?> >
																<span class="checkbox-switch-new"></span>
																<span class="ui-icon ui-icon-caret-2-n-s wpss-tooltio-link disabled-pro-version">
																	<span class="drag-drop-icon"></span>
																	<span class="tooltip-text">Upgrade To Pro</span>
																</span>
																<input type="hidden" class="header_shortcode" name="header_shortcode_<?php echo esc_attr($i); ?>" value="<?php echo esc_attr($form_fields[$i]); ?>"/>
																<input type="hidden" class="header_value" name="header_value_<?php echo esc_attr($i); ?>" value="<?php echo esc_attr($field); ?>"/>
																	
															</span>
														</label>
														<span class="fieldsmap">
															<?php
						echo esc_html__('Map Field : ', 'contactsheets-lite') . esc_html($form_fields[$i]);
?>
														</span>
													</li>
													<?php
					}?>
												</ul>
													<?php
				}
?>
										</div>
									</div>
								</div>
								<div class="generalSetting-section">
									<div class="generalSetting-left">
										<h4><?php echo esc_html__('Save to DB', 'contactsheets-lite'); ?></h4>
										<p><?php echo esc_html__('Enable this option to store form entries in the database. Once enabled, each submission will be saved securely and can be synchronized or accessed later as needed.', 'contactsheets-lite'); ?></p>
									</div>
									<div class="generalSetting-right">
										<label for="wpssc_enable_db_save">
											<input name="wpssc_enable_db_save" id="wpssc_enable_db_save" type="checkbox" class="" value="yes" 
											<?php
				if ('yes' === (string)$db_enabled) {
					echo 'checked=checked';
				}
?>
											><span class="checkbox-switch"></span>
										</label>
									</div>
								</div>
											
								<div class="generalSetting-section-freeze-header-row freeze_header">
									<div class="generalSetting-left">
										<div class="contactforms-panel-field">
											<label><?php echo esc_html__('Freeze Header', 'contactsheets-lite'); ?></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.', 'contactsheets-lite'); ?></p>
									</div>
									<div class="generalSetting-right">
										<label>
											<input type="checkbox" name="freeze_header" value="yes" 
											<?php
				if (isset($freeze) && 'yes' === (string)$freeze) {
					echo 'checked=checked';
				}
?>
											><span class="checkbox-switch"></span>  							
										</label>
									</div>
								</div>

								<div class="generalSetting-section generalSetting-section-row-input-option row-input-option">
									<div class="generalSetting-left">
										<div class="contactforms-panel-field">
											<label><?php echo esc_html__('Row Input Format Option', 'contactsheets-lite'); ?><span class="wpss-tooltio-link tooltip-right">
													<span class="tooltip-text"><a target="_blank" href="<?php echo esc_url(WPSSLC_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, ', 'contactsheets-lite'); ?><a href="https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption" target="_blank">click here.</a></p>
									</div>
								</div>
						</div>
					</div>
				</form>
				<?php
			}
			else {
				echo '<div class="gs-fields wpsslc-gs-fields vertical-tabs">
					<div class="generalSetting-section">
						<p class="wpsslc-save-settings-message">';
				echo esc_html__('Please save your newly created form for WPSyncSheets Lite For Contact Form 7 settings.', 'contactsheets-lite');
				echo '</p>
					</div>
				</div>';
			}
		}
	}



	/**
	 * Prepare Google Spreadsheet list
	 *
	 * @access public
	 * @return array $sheetarray
	 */
	public static function wpsslc_list_googlespreedsheet()
	{
		$sheetarray = array(
			'' => __('Select Google Spreeadsheet List', 'contactsheets-lite'),
		);
		$sheetarray = self::$wpsslc_instance_api->get_spreadsheet_listing($sheetarray);
		return $sheetarray;
	}

	/**
	 * Prepare Google Spreedsheet sheet name for feed setting.
	 *
	 * @access public
	 * @param array $data selected spreadsheet data .
	 * @return array $choices
	 */
	public function sheet_for_form_setting($data)
	{

		/* Build choices array. */
		$choices = 'Select a Sheet List';
		/* Get feed settings. */
		$settings = isset($data[0]['spreadsheetname']) ? $data[0]['spreadsheetname'] : '';
		if ('' === $data[0]['spreadsheetname'] || 'new' === $data[0]['spreadsheetname']) {
			return $choices;
		}
		$sheets = array();

		try {
			$response = self::$wpsslc_instance_api->get_sheet_listing($data[0]['spreadsheetname']);
			// If Google failed or returned nothing
			if (empty($response) || !is_object($response)) {
				return array();
			}
			// If object exists but method not available
			if (!method_exists($response, 'getSheets')) {
				return array();
			}
			$google_sheets = $response->getSheets();
			if (empty($google_sheets) || !is_array($google_sheets)) {
				return array();
			}
			foreach ($google_sheets as $s) {
				// Google returns objects, not arrays
				if (is_object($s) && method_exists($s, 'getProperties')) {
					$properties = $s->getProperties();
					if (is_object($properties) && method_exists($properties, 'getTitle')) {
						$sheets[] = $properties->getTitle();
					}
				}
			}
		}
		catch (Throwable $e) {
			if (defined('WP_DEBUG') && WP_DEBUG) {
				// Prevent WordPress admin crash
				error_log('WPSyncSheets Google API error: ' . $e->getMessage()); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
			}
			return array();
		}
		return $sheets;
	}

	/**
	 * Get form data.
	 *
	 * @access public
	 * @param object $form .
	 * @return array $assoc_arr
	 */
	public function get_form_data($form)
	{
		$assoc_arr = array();
		$meta = get_post_meta($form, '_form', true);

		$fields = self::get_fields($meta);
		foreach ($fields as $field) {

			$single = self::get_field_assoc($field);
			if ($single) {
				$assoc_arr[] = $single;
			}
		}
		return $assoc_arr;
	}

	/**
	 * Get form fields.
	 *
	 * @access public
	 * @param string $meta .
	 * @return array $arr
	 */
	public function get_fields($meta)
	{
		$regexp = '/\[.*\]/';
		$arr = array();

		if (false === preg_match_all($regexp, $meta, $arr)) {
			return false;
		}
		return $arr[0];
	}

	/**
	 * Get associative form fields.
	 *
	 * @access public
	 * @param string $content .
	 * @return array
	 */
	public function get_field_assoc($content)
	{
		$regexp_type = '/(?<=\[)[^\s\*]*/';
		$regexp_name = '/(?<=\s)[^\s\]]*/';

		$arr_type = array();
		$arr_name = array();
		if (false === preg_match($regexp_type, $content, $arr_type)) {
			return false;
		}
		if (!in_array($arr_type[0], $this->allowed_tags, true)) {
			return false;
		}
		if (false === preg_match($regexp_name, $content, $arr_name)) {
			return false;
		}

		return array($arr_type[0] => $arr_name[0]);
	}

	/**
	 * Serch for key in given array using given value
	 *
	 * @access public
	 * @param string $value is to search in arrray.
	 * @param array  $array_val .
	 * @return string $key or null
	 */
	public function search_forkey($value, $array_val)
	{
		foreach ($array_val as $key => $val) {
			$key = array_search($value, $val, true);
			if ($key) {
				return $key;
			}
		}
		return null;
	}

	/**
	 * Check Mapping fields
	 *
	 * @param array $mapping_fields .
	 */
	public function check_mapping_fields($mapping_fields)
	{
		if (!is_array($mapping_fields)) {
			$mapping_fields = array();
		}
		if ($mapping_fields && is_array($mapping_fields)) {
			if (!array_key_exists('IP-address', $mapping_fields)) {
				$mapping_fields['IP-address'] = 'IP Address';
			}
			if (!array_key_exists('page-URL', $mapping_fields)) {
				$mapping_fields['page-URL'] = 'Page URL';
			}
			if (!array_key_exists('submission-date', $mapping_fields)) {
				$mapping_fields['submission-date'] = 'Submission Date';
			}
			if (!array_key_exists('submission-time', $mapping_fields)) {
				$mapping_fields['submission-time'] = 'Submission Time';
			}
			if (!array_key_exists('entry-id', $mapping_fields)) {
				$mapping_fields['entry-id'] = 'Entry ID';
			}
		}
	}

	/**
	 * Check active headers
	 *
	 * @param array $active_headers .
	 */
	public function check_active_headers($active_headers)
	{
		if (!is_array($active_headers)) {
			$active_headers = array();
		}
		if (!isset($active_headers[0]) || !is_array($active_headers[0])) {
			$active_headers[0] = array();
		}
		if ($active_headers && is_array($active_headers)) {
			if (!array_key_exists('IP-address', $active_headers[0])) {
				$active_headers[0]['IP-address'] = '1';
			}
			if (!array_key_exists('page-URL', $active_headers[0])) {
				$active_headers[0]['page-URL'] = '1';
			}
			if (!array_key_exists('submission-date', $active_headers[0])) {
				$active_headers[0]['submission-date'] = '1';
			}
			if (!array_key_exists('submission-time', $active_headers[0])) {
				$active_headers[0]['submission-time'] = '1';
			}
			if (!array_key_exists('entry-id', $active_headers[0])) {
				$active_headers[0]['entry-id'] = '1';
			}
		}
	}

	/**
	 * Create simple index array
	 *
	 * @access public
	 * @param array $arr .
	 * @return array $new_arr
	 */
	public static function single_array($arr)
	{
		$new_arr = array();
		foreach ($arr as $key) {
			if (is_array($key)) {
				$arr1 = self::single_array($key);
				foreach ($arr1 as $k) {
					$new_arr[] = $k;
				}
			}
			else {
				$new_arr[] = $key;
			}
		}
		return $new_arr;
	}
	/**
	 * Prepare Google Spreedsheet sheet headers for mapping fields to form fields.
	 *
	 * @access public
	 * @param int $form_id .
	 * @param int $param .
	 */
	public static function wpsslc_check_spreadsheet_header_value($form_id, $param = 0)
	{

		$form_data = self::$wpsslc_instance_api->wpsslc_option('wpssc_cf_settings', '', $form_id);
		if (!$form_data || !isset($form_data[0]['spreadsheetname']) || !isset($form_data[0]['sheetname'])) {
			return true;
		}

		if ((!empty($form_data[0]['spreadsheetname'])) && (!empty($form_data[0]['sheetname']))) {

			$spreadsheetid = $form_data[0]['spreadsheetname'];
			$spredsheet = $form_data[0]['sheetname'] . '!A1:Z1';

			$response = self::$wpsslc_instance_api->get_row_list($spreadsheetid, $spredsheet);
			$values = $response->getValues();

			if (1 === (int)$param) {
				return $response['values'];
			}
			if (empty($response['values'])) {
				return true;
			}
			else {
				return false;
			}
		}
	}

	/**
	 * Reset Google API Settings
	 */
	public static function wpsslc_reset_settings()
	{
		if (!current_user_can('edit_wpsyncsheets_contact_form_7_lite_main_settings')) {
			echo esc_html__('You do not have permission to access this page.', 'contactsheets-lite');
			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.', 'contactsheets-lite');
			wp_die();
		}
		try {
			$wpsslc_google_settings_value = self::$wpsslc_instance_api->wpsslc_option('wpssc_google_settings');
			$settings = array();
			foreach ($wpsslc_google_settings_value as $key => $value) {
				$settings[$key] = '';
			}
			self::$wpsslc_instance_api->wpsslc_update_option('wpssc_google_settings', $settings);
			self::$wpsslc_instance_api->wpsslc_update_option('wpssc_google_accessToken', '');
		}
		catch (Exception $e) {
			echo esc_html('Message: ' . $e->getMessage());
		}
		echo esc_html('successful');
		wp_die();
	}
	/**
	 * Clear spreadsheet
	 *
	 * @access public
	 */
	public static function wpsslc_clear_sheet()
	{

		$wpsslc_error = '';
		$form_id = isset($_POST['form_id']) ? sanitize_text_field(wp_unslash($_POST['form_id'])) : '';
		if (!isset($_POST['wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['wpnonce'])), 'save_sheet_settings') || empty($form_id)) {
			echo esc_html__('Sorry, your nonce did not verify.', 'contactsheets-lite');
			wp_die();
		}

		$form_data = self::$wpsslc_instance_api->wpsslc_option('wpssc_cf_settings', '', $form_id);
		$wpsslc_active_headers = self::$wpsslc_instance_api->wpsslc_option('wpssc_active_headers', '', $form_id);

		$wpsslc_spreadsheetid = $form_data[0]['spreadsheetname'];
		$sheetname = $form_data[0]['sheetname'];

		$total_headers = count($wpsslc_active_headers[0]);
		$r = self::$wpsslc_instance_api->get_row_list($wpsslc_spreadsheetid, $sheetname);

		foreach ($r['values'][0] as $data_value) {
			if ('Submission Date' === (string)$data_value) {
				$total_headers++;
				continue;
			}
		}

		foreach ($r['values'][0] as $data_value) {
			if ('Submission Time' === (string)$data_value) {
				$total_headers++;
				continue;
			}
		}

		$last_column = self::get_column_index($total_headers);
		try {
			$range = $sheetname . '!A2:' . $last_column . '100000';
			$requestbody = self::$wpsslc_instance_api->clearobject();
			$param = array();
			$param['spreadsheetid'] = $wpsslc_spreadsheetid;
			$param['sheetname'] = $range;
			$param['requestbody'] = $requestbody;
			$response = self::$wpsslc_instance_api->clear($param);
			echo esc_html('successful');
		}
		catch (Exception $e) {
			echo esc_html('Message: ' . $e->getMessage());
		}
		wp_die();
	}
	/**
	 * Get column index of sheet
	 *
	 * @access public
	 * @param int $number .
	 * @return string $letter
	 */
	public static function 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;
	}
	/**
	 * Fetch spreadsheet sheets and output option markup.
	 *
	 * @return void
	 */
	public static function wpsslc_get_sheetslist()
	{

		$spreadsheetid = isset($_POST['spreadsheetid']) ? sanitize_text_field(wp_unslash($_POST['spreadsheetid'])) : '';

		if (empty($spreadsheetid) || !isset($_POST['wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['wpnonce'])), 'save_sheet_settings')) {
			wp_send_json_error();
		}

		$response = self::$wpsslc_instance_api->get_sheet_listing($spreadsheetid);

		$html = '';
		if (!empty($response) && !is_wp_error($response)) {
			$html .= '<option value="">Select Sheet</option>';
			foreach ($response->getSheets() as $s) {
				$val = $s['properties']['title'];
				$html .= '<option value="' . esc_attr($val) . '">' . esc_html($val) . '</option>';
			}
			$html .= '<option value="new">Create New Sheet</option>';
		}
		else {
			wp_send_json_error();
		}
		wp_send_json_success(
			array(
			'html' => $html,
		)
		);
	}
	/**
	 * Check for existing spreadsheet
	 *
	 * @param array $data array of spreadsheet id and sheet name.
	 */
	public static function wpsslc_check_existing_sheet($data)
	{

		$wpsslc_spreadsheetid = $data['spreadsheetid'];
		$wpsslc_sheetname = $data['sheetname'];
		if ('new' !== (string)$wpsslc_spreadsheetid && 0 !== (int)$wpsslc_spreadsheetid) {
			$wpsslc_exist = 0;
			$wpsslc_response = self::$wpsslc_instance_api->get_sheet_listing($wpsslc_spreadsheetid);
			$wpsslc_existingsheetsnames = self::$wpsslc_instance_api->get_sheet_list($wpsslc_response);
			$wpsslc_existingsheetsnames = array_flip($wpsslc_existingsheetsnames);
			if (in_array($wpsslc_sheetname, $wpsslc_existingsheetsnames, true)) {
				return true;
			}
		}
		return false;
	}
}
$wpsslc_instance = new WPSSLC_Service();
