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

if ( ! class_exists( 'SftcyWordformAjaxhandler' ) ) {
	class SftcyWordformAjaxhandler {

		private static $initiated   = false;
		public static $success_icon = '<i class="fa-regular fa-circle-check"></i>';
		public static $error_icon   = '<i class="fa-regular fa-circle-xmark"></i>';
		public static $info_icon    = '<i class="fa-solid fa-circle-info"></i>';
		public static $warning_icon = '<i class="fa-solid fa-circle-exclamation"></i>';
		public static $wordform_pages = [];
		public static $output       = array();		

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

		private static function initiate_hooks() {
				// Enqueue scripts
				add_action( 'admin_enqueue_scripts', array( __CLASS__, 'sc_wordform_admin_required_scripts' ) );
				add_action( 'wp_enqueue_scripts', array( __CLASS__, 'sc_wordform_frontend_required_scripts' ) );
				// add_action( 'enqueue_block_editor_assets', array( __CLASS__, 'sc_wordform_block_editor_required_scripts' ) );
				add_action( 'enqueue_block_assets', array( __CLASS__, 'sc_wordform_block_editor_required_scripts' ) );
				
				add_action( 'init', array( __CLASS__, 'wordform_both_admin_front_end_register_scripts' ) );
				add_filter( 'safe_style_css', array( __CLASS__, 'sc_wordform_style_filter_hook' ), 10, 1 );

				// Add body class
				add_filter( 'admin_body_class', array( __CLASS__, 'wordform_plugin_admin_pages_body_class') );

				// Ajax : WordForm Elements
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_text', array( __CLASS__, 'sc_wordform_render_element_options_type_text' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_firstlastname', array( __CLASS__, 'sc_wordform_render_element_options_type_firstlastname' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_number', array( __CLASS__, 'sc_wordform_render_element_options_type_number' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_textarea', array( __CLASS__, 'sc_wordform_render_element_options_type_textarea' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_range', array( __CLASS__, 'sc_wordform_render_element_options_type_range' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_url', array( __CLASS__, 'sc_wordform_render_element_options_type_url' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_date', array( __CLASS__, 'sc_wordform_render_element_options_type_date' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_time', array( __CLASS__, 'sc_wordform_render_element_options_type_time' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_datetime', array( __CLASS__, 'sc_wordform_render_element_options_type_datetime' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_tel', array( __CLASS__, 'sc_wordform_render_element_options_type_tel' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_radio', array( __CLASS__, 'sc_wordform_render_element_options_type_radio' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_checkbox', array( __CLASS__, 'sc_wordform_render_element_options_type_checkbox' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_select', array( __CLASS__, 'sc_wordform_render_element_options_type_select' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_email', array( __CLASS__, 'sc_wordform_render_element_options_type_email' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_address', array( __CLASS__, 'sc_wordform_render_element_options_type_address' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_sectionhtml', array( __CLASS__, 'sc_wordform_render_element_options_type_sectionhtml' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_maskinput', array( __CLASS__, 'sc_wordform_render_element_options_type_maskinput' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_hidden', array( __CLASS__, 'sc_wordform_render_element_options_type_hidden' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_captcha', array( __CLASS__, 'sc_wordform_render_element_options_type_captcha' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_gcaptcha', array( __CLASS__, 'sc_wordform_render_element_options_type_gcaptcha' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_hcaptcha', array( __CLASS__, 'sc_wordform_render_element_options_type_hcaptcha' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_upload', array( __CLASS__, 'sc_wordform_render_element_options_type_upload' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_rating', array( __CLASS__, 'sc_wordform_render_element_options_type_rating' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_richeditor', array( __CLASS__, 'sc_wordform_render_element_options_type_richeditor' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_likert', array( __CLASS__, 'sc_wordform_render_element_options_type_likert' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_signature', array( __CLASS__, 'sc_wordform_render_element_options_type_signature' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_pagebreak', array( __CLASS__, 'sc_wordform_render_element_options_type_pagebreak' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_terms', array( __CLASS__, 'sc_wordform_render_element_options_type_terms' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_gdpr', array( __CLASS__, 'sc_wordform_render_element_options_type_gdpr' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_payment_item', array( __CLASS__, 'sc_wordform_render_element_options_type_payment_item' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_payment_coupon', array( __CLASS__, 'sc_wordform_render_element_options_type_payment_coupon' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_payment_method', array( __CLASS__, 'sc_wordform_render_element_options_type_payment_method' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_payment_custom_amount', array( __CLASS__, 'sc_wordform_render_element_options_type_payment_custom_amount' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_payment_quantity', array( __CLASS__, 'sc_wordform_render_element_options_type_payment_quantity' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_payment_summary', array( __CLASS__, 'sc_wordform_render_element_options_type_payment_summary' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_stripe', array( __CLASS__, 'sc_wordform_render_element_options_type_stripe' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_paypal', array( __CLASS__, 'sc_wordform_render_element_options_type_paypal' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_square', array( __CLASS__, 'sc_wordform_render_element_options_type_square' ) );
				add_action( 'wp_ajax_sc_wordform_render_element_options_type_authorizenet', array( __CLASS__, 'sc_wordform_render_element_options_type_authorizenet' ) );

				// Ajax : WordForm Captcha
				add_action( 'wp_ajax_wordform_generate_captcha_image', array( __CLASS__, 'wordform_generate_captcha_image' ) );

				// Ajax : Save created - edited wordform data - Delete
				add_action( 'wp_ajax_sc_wordform_save', array( __CLASS__, 'sc_wordform_save' ) );
				add_action( 'wp_ajax_sc_wordform_built_form_data_save', array( __CLASS__, 'sc_wordform_built_form_data_save' ) );
				add_action( 'wp_ajax_sc_wordform_all_forms_page_delete_form', array( __CLASS__, 'sc_wordform_all_forms_page_delete_form' ) );

				// Ajax : Settings : Validation tab
				add_action( 'wp_ajax_sc_wordform_settings_menu_validation_tab_data_save', array( __CLASS__, 'sc_wordform_settings_menu_validation_tab_data_save' ) );
				add_action( 'wp_ajax_sc_wordform_settings_menu_validation_tab_data_reset', array( __CLASS__, 'sc_wordform_settings_menu_validation_tab_data_reset' ) );
				add_action( 'wp_ajax_sc_wordform_settings_menu_validation_tab_selected_form_data_save', array( __CLASS__, 'sc_wordform_settings_menu_validation_tab_selected_form_data_save' ) );
				// Ajax: Settings : General Tab
				add_action( 'wp_ajax_sc_wordform_settings_general_tab_form', array( __CLASS__, 'sc_wordform_settings_general_tab_form' ) );
				add_action( 'wp_ajax_sc_wordform_get_general_tab_data', array( __CLASS__, 'sc_wordform_get_general_tab_data' ) );
				add_action( 'wp_ajax_sc_wordform_get_general_tab_default_data', array( __CLASS__, 'sc_wordform_get_general_tab_default_data' ) );
				
				// Ajax: Settings : Upload Tab
				add_action( 'wp_ajax_sc_wordform_settings_upload_tab_form', array( __CLASS__, 'sc_wordform_settings_upload_tab_form' ) );	
				// Ajax: Settings : Payment Tab
				add_action( 'wp_ajax_sc_wordform_settings_payment_tab_form', array( __CLASS__, 'sc_wordform_settings_payment_tab_form' ) );
				add_action( 'wp_ajax_sc_wordform_coupon_save', array( __CLASS__, 'sc_wordform_coupon_save' ) );
				add_action( 'wp_ajax_sc_wordform_coupon_delete', array( __CLASS__, 'sc_wordform_coupon_delete' ) );
				add_action( 'wp_ajax_sc_wordform_validate_coupon', array( __CLASS__, 'sc_wordform_validate_coupon' ) );
				add_action( 'wp_ajax_nopriv_sc_wordform_validate_coupon', array( __CLASS__, 'sc_wordform_validate_coupon' ) );
				// Ajax: Settings : Google reCaptcha Tab
				add_action( 'wp_ajax_sc_wordform_settings_google_recaptcha_tab_form', array( __CLASS__, 'sc_wordform_settings_google_recaptcha_tab_form' ) );
				add_action( 'wp_ajax_sc_wordform_settings_hcaptcha_tab_form', array( __CLASS__, 'sc_wordform_settings_hcaptcha_tab_form' ) );
				add_action( 'wp_ajax_sc_wordform_submit_support_request', array( __CLASS__, 'sc_wordform_submit_support_request' ) );
				add_action( 'wp_ajax_sc_wordform_reply_support_request', array( __CLASS__, 'sc_wordform_reply_support_request' ) );
								

				// Ajax : Front-end Users submission form data display through datatable
				add_action( 'wp_ajax_sc_wordform_users_submission_report_load', array( __CLASS__, 'sc_wordform_users_submission_report_load' ) );
				add_action( 'wp_ajax_sc_wordform_users_submission_data_load', array( __CLASS__, 'sc_wordform_users_submission_data_load' ) );
				add_action( 'wp_ajax_sc_wordform_connection_status_send_log_load', array( __CLASS__, 'sc_wordform_connection_status_send_log_load' ) );
				add_action( 'wp_ajax_sc_wordform_payment_reports_load', array( __CLASS__, 'sc_wordform_payment_reports_load' ) );

				// Ajax : Front-end users form submit
				add_action( 'wp_ajax_sc_wordform_validate_created_form_submission', array( __CLASS__, 'sc_wordform_validate_created_form_submission' ) );
				add_action( 'wp_ajax_nopriv_sc_wordform_validate_created_form_submission', array( __CLASS__, 'sc_wordform_validate_created_form_submission' ) );
				add_action( 'wp_ajax_sc_wordform_create_stripe_payment_intent', array( __CLASS__, 'sc_wordform_create_stripe_payment_intent' ) );
				add_action( 'wp_ajax_nopriv_sc_wordform_create_stripe_payment_intent', array( __CLASS__, 'sc_wordform_create_stripe_payment_intent' ) );
				add_action( 'wp_ajax_sc_wordform_create_paypal_order', array( __CLASS__, 'sc_wordform_create_paypal_order' ) );
				add_action( 'wp_ajax_nopriv_sc_wordform_create_paypal_order', array( __CLASS__, 'sc_wordform_create_paypal_order' ) );
				add_action( 'wp_ajax_sc_wordform_capture_paypal_order', array( __CLASS__, 'sc_wordform_capture_paypal_order' ) );
				add_action( 'wp_ajax_nopriv_sc_wordform_capture_paypal_order', array( __CLASS__, 'sc_wordform_capture_paypal_order' ) );
				add_action( 'wp_ajax_sc_wordform_create_square_payment', array( __CLASS__, 'sc_wordform_create_square_payment' ) );
				add_action( 'wp_ajax_nopriv_sc_wordform_create_square_payment', array( __CLASS__, 'sc_wordform_create_square_payment' ) );
				add_action( 'wp_ajax_sc_wordform_create_authorizenet_transaction', array( __CLASS__, 'sc_wordform_create_authorizenet_transaction' ) );
				add_action( 'wp_ajax_nopriv_sc_wordform_create_authorizenet_transaction', array( __CLASS__, 'sc_wordform_create_authorizenet_transaction' ) );
				add_action( 'wp_ajax_sc_wordform_created_form_submission', array( __CLASS__, 'sc_wordform_created_form_submission' ) );
				add_action( 'wp_ajax_nopriv_sc_wordform_created_form_submission', [ __CLASS__, 'sc_wordform_created_form_submission'] );

				// Ajax: Front-end users form submit data send activate - deactivate
				add_action( 'wp_ajax_wordform_forms_data_send_activate_deactivate', [ __CLASS__, 'wordform_forms_data_send_activate_deactivate'] );				
				add_action( 'wp_ajax_wordform_connect_check_webhook_endpoint', [ __CLASS__, 'wordform_connect_check_webhook_endpoint'] );

				// REST API : End Points : Wordform Block Editor
				add_action(
					'rest_api_init',
					function () {
															register_rest_route(
																'wordform/v1',
																'/all-form-list',
																array(
																	'methods'  => 'POST',
																	'callback' => array( __CLASS__, 'sc_wordform_block_editor_get_forms_ajax_callback' ),
																	'permission_callback' => function () {
																			return true;},
																)
															);
					}
				);

				add_action(
					'rest_api_init',
					function () {
															register_rest_route(
																'wordform/v1',
																'/render-selected-form',
																array(
																	'methods'  => 'POST',
																	'callback' => array( __CLASS__, 'sc_wordform_block_editor_get_selected_form_ajax_callback' ),
																	'permission_callback' => function () {
																			return true;},
																)
															);
					}
				);

				self::$initiated = true;
		}


		/**
		 * Block Editor
		 * Rest API Callback
		 * Rest Path: wordform/v1/all-form-list
		 * Get all created form lists for block editor to display & to choose from dropdown select menu
		 * return - json
		 */
		public static function sc_wordform_block_editor_get_forms_ajax_callback( $data ) {
			self::$output = array();
			$result       = $data->get_body();
			if ( $result ) {
				$result_arr = json_decode( $result, true );
				if ( isset( $result_arr['postID'] ) && ! empty( $result_arr['postID'] ) ) {
					$postID                   = sanitize_text_field( $result_arr['postID'] );
					$created_forms            = SftcyWordformBase::sc_wordform_get_all_forms_for_block_dynamic_callback();
					self::$output['status']   = 'success';
					self::$output['formList'] = $created_forms;
					self::$output['postID']   = $postID;
				} else {
					self::$output['status']  = 'fail';
					self::$output['comment'] = 'postID not received.';
				}
			} else {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'No post Result data found.';
			}
			return wp_json_encode( self::$output );
		}

		/**
		 * Block Editor
		 * Rest API Callback
		 * Rest Path: wordform/v1/render-selected-form
		 * Rendering the created form based on selected or chosen from block editor dropdown list
		 * Embed the selected form with the post
		 * Also save the POST ID attached with the selected form
		 * return json
		 */
		public static function sc_wordform_block_editor_get_selected_form_ajax_callback( $data ) {
			self::$output = array();

			$result = $data->get_body();
			if ( $result ) {
				$result_arr = json_decode( $result, true );
				if ( isset( $result_arr['WordFormID'] ) && ! empty( $result_arr['WordFormID'] ) ) {
					$form_id                  = sanitize_text_field( $result_arr['WordFormID'] );
					$attached_post_id         = sanitize_text_field( $result_arr['postID'] );
					self::$output['formdata'] = SftcyWordformBuildForm::wordform_built_to_display( $form_id );
					self::$output['status']   = 'success';
					self::$output['reason']   = 'Form data ready to display.';
				}
			} else {
				self::$output['status'] = 'fail';
				self::$output['reason'] = 'no form ID received.';
			}
			return wp_json_encode( self::$output );
		}

		/**
		 * Submit a support request from the Support admin page.
		 *
		 * @return void
		 */
		public static function sc_wordform_submit_support_request() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output = array();

			if ( ! current_user_can( 'manage_options' ) ) {
				self::$output['status']  = 'fail';
				self::$output['message'] = __( 'You do not have permission to send support requests.', 'wordform-pro' );
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$request_data = array(
				'sender_email'        => isset( $_POST['sender_email'] ) ? sanitize_email( wp_unslash( $_POST['sender_email'] ) ) : '',
				'subject'             => isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : '',
				'issue_type'          => isset( $_POST['issue_type'] ) ? sanitize_key( wp_unslash( $_POST['issue_type'] ) ) : 'general',
				'message'             => isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '',
				'include_diagnostics' => isset( $_POST['include_diagnostics'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['include_diagnostics'] ) ) ? 'yes' : 'no',
				'delivery_channels'   => isset( $_POST['delivery_channels'] ) && is_array( $_POST['delivery_channels'] )
					? array_map(
						static function( $channel ) {
							return sanitize_key( wp_unslash( $channel ) );
						},
						$_POST['delivery_channels']
					)
					: array(),
			);

			$attachment_result = SftcyWordformSupport::handle_support_request_attachments( $_FILES['support_attachments'] ?? array() );
			if ( isset( $attachment_result['status'] ) && 'fail' === $attachment_result['status'] ) {
				self::$output['status']  = 'fail';
				self::$output['message'] = $attachment_result['message'] ?? __( 'Support attachment could not be uploaded.', 'wordform-pro' );
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$request_data['attachments'] = $attachment_result['attachments'] ?? array();

			$result = SftcyWordformSupport::create_support_request( $request_data );

			self::$output['status']      = isset( $result['status'] ) ? $result['status'] : 'fail';
			self::$output['message']     = isset( $result['message'] ) ? $result['message'] : __( 'Support request could not be sent.', 'wordform-pro' );
			self::$output['ticket_uuid'] = isset( $result['ticket_uuid'] ) ? $result['ticket_uuid'] : '';
			self::$output['delivery_results'] = isset( $result['delivery_results'] ) ? $result['delivery_results'] : array();
			self::$output['overall_status'] = isset( $result['overall_status'] ) ? $result['overall_status'] : 'received';

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

		public static function sc_wordform_reply_support_request() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output = array();

			if ( ! current_user_can( 'manage_options' ) ) {
				self::$output['status']  = 'fail';
				self::$output['message'] = __( 'You do not have permission to reply to support requests.', 'wordform-pro' );
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$ticket_uuid   = isset( $_POST['ticket_uuid'] ) ? sanitize_text_field( wp_unslash( $_POST['ticket_uuid'] ) ) : '';
			$sender_email  = isset( $_POST['sender_email'] ) ? sanitize_email( wp_unslash( $_POST['sender_email'] ) ) : '';
			$reply_message = isset( $_POST['reply_message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['reply_message'] ) ) : '';

			$result = SftcyWordformSupport::reply_to_support_request( $ticket_uuid, $reply_message, $sender_email );

			self::$output['status']           = $result['status'] ?? 'fail';
			self::$output['message']          = $result['message'] ?? __( 'Reply could not be sent.', 'wordform-pro' );
			self::$output['ticket_uuid']      = $result['ticket_uuid'] ?? $ticket_uuid;
			self::$output['delivery_results'] = $result['delivery_results'] ?? array();
			self::$output['overall_status']   = $result['overall_status'] ?? 'received';

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

		/**
		 * Record a payment-related support log entry.
		 *
		 * @param string $gateway
		 * @param string $stage
		 * @param string $form_id
		 * @param string $message
		 * @param array  $context
		 * @return void
		 */
		private static function wordform_log_payment_failure( $gateway = '', $stage = '', $form_id = '', $message = '', $context = array() ) {
			SftcyWordformSupport::log_event(
				'payment',
				'error',
				sanitize_key( $gateway . '_' . $stage . '_failed' ),
				$message,
				array_merge(
					array(
						'gateway' => sanitize_key( $gateway ),
						'stage'   => sanitize_key( $stage ),
					),
					is_array( $context ) ? $context : array()
				),
				$form_id
			);
		}

		/**
		 * Register Scripts
		 * For both admin & front-end
		 */
		// public static function wordform_both_admin_front_end_register_scripts() {
		// 	wp_register_style( 'wordform-font-awesome-6-style', plugins_url( '../admin/css/fontawesome6-all.min.css', __FILE__ ), array(), SFTCY_WORDFORM_VERSION, 'all' );
		// }


		/**
		 * Register shared scripts and styles.
		 *
		 * These handles are enqueued by the admin/frontend-specific loaders only
		 * when a WordForm screen or rendered form actually needs them.
		 */
		public static function wordform_both_admin_front_end_register_scripts() {

			// --- Detect plugin folder 
			$plugin_dir_name = basename( dirname( '../' . dirname( __FILE__ ) ) ); // e.g. wordform or wordform-pro
			$handle_prefix   = ( $plugin_dir_name === 'wordform-pro' ) ? 'wordform-pro' : 'wordform';

			wp_register_script(
				$handle_prefix . '-jquery-ui-timepicker-addon',
				plugins_url( '../assets/js/jquery-ui-timepicker-addon.js', __FILE__ ),
				array( 'jquery', 'jquery-ui-datepicker', 'jquery-ui-widget', 'jquery-ui-core' ),
				defined( 'SFTCY_WORDFORM_VERSION' ) ? SFTCY_WORDFORM_VERSION : '1.0.0',
				true
			);

			wp_register_style(
				$handle_prefix . '-jquery-ui-timepicker-addon',
				plugins_url( '../assets/css/jquery-ui-timepicker-addon.css', __FILE__ ),
				array(),
				defined( 'SFTCY_WORDFORM_VERSION' ) ? SFTCY_WORDFORM_VERSION : '1.0.0',
				'all'
			);

			wp_register_style(
				'wordform-font-awesome-6-style',
				plugins_url( '../admin/css/fontawesome6-all.min.css', __FILE__ ),
				array(),
				defined( 'SFTCY_WORDFORM_VERSION' ) ? SFTCY_WORDFORM_VERSION : '1.0.0',
				'all'
			);

			if ( 'wordform-font-awesome-6-style' !== $handle_prefix . '-font-awesome-6-style' ) {
				wp_register_style(
					$handle_prefix . '-font-awesome-6-style',
					plugins_url( '../admin/css/fontawesome6-all.min.css', __FILE__ ),
					array(),
					defined( 'SFTCY_WORDFORM_VERSION' ) ? SFTCY_WORDFORM_VERSION : '1.0.0',
					'all'
				);
			}
		}


		/**
		 * Admin Pages body class
		 *
		 * @return string - $classes
		 */
		public static function wordform_plugin_admin_pages_body_class( $classes ) {
			global $pagenow;
			$screen              = get_current_screen();
			$admin_page          = isset( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : '';
			$attachto_wordformid = isset( $_GET['attach-wordform-id'] ) ? sanitize_text_field( $_GET['attach-wordform-id'] ) : '';
			self::$wordform_pages = array( 'word-form-topmenu', 'sc-wordform-create-forms', 'sc-wordform-user-submission-data', 'sc-wordform-user-form-submission-data', 'sc-wordform-connection-status-send-log', 'sc-wordform-settings', 'wordform-connects', 'wordform-support', 'wordform-license' );

			if ( in_array( $admin_page, self::$wordform_pages ) || ! empty( $attachto_wordformid ) ) {
					$classes .= ' wordform-plugin-admin-page-body-class-wrapper';
				}
				return $classes;
			}

		/**
		 * Enqueue admin scripts
		 * Enqueue only with plugin admin pages
		 *
		 * @since 1.0.0
		 */
		public static function sc_wordform_admin_required_scripts() {
			// get current admin screen
			global $pagenow;
			$screen              = get_current_screen();
			$admin_page          = isset( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : '';
			$attachto_wordformid = isset( $_GET['attach-wordform-id'] ) ? sanitize_text_field( $_GET['attach-wordform-id'] ) : '';
			self::$wordform_pages = array( 'word-form-topmenu', 'sc-wordform-create-forms', 'sc-wordform-user-submission-data', 'sc-wordform-user-form-submission-data', 'sc-wordform-connection-status-send-log', 'sc-wordform-settings', 'wordform-connects', 'wordform-support', 'wordform-license' );

			if ( in_array( $admin_page, self::$wordform_pages ) || ! empty( $attachto_wordformid ) ) {
				global $post;

				// CSS SCRIPTS //

				// jQuery UI Timepicker Addon
				wp_enqueue_style( 'jquery-ui-timepicker-addon-style', plugins_url('../assets/css/jquery-ui-timepicker-addon.css', __FILE__), array(), SFTCY_WORDFORM_VERSION, 'all');

				// Color picker Style
				wp_enqueue_style( 'wp-color-picker' );
				// Datatable Style
				wp_enqueue_style( 'sc-wordform-datatable-style', plugins_url( '../admin/css/dataTables.css', __FILE__ ), array(), SFTCY_WORDFORM_VERSION, 'all' );

				// Wordform Style
				$wordform_admin_style_path    = SFTCY_WORDFORM_PLUGIN_DIR . 'admin/css/sc-wordform-admin-misc-styles.css';
				$wordform_admin_style_version = file_exists( $wordform_admin_style_path ) ? (string) filemtime( $wordform_admin_style_path ) : SFTCY_WORDFORM_VERSION;
				wp_enqueue_style( 'sc-wordform-admin-style', plugins_url( '../admin/css/sc-wordform-admin-misc-styles.css', __FILE__ ), array(), $wordform_admin_style_version, 'all' );

				// jQuery UI Style
				wp_enqueue_style( 'sc-wordform-jquery-ui-style', plugins_url( '../admin/css/jquery-ui.css', __FILE__ ), array(), SFTCY_WORDFORM_VERSION, 'all' );

				// Font Awesome
				// wp_enqueue_style('wordform-font-awesome-6-style', plugins_url('../admin/css/fontawesome6-all.min.css', __FILE__ ), array('sc-wordform-admin-style'), SFTCY_WORDFORM_VERSION, 'all' );
				wp_enqueue_style( 'wordform-font-awesome-6-style' );

				// JS SCRIPTS //
 
				// jQuery UI Timepicker Addon
				wp_enqueue_script( 'jquery-ui-timepicker-addon', plugins_url('../assets/js/jquery-ui-timepicker-addon.js', __FILE__), array('jquery', 'jquery-ui-datepicker'), '1.6.3',	true );	

				// Enqueue jQuery UI Accordion
				wp_enqueue_script( 'jquery-ui-accordion' );

				// Datatable JS
				wp_enqueue_script( 'sc-wordform-datatable-script', plugins_url( '../admin/js/dataTables.js', __FILE__ ), array( 'jquery' ), SFTCY_WORDFORM_VERSION, 'all' );
				// Cipboard JS
				wp_enqueue_script( 'sc-wordform-admin-copy-to-clipboard-script', plugins_url( '../admin/js/clipboard.min.js', __FILE__ ), array( 'jquery' ), SFTCY_WORDFORM_VERSION, true );
				// Shared admin color picker
				wp_enqueue_script( 'sc-wordform-iro-script', plugins_url( '../admin/js/iro.min.js', __FILE__ ), array(), SFTCY_WORDFORM_VERSION, true );
				// Wordform Custom JS - Misc common scripts
				wp_enqueue_script( 'sc-wordform-admin-misc-script', plugins_url( '../admin/js/sc-wordform-admin-misc-script.js', __FILE__ ), array( 'jquery', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-sortable', 'jquery-ui-tabs', 'jquery-ui-tooltip', 'wp-color-picker', 'jquery-ui-datepicker', 'jquery-ui-accordion', 'jquery-ui-slider', 'sc-wordform-iro-script' ), SFTCY_WORDFORM_VERSION, true );				
				
				// Wordform Custom JS 2 - View pages scripts
				$wordform_admin_view_script_path    = SFTCY_WORDFORM_PLUGIN_DIR . 'admin/js/wordform-admin-view-page-script.js';
				$wordform_admin_view_script_version = file_exists( $wordform_admin_view_script_path ) ? (string) filemtime( $wordform_admin_view_script_path ) : SFTCY_WORDFORM_VERSION;
				wp_enqueue_script( 'wordform-admin-view-page-script', plugins_url( '../admin/js/wordform-admin-view-page-script.js', __FILE__ ), array( 'jquery', 'jquery-ui-slider', 'sc-wordform-admin-misc-script' ), $wordform_admin_view_script_version, true );
				// Wordform Connect Line Arrow & Tooltip Script  - Connect line arrow and tooltips hint in Create / Edit form
				wp_enqueue_script( 'wordform-admin-line-arrow-tooltips-page-script', plugins_url( '../admin/js/wordform-admin-view-line-arrow-tooltips-page-script.js', __FILE__ ), array( 'jquery' ), SFTCY_WORDFORM_VERSION, true );
				// Wordform Connects Page Script
				wp_enqueue_script( 'wordform-admin-connects-page-script', plugins_url( '../admin/js/wordform-connects-script.js', __FILE__ ), array( 'jquery', 'jquery-ui-dialog', 'sc-wordform-admin-misc-script' ), SFTCY_WORDFORM_VERSION, true );
				// Wordform License Page Script
				// wp_enqueue_script( 'wordform-admin-license-page-script', plugins_url( '../admin/js/wordform-license-script.js', __FILE__ ), array( 'jquery', 'sc-wordform-admin-misc-script', 'jquery-ui-slider' ), SFTCY_WORDFORM_VERSION, true );

				$nonce = SftcyWordformBase::sc_wordform_get_nonce();
				$timezone_name  = function_exists( 'wp_timezone_string' ) ? wp_timezone_string() : '';
				$timezone_label = 'UTC';
				if ( function_exists( 'current_datetime' ) ) {
					$timezone_offset = current_datetime()->format( 'P' );
				} else {
					$timezone_offset = '+00:00';
				}

				if ( ! empty( $timezone_name ) && ! preg_match( '/^[+-]\d{2}:\d{2}$/', $timezone_name ) ) {
					$timezone_label = $timezone_name . ' (' . $timezone_offset . ')';
				} else {
					$timezone_label = 'UTC ' . $timezone_offset;
					if ( '+00:00' === $timezone_offset ) {
						$timezone_label = 'UTC (+00:00)';
					}
				}

				$localize_data = array(
					'adminajax_url'                 => admin_url( 'admin-ajax.php' ),
					'nonce'                         => $nonce,
					'current_screenid'              => $screen->id,
					'current_action'                => $screen->action,
					'current_posttype'              => $screen->post_type,
					'current_pagenow'               => $pagenow,
					'postID'                        => ! is_null( $post ) ? $post->ID : 0,
					'attachto_wordformid'           => $attachto_wordformid,
					'sc_wordform_submit_text'       => __( 'Submit', 'wordform-pro' ),
					'sc_wordform_submit_align'      => __( 'left', 'wordform-pro' ),
					'wordform_connect_page_url'     => esc_url( admin_url( 'admin.php?page=wordform-connects' ) ),
					'wordform_default_template_url' => SftcyWordformCaptcha::wordform_create_form_default_captcha_template_url(),
					'wordform_form_width'           => SftcyWordformBase::wordform_current_form_width(),
					'wordform_site_timezone_name'   => $timezone_name,
					'wordform_site_timezone_label'  => $timezone_label,
					'wordform_current_site_date'    => current_time( 'Y-m-d' ),
					'wordform_current_site_datetime'=> current_time( 'Y-m-d H:i' ),
					'wordform_upload_config_data'   => SftcyWordformBase::wordform_settings_page_upload_config(),
					'wordform_copied_text'          => '<i class="fa-regular fa-copy"></i> ' . __( 'Copied', 'wordform-pro' ),
					'wordform_copy_shortcode_text'  => '<i class="fa-regular fa-copy"></i> ' . __( 'Copy', 'wordform-pro' ),
					'noElementDroppedMsg'           => '<span class="dashicons dashicons-info"></span> ' . __( 'Click or drag elements into the DropZone to start creating your form.', 'wordform-pro' ),
					'support_choose_channel'       => __( 'Select at least one support delivery channel before sending the request.', 'wordform-pro' ),
					'support_sending_request'      => __( 'Sending support request...', 'wordform-pro' ),
					'support_request_failed'       => __( 'Support request could not be sent right now.', 'wordform-pro' ),
					'support_office_status_url'    => class_exists( 'SftcyWordformSupport' ) ? SftcyWordformSupport::get_support_office_status_endpoint() : trailingslashit( SFTCY_SOFTCOY_API_BASE ) . 'support/tickets/status',
					'support_softcoy_icon_url'     => 'https://www.softcoy.com/brand-assets/logos/softcoy-mark.png',
					'support_wordform_icon_url'    => 'https://softcoy.com/brand-assets/logos/wordform-pro.svg',
				);

				// Localize script
				wp_localize_script( 'sc-wordform-admin-misc-script', 'sc_wordform_metabox_script_obj', $localize_data );
				wp_localize_script( 'wordform-admin-view-page-script', 'wordform_admin_view_page_script_obj', $localize_data );
				wp_localize_script( 'wordform-admin-line-arrow-tooltips-page-script', 'wordform_admin_line_arrow_tooltips_page_script', $localize_data );
				
				wp_localize_script( 'wordform-admin-connects-page-script', 'wordform_admin_view_connects_page_script_obj', $localize_data );
				// wp_localize_script( 'wordform-admin-license-page-script', 'wordform_admin_view_license_page_script_obj', $localize_data );
			}
		}

		/**
		 * Front-end required scripts
		 * If plugin active then enqueue scripts
		 */
		public static function sc_wordform_frontend_required_scripts() {			
			self::wordform_check_plugin_activator_file();
			if ( is_plugin_active( self::wordform_current_plugin_basename() ) ) {
				global $pagenow;
				$gcaptcha_data = SftcyWordformBase::wordform_settings_page_grecaptcha_config();
				$hcaptcha_data = SftcyWordformBase::wordform_settings_page_hcaptcha_config();
				$payment_data  = SftcyWordformBase::wordform_settings_page_payment_config();

				// Loaded jQuery-UI-CSS
				// wp_enqueue_style(
				// 		'jquery-ui-css',
				// 		'https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css'
				// );			
				wp_enqueue_style( 'jquery-ui-css', plugins_url( '../assets/css/jquery-ui.css', __FILE__ ), array(), SFTCY_WORDFORM_VERSION, 'all' );

				// Front-end style
				// wp_enqueue_style( 'sc-wordform-frontend-misc-style', plugins_url( '../assets/css/sc-wordform-frontend-misc-styles.css', __FILE__ ), array(), SFTCY_WORDFORM_VERSION, 'all' );
				wp_enqueue_style( 'sc-wordform-frontend-misc-style', plugins_url( '../assets/css/wordform-frontend-custom-styles.css', __FILE__ ), array(), SFTCY_WORDFORM_VERSION, 'all' );
				wp_enqueue_style( 'sc-wordform-flatpickr-style', plugins_url( '../assets/css/flatpickr.min.css', __FILE__ ), array(), SFTCY_WORDFORM_VERSION, 'all' );
				// Font Awesome
				wp_enqueue_style( 'wordform-font-awesome-6-style' );

				wp_enqueue_script( 'sc-wordform-flatpickr-script', plugins_url( '../assets/js/flatpickr.min.js', __FILE__ ), array(), SFTCY_WORDFORM_VERSION, true );

				// Front-end main JS - Loaded with jQuery, jQuery-UI-DatePicker
				wp_enqueue_script( 'sc-wordform-frontend-misc-script', plugins_url( '../assets/js/sc-wordform-frontend-misc-script.js', __FILE__ ), array( 'jquery', 'jquery-ui-datepicker', 'sc-wordform-flatpickr-script' ), SFTCY_WORDFORM_VERSION, true );
				if ( isset( $payment_data['stripe_enabled'], $payment_data['stripe_publishable_key'] ) && 'yes' === $payment_data['stripe_enabled'] && ! empty( $payment_data['stripe_publishable_key'] ) ) {
					wp_enqueue_script( 'sc-wordform-stripe-js', 'https://js.stripe.com/v3/', array(), null, true );
				}
				if ( isset( $payment_data['paypal_enabled'], $payment_data['paypal_client_id'] ) && 'yes' === $payment_data['paypal_enabled'] && ! empty( $payment_data['paypal_client_id'] ) ) {
					$paypal_currency = isset( $payment_data['payment_currency'] ) ? strtoupper( sanitize_text_field( $payment_data['payment_currency'] ) ) : 'USD';
					$paypal_sdk_url  = add_query_arg(
						array(
							'client-id'  => trim( sanitize_text_field( $payment_data['paypal_client_id'] ) ),
							'currency'   => $paypal_currency,
							'intent'     => 'capture',
							'components' => 'buttons',
						),
						'https://www.paypal.com/sdk/js'
					);
					wp_enqueue_script( 'sc-wordform-paypal-js', $paypal_sdk_url, array(), null, true );
				}
				if ( isset( $payment_data['square_enabled'], $payment_data['square_application_id'], $payment_data['square_location_id'] ) && 'yes' === $payment_data['square_enabled'] && ! empty( $payment_data['square_application_id'] ) && ! empty( $payment_data['square_location_id'] ) ) {
					wp_enqueue_script( 'sc-wordform-square-js', SftcyWordformPaymentSquare::get_sdk_url(), array(), null, true );
				}
				if ( isset( $payment_data['authorizenet_enabled'], $payment_data['authorizenet_client_key'], $payment_data['authorizenet_api_login_id'] ) && 'yes' === $payment_data['authorizenet_enabled'] && ! empty( $payment_data['authorizenet_client_key'] ) && ! empty( $payment_data['authorizenet_api_login_id'] ) ) {
					wp_enqueue_script( 'sc-wordform-authorizenet-js', SftcyWordformPaymentAuthorizenet::get_acceptjs_url(), array(), null, true );
				}
				$nonce = SftcyWordformBase::sc_wordform_get_nonce();

				// When reCaptcha Keys are V2 Checkbox [ Classic || Enterprise ] DO NOT USE render parameter with script URL
				// When reCaptcha Keys are V3 invisible [ Classic || Enterprise ] USE render parameter with script URL 
				if ( ! empty( $gcaptcha_data['gcaptcha-site-key'] ) && $gcaptcha_data['gcaptcha-version'] == 'v2' ) {
					$recaptcha_script_url = 'https://www.google.com/recaptcha/api.js?onload=wordformOnloadgreCaptchaCallback&error-callback=wordformreCaptchaErrorCallback';
				}
				else if ( ! empty( $gcaptcha_data['gcaptcha-site-key'] ) && $gcaptcha_data['gcaptcha-version'] == 'v3' ) {
					$recaptcha_script_url = 'https://www.google.com/recaptcha/api.js?onload=wordformOnloadgreCaptchaCallback&error-callback=wordformreCaptchaErrorCallback&render=' . esc_attr( $gcaptcha_data['gcaptcha-site-key'] );
				}
				                
				// $enterprise_recaptcha_script_url = 'https://www.google.com/recaptcha/enterprise.js?sitekey=' . esc_attr( $gcaptcha_data['gcaptcha-site-key'] ) . '&badge=bottomleft';
				// if ( isset( $recaptcha_script_url ) && ! empty( $recaptcha_script_url ) ) {
				// Google reCAPTCHA script loaded only when reCAPTCHA element integrated with Form
				$google_recaptcha_element_exist_in_built_form = ( SftcyWordformBuildForm::is_google_recaptcha_element_exist_in_built_form() === true )? 1 : 0;
				if ( isset( $recaptcha_script_url ) && ! empty( $recaptcha_script_url ) && $google_recaptcha_element_exist_in_built_form === 1  ) {					
					wp_enqueue_script( 'sc-wordform-frontend-google-recaptcha-script', $recaptcha_script_url, array( 'jquery' ), SFTCY_WORDFORM_VERSION, true );					
				}
				$hcaptcha_element_exist_in_built_form = ( SftcyWordformBuildForm::is_hcaptcha_element_exist_in_built_form() === true ) ? 1 : 0;
				if ( ! empty( $hcaptcha_data['hcaptcha-site-key'] ) && 1 === $hcaptcha_element_exist_in_built_form ) {
					wp_enqueue_script( 'sc-wordform-frontend-hcaptcha-script', 'https://js.hcaptcha.com/1/api.js', array( 'jquery' ), null, true );
				}


				// Localize script
				wp_localize_script(
					'sc-wordform-frontend-misc-script',
					'sc_wordform_frontend_misc_script_obj',
					array(
						'ajax_url'                => admin_url( 'admin-ajax.php' ),
						'nonce'                   => $nonce,
						'current_pagenow'         => $pagenow,
						'remove_file_icon'        => '<i class="fa-solid fa-delete-left wordform-remove-selected-file" title="Remove"></i> ',
						'info_file_icon'          => '<i class="fa-solid fa-triangle-exclamation"></i> ',
						'hide_form_on_submission' => SftcyWordformBase::wordform_hide_form_on_submission_status(),
						'wordform_upload_config_data' => SftcyWordformBase::wordform_settings_page_upload_config(),
						'upload_max_size'		  => SftcyWordformFormValidation::convert_filesize_into_bytes( ini_get('upload_max_filesize') ),
						'post_max_size'			  => SftcyWordformFormValidation::convert_filesize_into_bytes( ini_get('post_max_size') ),	
						'max_file_upload_numbers' => ini_get( 'max_file_uploads'),
						'gcaptcha_site_key'       => $gcaptcha_data['gcaptcha-site-key'],
						'gcaptcha_type'       	  => $gcaptcha_data['gcaptcha-type'],						
						'gcaptcha_version'        => $gcaptcha_data['gcaptcha-version'],
						'gcaptcha_form_element_exist' =>  $google_recaptcha_element_exist_in_built_form,  // gcaptcha added or not into form - 1 | 0 						
						'hcaptcha_site_key'       => $hcaptcha_data['hcaptcha-site-key'],
						'hcaptcha_theme'          => $hcaptcha_data['hcaptcha-theme'],
						'hcaptcha_form_element_exist' => $hcaptcha_element_exist_in_built_form,
						'payment_settings'        => array(
							'currency'               => isset( $payment_data['payment_currency'] ) ? strtoupper( sanitize_text_field( $payment_data['payment_currency'] ) ) : 'USD',
							'currency_symbol_position' => isset( $payment_data['payment_currency_symbol_position'] ) ? sanitize_text_field( $payment_data['payment_currency_symbol_position'] ) : 'before',
							'stripe_enabled'         => isset( $payment_data['stripe_enabled'] ) ? sanitize_text_field( $payment_data['stripe_enabled'] ) : 'no',
							'stripe_publishable_key' => isset( $payment_data['stripe_publishable_key'] ) ? trim( sanitize_text_field( $payment_data['stripe_publishable_key'] ) ) : '',
							'paypal_enabled'         => isset( $payment_data['paypal_enabled'] ) ? sanitize_text_field( $payment_data['paypal_enabled'] ) : 'no',
							'paypal_client_id'       => isset( $payment_data['paypal_client_id'] ) ? trim( sanitize_text_field( $payment_data['paypal_client_id'] ) ) : '',
							'square_enabled'         => isset( $payment_data['square_enabled'] ) ? sanitize_text_field( $payment_data['square_enabled'] ) : 'no',
							'square_application_id'  => isset( $payment_data['square_application_id'] ) ? trim( sanitize_text_field( $payment_data['square_application_id'] ) ) : '',
							'square_location_id'     => isset( $payment_data['square_location_id'] ) ? trim( sanitize_text_field( $payment_data['square_location_id'] ) ) : '',
							'authorizenet_enabled'   => isset( $payment_data['authorizenet_enabled'] ) ? sanitize_text_field( $payment_data['authorizenet_enabled'] ) : 'no',
							'authorizenet_api_login_id' => isset( $payment_data['authorizenet_api_login_id'] ) ? trim( sanitize_text_field( $payment_data['authorizenet_api_login_id'] ) ) : '',
							'authorizenet_client_key' => isset( $payment_data['authorizenet_client_key'] ) ? trim( sanitize_text_field( $payment_data['authorizenet_client_key'] ) ) : '',
						),
					)
				);
			}
		}

		/**
		 * Check if requres to load plugin activator file
		 *
		 * @return void
		 */
        public static function wordform_check_plugin_activator_file() {
			if ( ! function_exists( 'is_plugin_active' ) ) {
				include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
			}
		}

		private static function wordform_current_plugin_basename() {
			if ( defined( 'SFTCY_WORDFORM_PLUGIN_FILE' ) ) {
				$plugin_dir  = basename( dirname( SFTCY_WORDFORM_PLUGIN_FILE ) );
				$plugin_file = basename( SFTCY_WORDFORM_PLUGIN_FILE );

				if ( '' !== $plugin_dir && '' !== $plugin_file ) {
					return $plugin_dir . '/' . $plugin_file;
				}
			}

			return 'wordform/wordform.php';
		}


		/**		 		  
		 * Callback of hook 'enqueue_block_assets'
		 * Block editor scripts enqeue
		 * Only when plugin is active
		 */
		public static function sc_wordform_block_editor_required_scripts() {
			self::wordform_check_plugin_activator_file();
			if ( is_plugin_active( self::wordform_current_plugin_basename() ) && is_admin() ) {
				global $pagenow;
				$screen = get_current_screen();
				// Load Font Awesome stylesheet for block editor
				wp_enqueue_style( 'wordform-font-awesome-6-style-for-wordform-block', plugins_url( '../admin/css/fontawesome6-all.min.css', __FILE__ ), array(), SFTCY_WORDFORM_VERSION, 'all' );
				// Block editor standard Stylesheet
				// wp_enqueue_style( 'sc-wordform-frontend-block-editor-misc-style', plugins_url( '../assets/css/sc-wordform-block-editor-misc-styles.css', __FILE__ ), array('wordform-font-awesome-6-style-for-wordform-block'), SFTCY_WORDFORM_VERSION, 'all' );
				wp_enqueue_style( 'sc-wordform-frontend-block-editor-misc-style', plugins_url( '../assets/css/wordform-frontend-custom-styles.css', __FILE__ ), array('wordform-font-awesome-6-style-for-wordform-block'), SFTCY_WORDFORM_VERSION, 'all' );

				wp_enqueue_script( 'sc-wordform-block-editor-misc-script', plugins_url( '../assets/js/sc-wordform-block-editor-script.js', __FILE__ ), array( 'jquery' ), SFTCY_WORDFORM_VERSION, true );
				$nonce = SftcyWordformBase::sc_wordform_get_nonce();
				// localize script
				wp_localize_script(
					'sc-wordform-block-editor-misc-script',
					'sc_wordform_block_editor_misc_script_obj',
					array(
						'ajax_url'         => admin_url( 'admin-ajax.php' ),
						'nonce'            => $nonce,
						'current_screenid' => $screen->id,
						'current_posttype' => $screen->post_type,
						'current_pagenow'  => $pagenow,
					)
				);
			}
		}

		/**
		 * Add custom style attributes
		 * To allow with wp_kses
		 */
		public static function sc_wordform_style_filter_hook( $styles ) {			
			$styles[] = 'display';
			$styles[] = 'float';
			$styles[] = 'background-color';			
			return $styles;			
		}

		// Text: Load Text Options template
		public static function sc_wordform_render_element_options_type_text() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Text';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/text.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// First Last Name: Load First Last Name Options template
		public static function sc_wordform_render_element_options_type_firstlastname() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'FirstLastName';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/firstlastname.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}


		// Number: Load Number Options template
		public static function sc_wordform_render_element_options_type_number() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Number';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/number.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}



		// Textarea: Load Textarea Options template
		public static function sc_wordform_render_element_options_type_textarea() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Textarea';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/textarea.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Range: Load Range Options template
		public static function sc_wordform_render_element_options_type_range() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Range';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/range.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Url: Load Url Options template
		public static function sc_wordform_render_element_options_type_url() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Url';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/url.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Date: Load Date Options template
		public static function sc_wordform_render_element_options_type_date() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Date';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/date.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Datetime: Load Datetime Options template
		public static function sc_wordform_render_element_options_type_datetime() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Datetime';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/datetime.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Tel: Load Tel Options template
		public static function sc_wordform_render_element_options_type_tel() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Tel';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/tel.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Radio: Load Radio Options template
		public static function sc_wordform_render_element_options_type_radio() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Radio';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/radio.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Dropdown: Load Select Dropdown template
		public static function sc_wordform_render_element_options_type_select() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Select';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/select.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Checkbox: Load Checkbox template
		public static function sc_wordform_render_element_options_type_checkbox() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Checkbox';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/checkbox.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Email: Load Email Options template
		public static function sc_wordform_render_element_options_type_email() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Email';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/email.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Address: Load Address Options template
		public static function sc_wordform_render_element_options_type_address() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Address';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/address.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Section / HTML: Load static content block options template
		public static function sc_wordform_render_element_options_type_sectionhtml() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'SectionHTML';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/sectionhtml.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Mask Input: Load patterned text input options template
		public static function sc_wordform_render_element_options_type_maskinput() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'MaskInput';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/maskinput.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Hidden: Load hidden field options template
		public static function sc_wordform_render_element_options_type_hidden() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Hidden';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/hidden.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Captcha: Load Captcha Options template
		public static function sc_wordform_render_element_options_type_captcha() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Captcha';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/captcha.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Google Captcha: Load Google Captcha Options template
		public static function sc_wordform_render_element_options_type_gcaptcha() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'gCaptcha';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/gcaptcha.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Upload: Load Upload Options template
		public static function sc_wordform_render_element_options_type_upload() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Upload';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/upload.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Rating: Load Rating options template
		public static function sc_wordform_render_element_options_type_rating() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Rating';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/rating.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Rich Editor: Load Rich Editor options template
		public static function sc_wordform_render_element_options_type_richeditor() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'RichEditor';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/richeditor.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Likert: Load Likert options template
		public static function sc_wordform_render_element_options_type_likert() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Likert';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/likert.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Signature: Load Signature options template
		public static function sc_wordform_render_element_options_type_signature() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Signature';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/signature.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Terms: Load Terms template
		public static function sc_wordform_render_element_options_type_terms() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Terms';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/terms.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// GDPR: Load GDPR consent template
		public static function sc_wordform_render_element_options_type_gdpr() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'GDPR';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/gdpr.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Time: Load Time options template
		public static function sc_wordform_render_element_options_type_time() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Time';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/time.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Page Break: Load Page Break options template
		public static function sc_wordform_render_element_options_type_pagebreak() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'PageBreak';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/pagebreak.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// hCaptcha: Load hCaptcha Options template
		public static function sc_wordform_render_element_options_type_hcaptcha() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'hCaptcha';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/hcaptcha.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( ! isset( $element_wrapper_id ) || empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Payment Item: Load Payment Item options template
		public static function sc_wordform_render_element_options_type_payment_item() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'PaymentItem';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/payment-item.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Coupon: Load payment coupon options template
		public static function sc_wordform_render_element_options_type_payment_coupon() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'PaymentCoupon';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/payment-coupon.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Payment Method: Load combined payment method selector options template
		public static function sc_wordform_render_element_options_type_payment_method() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'PaymentMethod';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/payment-method.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Custom Amount: Load Payment Custom Amount options template
		public static function sc_wordform_render_element_options_type_payment_custom_amount() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'PaymentCustomAmount';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/payment-custom-amount.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Quantity: Load Payment Quantity options template
		public static function sc_wordform_render_element_options_type_payment_quantity() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'PaymentQuantity';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/payment-quantity.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Summary: Load Payment Summary options template
		public static function sc_wordform_render_element_options_type_payment_summary() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'PaymentSummary';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/payment-summary.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Stripe: Load Stripe options template
		public static function sc_wordform_render_element_options_type_stripe() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Stripe';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/stripe.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// PayPal: Load PayPal options template
		public static function sc_wordform_render_element_options_type_paypal() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'PayPal';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/paypal.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Square: Load Square options template
		public static function sc_wordform_render_element_options_type_square() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'Square';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/square.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Authorize.Net: Load Authorize.Net options template
		public static function sc_wordform_render_element_options_type_authorizenet() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$element_wrapper_id               = isset( $_POST['elementWrapperID'] ) ? sanitize_text_field( $_POST['elementWrapperID'] ) : '';
			self::$output                     = array();
			self::$output['elementType']      = 'AuthorizeNet';
			self::$output['elementWrapperID'] = $element_wrapper_id;
			$element_index                    = explode( '-', $element_wrapper_id )[1];
			ob_start();
			include_once SFTCY_WORDFORM_PLUGIN_INC . 'elements/authorizenet.php';
			self::$output['fieldEditOptionsHtml'] = ob_get_clean();
			if ( empty( $element_wrapper_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Element wrapper ID missing.';
			} else {
				self::$output['status'] = 'success';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}



		/**
		 * Ajax Request
		 * Build form - Request comes from Create Form or Edit Form admin pages
		 * Created form data
		 * Save Form Button: Created wordform
		 *
		 * @since 1.0.0
		 */
		public static function sc_wordform_save() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			global $wpdb;
			self::$output  = array();
			$form_saved    = isset( $_POST['saveMeta']['formSaved'] ) ? sanitize_text_field( $_POST['saveMeta']['formSaved'] ) : false;
			$saved_form_id = isset( $_POST['saveMeta']['createdFormID'] ) ? sanitize_text_field( $_POST['saveMeta']['createdFormID'] ) : '';
			$form_name     = isset( $_POST['saveMeta']['formName'] ) && ! empty( $_POST['saveMeta']['formName'] ) ? sanitize_text_field( $_POST['saveMeta']['formName'] ) : 'New Form';

			// echo '<pre>';
			// print_r( $_POST['params'] );
			// echo '</pre>';
			// exit;

			if ( isset( $_POST['params'] ) && is_array( $_POST['params'] ) ) {
				$sanitized_form_data = self::sc_wordform_sanitize_created_form_data( $_POST['params'] );

				// echo '<pre>';
				// print_r( $sanitized_form_data );
				// echo '</pre>';
				// exit;

				$form_data           = wp_json_encode( $sanitized_form_data );
				// Already Saved once - Update
				if ( $form_saved && ! empty( $saved_form_id ) ) {
					$preview_url              = site_url() . '?sc-wordform-id=' . $saved_form_id;
					$update_data['form']      = $form_data;
					$update_data['form_name'] = $form_name;
					$where_data['form_id']    = trim( $saved_form_id );
					$updated_status           = $wpdb->update( $wpdb->prefix . SftcyWordformBase::$sc_wordform_tbl, $update_data, $where_data );
					self::$output['status']   = 'success';
					// self::$output['reason']   = '<span class="dashicons dashicons-saved"></span> ' . __('Form updated successfully.');
					self::$output['reason']      = '<i class="fa-solid fa-file-circle-check"></i> Form[ <strong>' . $form_name . '</strong> ]' . __( ' updated successfully.', 'wordform-pro' );
					self::$output['formSaved']   = true;
					self::$output['savedFormID'] = $saved_form_id;
					self::$output['previewURL']  = $preview_url;
				}
				// New form data - insert
				else {
					$insert_data              = array();
					$insert_data['form_name'] = $form_name;
					$insert_data['form']      = $form_data;
					$insert_record            = $wpdb->insert( $wpdb->prefix . SftcyWordformBase::$sc_wordform_tbl, $insert_data );
					if ( $insert_record ) {
						$insert_id              = $wpdb->insert_id;
						$form_id                = 'wordform-' . $insert_id;
						$update_data['form_id'] = $form_id;
						$where_data['id']       = $insert_id;
						$update_status          = $wpdb->update( $wpdb->prefix . SftcyWordformBase::$sc_wordform_tbl, $update_data, $where_data );
						if ( $update_status > 0 ) {
							$preview_url            = site_url() . '?sc-wordform-id=' . $form_id;
							self::$output['status'] = 'success';
							// self::$output['reason']           = '<span class="dashicons dashicons-saved"></span> ' . __('Form created successfully.');
							self::$output['reason']      = '<i class="fa-solid fa-file-circle-check"></i> Form[ <strong>' . $form_name . '</strong> ]' . __( ' created successfully.', 'wordform-pro' );
							self::$output['formSaved']   = true;
							self::$output['savedFormID'] = $form_id;
							self::$output['previewURL']  = $preview_url;
						} else {
							self::$output['status'] = 'fail';
							self::$output['reason'] = 'Updating Form ID field failed.';
						}
					}
				} // else
			} else {
				self::$output['status'] = 'fail';
				self::$output['reason'] = 'First drag & drop form input elements to create the form.';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		/**
		 * Sanitize created form data values
		 * preserving nested arrays for complex builder elements.
		 *
		 * @param mixed $value
		 * @return mixed
		 */
		private static function sc_wordform_sanitize_created_form_value( $value ) {
			if ( is_array( $value ) ) {
				foreach ( $value as $key => $nested_value ) {
					$value[ $key ] = self::sc_wordform_sanitize_created_form_value( $nested_value );
				}

				return $value;
			}

			if ( is_bool( $value ) ) {
				return $value ? 'true' : 'false';
			}

			if ( is_null( $value ) ) {
				return '';
			}

			return sanitize_text_field( (string) $value );
		}

		/**
		 * Sanitize created form data values.
		 *
		 * @param array $form_data
		 * @return array
		 */
		public static function sc_wordform_sanitize_created_form_data( &$form_data ) {
			foreach ( $form_data as $key => &$all_data ) {
				$form_data[ $key ] = self::sc_wordform_sanitize_created_form_value( $all_data );
			}

			return $form_data;
		}

		/**
		 * Allowed html tags for wp_kses
		 * return - array
		 */
		public static function sc_wordform_allowed_html_tags() {
			$allowed_tags = array(
				
				'img'      => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
					'src'   => array(),
					'alt'   => array(),
				),
				'a' => array(
					'href'   => array(),
					'target' => array(),
					'rel'    => array(),
					'class'  => array(),
					'id'     => array(),
					'style'  => array(),
					'title'  => array(),
					'data-*' => array(),
				),
				'label'    => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
					'for'   => array(),
				),
				'div'      => array(
					'id'            => array(),
					'class'         => array(),
					'data-*'        => true,
					'wfd-invisible' => array(),
					'style'         => array(),
				),
				'ul'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'input'    => array(
					'id'            => array(),
					'class'         => array(),
					'type'          => array(),
					'name'          => array(),
					'value'         => array(),
					'checked'       => array(),
					'min'       	=> array(),
					'max'       	=> array(),
					'step'       	=> array(),
					'minlength'     => array(),
					'maxlength'     => array(),
					'pattern'       => array(),
					'size'          => array(),
					'readonly'      => array(),
					'disabled'      => array(),
					'wfd-invisible' => array(),
					'placeholder'   => array(),
					'onfocus'       => array(),
					'onblur'        => array(),
				),
				'textarea' => array(
					'id'            => array(),
					'class'         => array(),
					'name'          => array(),
					'value'         => array(),
					'readonly'      => array(),
					'disabled'      => array(),
					'wfd-invisible' => array(),
					'rows'          => array(),
					'cols'          => array(),
					'placeholder'   => array(),
				),
				'span'     => array(
					'id'    => array(),
					'class' => array(),
					'title' => array(),
					'style' => array(),
				),
				'button'   => array(
					'id'    => array(),
					'class' => array(),
					'type'  => array(),
					'style' => array(),
				),
				'i'        => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'li'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'h1'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'h2'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'h3'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'h4'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'h5'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'h6'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'p'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'strong'   => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'b'        => array(
					'id'    => array(),
					'class' => array(),
				),
				'em'        => array(
					'id'    => array(),
					'class' => array(),
				),
				'code'        => array(
					'id'    => array(),
					'class' => array(),
				),
				'table'    => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'thead'    => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'tbody'    => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'tr'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'td'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'form'     => array(
					'id'      => array(),
					'class'   => array(),
					'name'    => array(),
					'enctype' => array(),
					'method'  => array(),
					'style'   => array(),
				),
				'select'   => array(
					'id'    => array(),
					'class' => array(),
					'name'  => array(),
					'style' => array(),
				),
				'option'   => array(
					'id'       => array(),
					'class'    => array(),
					'value'    => array(),
					'checked'  => array(),
					'selected' => array(),
					'style'    => array(),
				),
				'small'    => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'hr'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'br'       => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				)
			);
			return $allowed_tags;
		}

		/**
		 * Save built form data
		 * Save built form options data
		 * return - json
		 */
		public static function sc_wordform_built_form_data_save() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			global $wpdb;
			self::$output = array();
			$update_data  = array();
			// var_dump( $_POST );

			$builtform_data         = isset( $_POST['params']['builtForm'] ) ? wp_kses( $_POST['params']['builtForm'], self::sc_wordform_allowed_html_tags() ) : '';
			$builtform_options_data = isset( $_POST['params']['builtFormOptions'] ) ? wp_kses( $_POST['params']['builtFormOptions'], self::sc_wordform_allowed_html_tags() ) : '';
			$builder_schema_version = isset( $_POST['params']['builderSchemaVersion'] ) ? absint( $_POST['params']['builderSchemaVersion'] ) : 1;
			// $builtform_data                              = isset( $_POST['params']['builtForm'] )? $_POST['params']['builtForm'] : '';
			// $builtform_options_data                      = isset( $_POST['params']['builtFormOptions'] )? $_POST['params']['builtFormOptions'] : '';

			
			// print_r($builtform_data);
			// print_r($builtform_options_data);
			// exit(); 

			$builtform_html                = array(
				'builtform_data'         => $builtform_data,
				'builtform_options_data' => $builtform_options_data,
				'builder_schema_version' => $builder_schema_version,
			);
			$builtform_html_json           = wp_json_encode( $builtform_html );
			self::$output['builtFormData'] = $builtform_html_json;
			$wordform_id                   = isset( $_POST['params']['formID'] ) ? sanitize_text_field( $_POST['params']['formID'] ) : '';

			if ( isset( $wordform_id ) && ! empty( $wordform_id ) ) {
				$update_data['builtform_html_data'] = $builtform_html_json;
				$where_data['form_id']              = $wordform_id;
				$update_record                      = $wpdb->update( $wpdb->prefix . SftcyWordformBase::$sc_wordform_tbl, $update_data, $where_data );
				if ( $update_record ) {
					self::$output['status'] = 'success';
					self::$output['reason'] = __( 'Updated built form data successfully.', 'wordform-pro' );
				} else {
					self::$output['status'] = 'success';
					self::$output['reason'] = __( 'Nothing changes.', 'wordform-pro' );
				}
			} else {
				self::$output['status'] = 'fail';
				self::$output['reason'] = __( 'Invalid word form ID.', 'wordform-pro' );
			}

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

		/**
		 * [ Currently Not Used ]
		 * Update attached block html form content on edit created form data
		 * Update attached block html form content on edit submit button attributes through settings - general tab
		 *
		 * @since 1.0.0
		 */
		/*
		public static function sc_wordform_block_editor_form_html_update( $postids = [], $form_id = null ) {
		foreach ( $postids as $postID ) {
			$post           = null;
			$post           = get_post( $postID );
			if ( ! is_null( $post ) && $post ) {
				$allblocks      = [];  // Reset for multiple post IDs
				$blocks         = []; // Reset for multiple post IDs
				$blocks         = parse_blocks( $post->post_content );
				foreach( $blocks as $key => $block ) {
					if ( 'wordform-block/wordform' == $block['blockName'] )  {

						$results                        = SftcyWordformBase::sc_wordform_db_query( $form_id );
						SftcyWordformBuildForm::$form_elements = json_decode( $results[0]['form'], true );
						$created_form                   = SftcyWordformBuildForm::sc_wordform_build_form_from_elements( $form_id );
						$formdata                       = '';
						foreach ( $created_form as $form ) {
							$formdata                  .= $form;
						}
						$updated_formdata               = '<div class="sc-wordform-block-editor-div-wrapper">' . $formdata . '</div>';
						//var_dump( $formdata );
						//var_dump( $updated_formdata );
						$block['innerHTML']             =   $updated_formdata;
						if ( isset( $block['innerContent'][0] ) ) {
							$block['innerContent'][0]   =   $updated_formdata;
						}
						//var_dump($postID);
						//var_dump( $block['innerHTML'] );
						//var_dump( $block['innerContent'][0] );
						$allblocks[]                    = $block;
						//$allblocks[]  = NULL; // work
					}
					else {
						$allblocks[]    = $block;
					}
				} // foreach

				$content     = serialize_blocks($allblocks);
				$updatedPost = array(
					'ID'            => $postID,
					'post_content'  => $content
				);
				if ( wp_update_post( $updatedPost ) ) {
					self::$output[ $form_id ]['blockFormDataUpdated']  = true;
				}
				else {
					self::$output[ $form_id ]['blockFormDataUpdated']  = false;
				}
			}
		} // foreach

		}*/

		/**
		 * When delete form permanently
		 * Delete attached block html form content also from the attached Post | Page
		 *
		 * @since 1.0.0
		 */
		public static function sc_wordform_block_editor_form_html_delete( $postids = array(), $wordform_id = null ) {
			foreach ( $postids as $postID ) {
				$post = null;
				$post = get_post( $postID );
				if ( ! is_null( $post ) && $post ) {
					$allblocks = array();  // Reset for multiple post IDs
					$blocks    = array();  // Reset for multiple post IDs
					$blocks    = parse_blocks( $post->post_content );
					foreach ( $blocks as $key => $block ) {
						if ( SftcyWordformBase::$wordform_custom_block_name == $block['blockName'] && isset( $block['attrs']['wordformid'] ) && $block['attrs']['wordformid'] == $wordform_id ) {
							$allblocks[] = null;
						} else {
							$allblocks[] = $block;
						}
					} // foreach
					$content     = serialize_blocks( $allblocks );
					$updatedPost = array(
						'ID'           => $postID,
						'post_content' => $content,
					);
					// Update post content
					// $updated_post_id = wp_update_post( $updatedPost, true );
					$updated_post_id = wp_update_post( $updatedPost );
					if ( is_wp_error( $updated_post_id ) ) {
						self::$output['postOnUpdateError'][ $postID ] = $updated_post_id->get_error_messages();
						self::$output['updateFailPostIds'][]          = $postID;
					} else {
						self::$output['updateSuccessPostIds'][]        = $postID;
						self::$output['wpUpdatePostStatus'][ $postID ] = 'success';
					}
				}
			} // foreach
		}

		/**
		 * Prepare current request form payload for validation / submission.
		 *
		 * @param string $wordform_id
		 * @return array
		 */
		private static function wordform_prepare_submission_request_payload( $wordform_id = '' ) {
			$post_params = isset( $_POST['wordform'][ $wordform_id ] ) ? $_POST['wordform'][ $wordform_id ] : array();

			if ( array_filter( $_FILES ) ) {
				$file_attributes = array( 'name', 'full_path', 'type', 'size', 'tmp_name', 'error' );
				$files_info      = array();
				foreach ( $file_attributes as $attribute ) {
					if ( isset( $_FILES['wordform'][ $attribute ][ $wordform_id ]['upload'] ) ) {
						foreach ( $_FILES['wordform'][ $attribute ][ $wordform_id ]['upload'] as $key => $values ) {
							$files_info[ $key ][ $attribute ] = $values['files'];
						}
					}
				}

				if ( isset( $post_params['upload'] ) ) {
					foreach ( $post_params['upload'] as $key => $values ) {
						$post_params['upload'][ $key ] = isset( $files_info[ $key ] ) ? array_merge( $post_params['upload'][ $key ], $files_info[ $key ] ) : $post_params['upload'][ $key ];
					}
				}
			}

			return array(
				'post_params'      => $post_params,
				'sanitized_data'   => self::sc_wordform_front_end_submission_data_sanitize( $post_params ),
			);
		}

		/**
		 * Validate sanitized submission data using existing validation classes.
		 *
		 * @param string $wordform_id
		 * @param array  $submission_sanitized_form_data
		 * @return array
		 */
		private static function wordform_validate_sanitized_submission_data( $wordform_id = '', $submission_sanitized_form_data = array(), $skip_input_types = array() ) {
			SftcyWordformFormValidation::$sc_wordform_validation_data = array();
			SftcyWordformFormValidation::$wordform_id                 = $wordform_id;
			SftcyWordformFormValidation::sc_wordform_set_validation_messages();
			$skip_input_types = array_map( 'sanitize_key', (array) $skip_input_types );

			foreach ( $submission_sanitized_form_data as $input_type => $input_data ) {
				if ( in_array( sanitize_key( $input_type ), $skip_input_types, true ) ) {
					continue;
				}

				switch ( $input_type ) {
					case 'text':
						SftcyWordformFormValidation::text_validation( $input_data );
						break;
					case 'firstlastname':
						SftcyWordformFormValidation::firstlastname_validation( $input_data );
						break;
					case 'number':
						SftcyWordformFormValidation::number_validation( $input_data );
						break;
					case 'textarea':
						SftcyWordformFormValidation::textarea_validation( $input_data );
						break;
					case 'richeditor':
						SftcyWordformFormValidation::richeditor_validation( $input_data );
						break;
					case 'range':
						SftcyWordformFormValidation::range_validation( $input_data );
						break;
					case 'url':
						SftcyWordformFormValidation::url_validation( $input_data );
						break;
					case 'tel':
						SftcyWordformFormValidation::tel_validation( $input_data );
						break;
					case 'date':
						SftcyWordformFormValidation::date_validation( $input_data );
						break;
					case 'time':
						SftcyWordformFormValidation::time_validation( $input_data );
						break;
					case 'datetime':
						SftcyWordformFormValidation::datetime_validation( $input_data );
						break;
					case 'radio':
						SftcyWordformFormValidation::radio_validation( $input_data );
						break;
					case 'checkbox':
						SftcyWordformFormValidation::checkbox_validation( $input_data );
						break;
					case 'select':
						SftcyWordformFormValidation::select_validation( $input_data );
						break;
					case 'email':
						SftcyWordformFormValidation::email_validation( $input_data );
						break;
					case 'address':
						SftcyWordformFormValidation::address_validation( $input_data );
						break;
					case 'maskinput':
						SftcyWordformFormValidation::maskinput_validation( $input_data );
						break;
					case 'captcha':
						SftcyWordformFormValidation::captcha_validation( $input_data );
						break;
					case 'gcaptcha':
						SftcyWordformFormValidation::gcaptcha_validation( $input_data );
						break;
					case 'hcaptcha':
						SftcyWordformFormValidation::hcaptcha_validation( $input_data );
						break;
					case 'upload':
						SftcyWordformFormValidation::upload_validation( $input_data );
						break;
					case 'rating':
						SftcyWordformFormValidation::rating_validation( $input_data );
						break;
					case 'likert':
						SftcyWordformFormValidation::likert_validation( $input_data );
						break;
					case 'signature':
						SftcyWordformFormValidation::signature_validation( $input_data );
						break;
					case 'gdpr':
						SftcyWordformFormValidation::gdpr_validation( $input_data );
						break;
					case 'payment_custom_amount':
						SftcyWordformFormValidation::payment_custom_amount_validation( $input_data );
						break;
					case 'payment_quantity':
						SftcyWordformFormValidation::payment_quantity_validation( $input_data );
						break;
					case 'payment_method':
						SftcyWordformFormValidation::payment_method_validation( $input_data );
						break;
				}
			}

			$validation_error_data = array_filter(
				SftcyWordformFormValidation::$sc_wordform_validation_data,
				function ( $validation_data ) {
					return ( isset( $validation_data['validationStatus'] ) && 'error' === $validation_data['validationStatus'] );
				}
			);

			return array(
				'all'    => SftcyWordformFormValidation::$sc_wordform_validation_data,
				'errors' => $validation_error_data,
			);
		}

		/**
		 * Build transient key for validated submission tokens.
		 *
		 * @param string $validation_token
		 * @return string
		 */
		private static function wordform_get_submission_validation_transient_key( $validation_token = '' ) {
			return 'wordform_submission_validation_' . md5( sanitize_text_field( $validation_token ) );
		}

		/**
		 * Create a short-lived validation token after a successful pre-submit validation pass.
		 *
		 * @param string $wordform_id
		 * @return string
		 */
		private static function wordform_create_submission_validation_token( $wordform_id = '' ) {
			if ( empty( $wordform_id ) ) {
				return '';
			}

			$validation_token = wp_generate_password( 32, false, false ) . '_' . wp_rand( 1000, 9999 );
			set_transient(
				self::wordform_get_submission_validation_transient_key( $validation_token ),
				array(
					'form_id'    => sanitize_text_field( $wordform_id ),
					'created_at' => time(),
				),
				15 * MINUTE_IN_SECONDS
			);

			return $validation_token;
		}

		/**
		 * Check whether a validated submission token is still usable for the current form.
		 *
		 * @param string $validation_token
		 * @param string $wordform_id
		 * @return bool
		 */
		private static function wordform_is_valid_submission_validation_token( $validation_token = '', $wordform_id = '' ) {
			if ( empty( $validation_token ) || empty( $wordform_id ) ) {
				return false;
			}

			$validation_token_data = get_transient( self::wordform_get_submission_validation_transient_key( $validation_token ) );
			if ( empty( $validation_token_data ) || ! is_array( $validation_token_data ) ) {
				return false;
			}

			return isset( $validation_token_data['form_id'] ) && sanitize_text_field( $validation_token_data['form_id'] ) === sanitize_text_field( $wordform_id );
		}

		/**
		 * Delete a validated submission token after the submission completes.
		 *
		 * @param string $validation_token
		 * @return void
		 */
		private static function wordform_delete_submission_validation_token( $validation_token = '' ) {
			if ( empty( $validation_token ) ) {
				return;
			}

			delete_transient( self::wordform_get_submission_validation_transient_key( $validation_token ) );
		}

		/**
		 * Get structured form definition for a form id.
		 *
		 * @param string $wordform_id
		 * @return array
		 */
		private static function wordform_get_form_definition_by_id( $wordform_id = '' ) {
			$results = SftcyWordformBase::sc_wordform_db_query( $wordform_id );
			return isset( $results[0]['form'] ) ? json_decode( $results[0]['form'], true ) : array();
		}

		/**
		 * Calculate payment totals from the submitted form data.
		 *
		 * @param string $wordform_id
		 * @param array  $submission_sanitized_form_data
		 * @return array
		 */
		private static function wordform_calculate_payment_totals_from_submission( $wordform_id = '', $submission_sanitized_form_data = array() ) {
			$form_definition    = self::wordform_get_form_definition_by_id( $wordform_id );
			$fixed_items_total  = 0;
			$default_quantity   = 1;

			if ( is_array( $form_definition ) ) {
				foreach ( $form_definition as $element ) {
					$element_type = isset( $element['type'] ) ? sanitize_key( $element['type'] ) : '';
					if ( 'payment_item' === $element_type ) {
						$fixed_items_total += (float) ( isset( $element['amount'] ) ? $element['amount'] : 0 );
					} elseif ( 'payment_quantity' === $element_type && isset( $element['defaultQuantity'] ) ) {
						$default_quantity = max( 1, absint( $element['defaultQuantity'] ) );
					}
				}
			}

			$quantity_value = $default_quantity;
			if ( ! empty( $submission_sanitized_form_data['payment_quantity'] ) ) {
				foreach ( $submission_sanitized_form_data['payment_quantity'] as $quantity_field ) {
					if ( isset( $quantity_field['values'][0] ) && '' !== $quantity_field['values'][0] ) {
						$quantity_value = max( 1, absint( $quantity_field['values'][0] ) );
						break;
					}
				}
			}

			$custom_amount_total = 0;
			if ( ! empty( $submission_sanitized_form_data['payment_custom_amount'] ) ) {
				foreach ( $submission_sanitized_form_data['payment_custom_amount'] as $amount_field ) {
					if ( isset( $amount_field['values'] ) && is_array( $amount_field['values'] ) ) {
						foreach ( $amount_field['values'] as $amount_value ) {
							$custom_amount_total += (float) $amount_value;
						}
					}
				}
			}

			$fixed_subtotal = $fixed_items_total * $quantity_value;
			$subtotal       = $fixed_subtotal + $custom_amount_total;

			return array(
				'fixed_items_total'   => number_format( $fixed_items_total, 2, '.', '' ),
				'quantity'            => $quantity_value,
				'fixed_subtotal'      => number_format( $fixed_subtotal, 2, '.', '' ),
				'custom_amount_total' => number_format( $custom_amount_total, 2, '.', '' ),
				'subtotal'            => number_format( $subtotal, 2, '.', '' ),
			);
		}

		/**
		 * Extract submitted coupon code from the sanitized payload.
		 *
		 * @param array $submission_sanitized_form_data
		 * @return string
		 */
		private static function wordform_get_submitted_coupon_code( $submission_sanitized_form_data = array() ) {
			if ( empty( $submission_sanitized_form_data['payment_coupon'] ) || ! is_array( $submission_sanitized_form_data['payment_coupon'] ) ) {
				return '';
			}

			foreach ( $submission_sanitized_form_data['payment_coupon'] as $coupon_field ) {
				if ( isset( $coupon_field['values'][0] ) && '' !== trim( (string) $coupon_field['values'][0] ) ) {
					return strtoupper( sanitize_text_field( $coupon_field['values'][0] ) );
				}
			}

			return '';
		}

		/**
		 * Build validated payment amount data for gateway requests.
		 *
		 * @param string $wordform_id
		 * @param array  $submission_sanitized_form_data
		 * @param string $coupon_code
		 * @return array
		 */
		private static function wordform_get_gateway_payment_amount_data( $wordform_id = '', $submission_sanitized_form_data = array(), $coupon_code = '' ) {
			$payment_totals = self::wordform_calculate_payment_totals_from_submission( $wordform_id, $submission_sanitized_form_data );
			$subtotal       = (float) $payment_totals['subtotal'];
			$custom_total    = (float) $payment_totals['custom_amount_total'];
			$fixed_subtotal  = (float) $payment_totals['fixed_subtotal'];
			$coupon_code     = '' !== $coupon_code ? strtoupper( sanitize_text_field( $coupon_code ) ) : self::wordform_get_submitted_coupon_code( $submission_sanitized_form_data );

			$response = array(
				'status'          => 'success',
				'subtotal'        => number_format( $subtotal, 2, '.', '' ),
				'discount_amount' => '0.00',
				'total'           => number_format( $subtotal, 2, '.', '' ),
				'coupon_code'     => '',
				'coupon'          => array(),
			);

			if ( '' === $coupon_code ) {
				return $response;
			}

			$coupon_data = SftcyWordformBase::wordform_get_coupon_by_code( $coupon_code );
			$discountable_subtotal = $fixed_subtotal;
			if ( isset( $coupon_data['apply_to_custom_amount'] ) && 'yes' === $coupon_data['apply_to_custom_amount'] ) {
				$discountable_subtotal += $custom_total;
			}

			$coupon_validation = SftcyWordformBase::wordform_validate_coupon_for_form(
				$coupon_code,
				$wordform_id,
				array(
					'subtotal'              => $subtotal,
					'discountable_subtotal' => $discountable_subtotal,
					'custom_amount_total'   => $custom_total,
				)
			);

			if ( ! isset( $coupon_validation['status'] ) || 'success' !== $coupon_validation['status'] ) {
				return array(
					'status'  => 'fail',
					'message' => isset( $coupon_validation['message'] ) ? $coupon_validation['message'] : __( 'Coupon could not be applied.', 'wordform-pro' ),
				);
			}

			$response['discount_amount'] = $coupon_validation['discount_amount'];
			$response['total']           = $coupon_validation['total'];
			$response['coupon_code']     = $coupon_validation['coupon_code'];
			$response['coupon']          = isset( $coupon_validation['coupon'] ) ? $coupon_validation['coupon'] : array();

			return $response;
		}

		/**
		 * Persist coupon usage once the submission record has been created.
		 *
		 * @param string $wordform_id
		 * @param int    $submission_id
		 * @param array  $submission_sanitized_form_data
		 * @return void
		 */
		private static function wordform_record_coupon_usage_from_submission( $wordform_id = '', $submission_id = 0, $submission_sanitized_form_data = array() ) {
			$coupon_code = self::wordform_get_submitted_coupon_code( $submission_sanitized_form_data );
			if ( '' === $coupon_code ) {
				return;
			}

			$discount_amount = 0;
			if ( ! empty( $submission_sanitized_form_data['payment_coupon'] ) ) {
				foreach ( $submission_sanitized_form_data['payment_coupon'] as $coupon_field ) {
					if ( isset( $coupon_field['discountAmount'] ) ) {
						$discount_amount = (float) $coupon_field['discountAmount'];
						break;
					}
				}
			}

			if ( $discount_amount <= 0 ) {
				return;
			}

			$payment_gateway = '';
			foreach ( array( 'stripe', 'paypal', 'square', 'authorizenet' ) as $gateway_slug ) {
				if ( empty( $submission_sanitized_form_data[ $gateway_slug ] ) ) {
					continue;
				}
				foreach ( $submission_sanitized_form_data[ $gateway_slug ] as $gateway_field ) {
					if ( ! empty( $gateway_field['paymentStatus'] ) ) {
						$payment_gateway = $gateway_slug;
						break 2;
					}
				}
			}

			$coupon = SftcyWordformBase::wordform_get_coupon_by_code( $coupon_code );
			if ( empty( $coupon['id'] ) ) {
				return;
			}

			SftcyWordformBase::wordform_record_coupon_usage( $coupon, $wordform_id, $submission_id, $payment_gateway, $discount_amount );
		}

		/**
		 * Front-end pre-validation endpoint used before payment confirmation.
		 *
		 * @return void
		 */
		public static function sc_wordform_validate_created_form_submission() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output   = array();
			$wordform_id    = isset( $_POST['WordFormID'] ) ? sanitize_text_field( $_POST['WordFormID'] ) : '';

			if ( empty( $wordform_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = '<div class="sc-wordform-submisson-fail-msg-div-wrapper">' . __( 'Invalid form.', 'wordform-pro' ) . '</div>';
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$prepared_payload                = self::wordform_prepare_submission_request_payload( $wordform_id );
			$submission_sanitized_form_data  = isset( $prepared_payload['sanitized_data'] ) ? $prepared_payload['sanitized_data'] : array();
			$validation_result               = self::wordform_validate_sanitized_submission_data( $wordform_id, $submission_sanitized_form_data );

			if ( isset( $validation_result['errors'] ) && array_filter( $validation_result['errors'] ) ) {
				self::$output['status']              = 'fail';
				self::$output['failMsg']             = '<div class="sc-wordform-submisson-fail-msg-div-wrapper">' . __( 'Input validation error.', 'wordform-pro' ) . '</div>';
				self::$output['validationAllData']   = $validation_result['all'];
				self::$output['validationErrorData'] = $validation_result['errors'];
			} else {
				self::$output['status']                  = 'success';
				self::$output['reason']                  = __( 'Validation passed.', 'wordform-pro' );
				self::$output['submissionValidationToken'] = self::wordform_create_submission_validation_token( $wordform_id );
			}

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

		/**
		 * Validate and calculate coupon discount for the current form state.
		 *
		 * @return void
		 */
		public static function sc_wordform_validate_coupon() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output = array();
			$wordform_id  = isset( $_POST['WordFormID'] ) ? sanitize_text_field( $_POST['WordFormID'] ) : '';
			$coupon_code  = isset( $_POST['coupon_code'] ) ? sanitize_text_field( $_POST['coupon_code'] ) : '';

			if ( empty( $wordform_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['message'] = __( 'Invalid form.', 'wordform-pro' );
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$prepared_payload               = self::wordform_prepare_submission_request_payload( $wordform_id );
			$submission_sanitized_form_data = isset( $prepared_payload['sanitized_data'] ) ? $prepared_payload['sanitized_data'] : array();

			$amount_data = self::wordform_get_gateway_payment_amount_data( $wordform_id, $submission_sanitized_form_data, $coupon_code );
			if ( ! isset( $amount_data['status'] ) || 'success' !== $amount_data['status'] ) {
				self::$output['status']  = 'fail';
				self::$output['message'] = isset( $amount_data['message'] ) ? $amount_data['message'] : __( 'Coupon could not be applied.', 'wordform-pro' );
				echo wp_json_encode( self::$output );
				wp_die();
			}

			self::$output['status']          = 'success';
			self::$output['coupon_code']     = $amount_data['coupon_code'];
			self::$output['subtotal']        = $amount_data['subtotal'];
			self::$output['discount_amount'] = $amount_data['discount_amount'];
			self::$output['total']           = $amount_data['total'];
			self::$output['coupon']          = isset( $amount_data['coupon'] ) ? $amount_data['coupon'] : array();
			self::$output['message']         = __( 'Coupon applied successfully.', 'wordform-pro' );

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

		/**
		 * Create a Stripe PaymentIntent for the current form total.
		 *
		 * @return void
		 */
		public static function sc_wordform_create_stripe_payment_intent() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output    = array();
			$form_id         = isset( $_POST['wordform_id'] ) ? sanitize_text_field( $_POST['wordform_id'] ) : '';
			$form_name       = isset( $_POST['wordform_name'] ) ? sanitize_text_field( $_POST['wordform_name'] ) : '';
			$currency        = isset( $_POST['currency'] ) ? strtoupper( sanitize_text_field( $_POST['currency'] ) ) : 'USD';
			$receipt_email   = isset( $_POST['receipt_email'] ) ? sanitize_email( $_POST['receipt_email'] ) : '';
			$prepared_payload               = self::wordform_prepare_submission_request_payload( $form_id );
			$submission_sanitized_form_data = isset( $prepared_payload['sanitized_data'] ) ? $prepared_payload['sanitized_data'] : array();
			$amount_data                    = self::wordform_get_gateway_payment_amount_data( $form_id, $submission_sanitized_form_data );

			if ( ! isset( $amount_data['status'] ) || 'success' !== $amount_data['status'] ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Stripe payment could not be initialized.', 'wordform-pro' );
				self::$output['comment'] = isset( $amount_data['message'] ) ? $amount_data['message'] : __( 'Unable to determine the final payment total.', 'wordform-pro' );
				self::$output['reason']  = isset( $amount_data['message'] ) ? $amount_data['message'] : __( 'Stripe initialization failed.', 'wordform-pro' );
				self::wordform_log_payment_failure( 'stripe', 'prepare', $form_id, self::$output['reason'], array( 'currency' => $currency ) );
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$amount = (float) $amount_data['total'];

			$intent_result = SftcyWordformPaymentStripe::create_payment_intent( $amount, $currency, $form_id, $form_name, $receipt_email );

			if ( isset( $intent_result['status'] ) && 'success' === $intent_result['status'] ) {
				self::$output['status'] = 'success';
				self::$output           = array_merge( self::$output, $intent_result );
			} else {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Stripe payment could not be initialized.', 'wordform-pro' );
				self::$output['comment'] = isset( $intent_result['comment'] ) ? $intent_result['comment'] : __( 'Unknown Stripe error.', 'wordform-pro' );
				self::$output['reason']  = isset( $intent_result['reason'] ) ? $intent_result['reason'] : __( 'Stripe initialization failed.', 'wordform-pro' );
				self::wordform_log_payment_failure( 'stripe', 'intent', $form_id, self::$output['reason'], array( 'comment' => self::$output['comment'], 'currency' => $currency ) );
			}

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

		/**
		 * Create a PayPal order for the current form total.
		 *
		 * @return void
		 */
		public static function sc_wordform_create_paypal_order() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output  = array();
			$form_id       = isset( $_POST['wordform_id'] ) ? sanitize_text_field( wp_unslash( $_POST['wordform_id'] ) ) : '';
			$form_name     = isset( $_POST['wordform_name'] ) ? sanitize_text_field( wp_unslash( $_POST['wordform_name'] ) ) : '';
			$currency      = isset( $_POST['currency'] ) ? strtoupper( sanitize_text_field( wp_unslash( $_POST['currency'] ) ) ) : 'USD';
			$prepared_payload               = self::wordform_prepare_submission_request_payload( $form_id );
			$submission_sanitized_form_data = isset( $prepared_payload['sanitized_data'] ) ? $prepared_payload['sanitized_data'] : array();
			$amount_data                    = self::wordform_get_gateway_payment_amount_data( $form_id, $submission_sanitized_form_data );

			if ( ! isset( $amount_data['status'] ) || 'success' !== $amount_data['status'] ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'PayPal order could not be created.', 'wordform-pro' );
				self::$output['comment'] = isset( $amount_data['message'] ) ? $amount_data['message'] : __( 'Unable to determine the final payment total.', 'wordform-pro' );
				self::$output['reason']  = isset( $amount_data['message'] ) ? $amount_data['message'] : __( 'PayPal order initialization failed.', 'wordform-pro' );
				self::wordform_log_payment_failure( 'paypal', 'prepare', $form_id, self::$output['reason'], array( 'currency' => $currency ) );
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$amount = (float) $amount_data['total'];

			$order_result = SftcyWordformPaymentPaypal::create_order( $amount, $currency, $form_id, $form_name );

			if ( isset( $order_result['status'] ) && 'success' === $order_result['status'] ) {
				self::$output['status'] = 'success';
				self::$output           = array_merge( self::$output, $order_result );
			} else {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'PayPal order could not be created.', 'wordform-pro' );
				self::$output['comment'] = isset( $order_result['comment'] ) ? $order_result['comment'] : __( 'Unknown PayPal error.', 'wordform-pro' );
				self::$output['reason']  = isset( $order_result['reason'] ) ? $order_result['reason'] : __( 'PayPal order initialization failed.', 'wordform-pro' );
				self::wordform_log_payment_failure( 'paypal', 'order', $form_id, self::$output['reason'], array( 'comment' => self::$output['comment'], 'currency' => $currency ) );
			}

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

		/**
		 * Capture an approved PayPal order.
		 *
		 * @return void
		 */
		public static function sc_wordform_capture_paypal_order() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output  = array();
			$order_id      = isset( $_POST['order_id'] ) ? sanitize_text_field( wp_unslash( $_POST['order_id'] ) ) : '';

			$capture_result = SftcyWordformPaymentPaypal::capture_order( $order_id );

			if ( isset( $capture_result['status'] ) && 'success' === $capture_result['status'] ) {
				self::$output['status'] = 'success';
				self::$output           = array_merge( self::$output, $capture_result );
			} else {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'PayPal payment could not be captured.', 'wordform-pro' );
				self::$output['comment'] = isset( $capture_result['comment'] ) ? $capture_result['comment'] : __( 'Unknown PayPal capture error.', 'wordform-pro' );
				self::$output['reason']  = isset( $capture_result['reason'] ) ? $capture_result['reason'] : __( 'PayPal capture failed.', 'wordform-pro' );
				self::wordform_log_payment_failure( 'paypal', 'capture', '', self::$output['reason'], array( 'comment' => self::$output['comment'], 'order_id' => $order_id ) );
			}

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

		/**
		 * Create a Square payment.
		 *
		 * @return void
		 */
		public static function sc_wordform_create_square_payment() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output          = array();
			$form_id               = isset( $_POST['wordform_id'] ) ? sanitize_text_field( $_POST['wordform_id'] ) : '';
			$form_name             = isset( $_POST['wordform_name'] ) ? sanitize_text_field( $_POST['wordform_name'] ) : '';
			$currency              = isset( $_POST['currency'] ) ? strtoupper( sanitize_text_field( $_POST['currency'] ) ) : 'USD';
			$buyer_email           = isset( $_POST['buyer_email'] ) ? sanitize_email( $_POST['buyer_email'] ) : '';
			$source_id             = isset( $_POST['source_id'] ) ? sanitize_text_field( $_POST['source_id'] ) : '';
			$verification_token    = isset( $_POST['verification_token'] ) ? sanitize_text_field( $_POST['verification_token'] ) : '';
			$prepared_payload               = self::wordform_prepare_submission_request_payload( $form_id );
			$submission_sanitized_form_data = isset( $prepared_payload['sanitized_data'] ) ? $prepared_payload['sanitized_data'] : array();
			$amount_data                    = self::wordform_get_gateway_payment_amount_data( $form_id, $submission_sanitized_form_data );

			if ( ! isset( $amount_data['status'] ) || 'success' !== $amount_data['status'] ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Square payment could not be completed.', 'wordform-pro' );
				self::$output['comment'] = isset( $amount_data['message'] ) ? $amount_data['message'] : __( 'Unable to determine the final payment total.', 'wordform-pro' );
				self::$output['reason']  = isset( $amount_data['message'] ) ? $amount_data['message'] : __( 'Square payment failed.', 'wordform-pro' );
				self::wordform_log_payment_failure( 'square', 'prepare', $form_id, self::$output['reason'], array( 'currency' => $currency ) );
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$amount = (float) $amount_data['total'];

			$payment_result = SftcyWordformPaymentSquare::create_payment( $amount, $currency, $source_id, $verification_token, $form_id, $form_name, $buyer_email );

			if ( isset( $payment_result['status'] ) && 'success' === $payment_result['status'] ) {
				self::$output['status'] = 'success';
				self::$output           = array_merge( self::$output, $payment_result );
			} else {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Square payment could not be completed.', 'wordform-pro' );
				self::$output['comment'] = isset( $payment_result['comment'] ) ? $payment_result['comment'] : __( 'Unknown Square error.', 'wordform-pro' );
				self::$output['reason']  = isset( $payment_result['reason'] ) ? $payment_result['reason'] : __( 'Square payment failed.', 'wordform-pro' );
				self::wordform_log_payment_failure( 'square', 'charge', $form_id, self::$output['reason'], array( 'comment' => self::$output['comment'], 'currency' => $currency ) );
			}

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

		/**
		 * Create an Authorize.Net transaction from Accept.js opaque data.
		 *
		 * @return void
		 */
		public static function sc_wordform_create_authorizenet_transaction() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output       = array();
			$form_id            = isset( $_POST['wordform_id'] ) ? sanitize_text_field( $_POST['wordform_id'] ) : '';
			$form_name          = isset( $_POST['wordform_name'] ) ? sanitize_text_field( $_POST['wordform_name'] ) : '';
			$buyer_email        = isset( $_POST['buyer_email'] ) ? sanitize_email( $_POST['buyer_email'] ) : '';
			$data_descriptor    = isset( $_POST['data_descriptor'] ) ? sanitize_text_field( $_POST['data_descriptor'] ) : '';
			$data_value         = isset( $_POST['data_value'] ) ? sanitize_text_field( $_POST['data_value'] ) : '';
			$prepared_payload               = self::wordform_prepare_submission_request_payload( $form_id );
			$submission_sanitized_form_data = isset( $prepared_payload['sanitized_data'] ) ? $prepared_payload['sanitized_data'] : array();
			$amount_data                    = self::wordform_get_gateway_payment_amount_data( $form_id, $submission_sanitized_form_data );

			if ( ! isset( $amount_data['status'] ) || 'success' !== $amount_data['status'] ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Authorize.Net payment could not be completed.', 'wordform-pro' );
				self::$output['comment'] = isset( $amount_data['message'] ) ? $amount_data['message'] : __( 'Unable to determine the final payment total.', 'wordform-pro' );
				self::$output['reason']  = isset( $amount_data['message'] ) ? $amount_data['message'] : __( 'Authorize.Net payment failed.', 'wordform-pro' );
				self::wordform_log_payment_failure( 'authorizenet', 'prepare', $form_id, self::$output['reason'], array() );
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$amount = (float) $amount_data['total'];

			$transaction_result = SftcyWordformPaymentAuthorizenet::create_transaction( $amount, $data_descriptor, $data_value, $form_id, $form_name, $buyer_email );

			if ( isset( $transaction_result['status'] ) && 'success' === $transaction_result['status'] ) {
				self::$output['status'] = 'success';
				self::$output           = array_merge( self::$output, $transaction_result );
			} else {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Authorize.Net payment could not be completed.', 'wordform-pro' );
				self::$output['comment'] = isset( $transaction_result['comment'] ) ? $transaction_result['comment'] : __( 'Unknown Authorize.Net error.', 'wordform-pro' );
				self::$output['reason']  = isset( $transaction_result['reason'] ) ? $transaction_result['reason'] : __( 'Authorize.Net payment failed.', 'wordform-pro' );
				self::wordform_log_payment_failure( 'authorizenet', 'charge', $form_id, self::$output['reason'], array( 'comment' => self::$output['comment'] ) );
			}

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


		/**
		 * Ajax Request
		 * Front end form submission by Users
		 * Sanitize - validate data
		 * Store form submission data into 'scwordform_submisson_forms_data' table
		 *
		 * @since 1.0.0
		 */
		public static function sc_wordform_created_form_submission() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			            
            // echo 'POST<pre>';
			// print_r( $_POST );			
			// echo '</pre>';
			
            // echo 'FILES<pre>';
			// print_r( $_FILES );
			// echo '</pre>';
			
			// exit();

			global $wpdb;
			self::$output     = array();
			$insert_data      = array();
			$wordform_id   = isset( $_POST['WordFormID'] ) ? sanitize_text_field( $_POST['WordFormID'] ) : '';
			$wordform_name = isset( $_POST['WordFormName'] ) ? sanitize_text_field( $_POST['WordFormName'] ) : '';	
			$gcaptcha_token = isset( $_POST['token'] ) ? sanitize_text_field( $_POST['token'] ) : '';
			$submission_validation_token = isset( $_POST['wordform_submission_validation_token'] ) ? sanitize_text_field( $_POST['wordform_submission_validation_token'] ) : '';

			// var_dump( $_POST['token'] );
			// var_dump( $gcaptcha_token );
			// exit();

			if ( isset( $wordform_id ) && ! empty( $wordform_id ) ) {
				$post_params   = isset( $_POST['wordform'][ $wordform_id ] )? $_POST['wordform'][ $wordform_id ] : [];    
				// Process File Upload Data Based On Available Upload Attributes
				if ( array_filter( $_FILES ) ) {
					$file_attributes = [ 'name', 'full_path', 'type', 'size', 'tmp_name', 'error' ];
					$files_info = [];
					foreach ( $file_attributes as $attribute ) {
						if ( isset( $_FILES['wordform'][ $attribute ][ $wordform_id ]['upload'] ) ) {
							foreach ( $_FILES['wordform'][ $attribute ][ $wordform_id ]['upload'] as $key => $values ) {
								$files_info[ $key ][ $attribute ] = $values['files'];
							}	
						}	
					}
                    // echo 'Files_INFO<pre>';
					// print_r( $files_info );
					// echo '</pre>';
				}

				// echo 'POST PARAMS<pre>';
				// print_r( $post_params );				
				// echo '</pre>';
                // Merge Uploaded Files Info ( $_FILES ) with POST params ( $_POST ) data fields before sanitizing & validation all together
				// If Files Info ( $_FILES ) not available then just keep POST params ( $_POST ) data fields
				if ( isset( $post_params['upload'] ) ) {
					foreach ( $post_params['upload'] as $key => $values ) {
						$post_params['upload'][ $key ] = isset( $files_info[ $key ] ) ? array_merge( $post_params['upload'][ $key ], $files_info[ $key ] ) : $post_params['upload'][ $key ];
					}
				}
				
				// echo 'POST PARAMS UPDATED AFTER MERGE WITH FILES<pre>';
				// print_r( $post_params );				
				// echo '</pre>';
				// exit(); 

				// Sanitize submission data               
				 $submission_sanitized_form_data = self::sc_wordform_front_end_submission_data_sanitize( $post_params );				
				// print_r( $submission_sanitized_form_data );				 				 
				// exit();

				$skip_validation_input_types = array();
				if ( self::wordform_is_valid_submission_validation_token( $submission_validation_token, $wordform_id ) ) {
					$skip_validation_input_types = array( 'captcha', 'gcaptcha', 'hcaptcha' );
				}

				$validation_result     = self::wordform_validate_sanitized_submission_data( $wordform_id, $submission_sanitized_form_data, $skip_validation_input_types );
				$validation_error_data = isset( $validation_result['errors'] ) ? $validation_result['errors'] : array();

				// When error found based on each input element validation
				if ( array_filter( $validation_error_data ) ) {
					self::$output['status']              = 'fail';
					self::$output['failMsg']             = '<div class="sc-wordform-submisson-fail-msg-div-wrapper">' . __( 'Input validation error.', 'wordform-pro' ) . '</div>';
					self::$output['validationAllData']   = isset( $validation_result['all'] ) ? $validation_result['all'] : array();
					self::$output['validationErrorData'] = $validation_error_data;					
				}
				// When Upload files data available
				else if ( isset( $submission_sanitized_form_data['upload'] ) && array_filter( $submission_sanitized_form_data['upload'] ) )	{
					$upload_results = SftcyWordformBase::wordform_upload_files( $submission_sanitized_form_data['upload'] );
					if ( ! $upload_results  ) {
						self::$output['status']          = 'fail';
						self::$output['failMsg']         = '<div class="sc-wordform-submisson-fail-msg-div-wrapper">' . __( 'Something went wrong with uploading.', 'wordform-pro' ) . '</div>';									
					}
					else {
						$submission_sanitized_form_data['upload'] = $upload_results;
					}
				}

				if ( ! isset( self::$output['status'] ) || self::$output['status'] !== 'fail' ) {
					
					// echo 'POST  PARAMS<pre>';
					// print_r( $post_params );
					// echo '</pre>';

					// echo 'ssubmisssion_sanitized_form_data<pre>';
					// print_r( $submission_sanitized_form_data );
					// echo '</pre>';

					// echo 'JSON ENCODED DATA FOR DB<pre>';
					// print_r( wp_json_encode( $submission_sanitized_form_data ) );
					// echo '</pre>';
					
					// exit();
										
					$wordform_submission_data_json       = wp_json_encode( $submission_sanitized_form_data );
					$insert_data['form_id']              = $wordform_id;
					$insert_data['submission_data']      = $wordform_submission_data_json;
					$submission_user_info_arr            = self::sc_wordform_form_submission_users_data();
					$insert_data['submission_user_data'] = wp_json_encode( $submission_user_info_arr );
					$insert_record                       = $wpdb->insert( $wpdb->prefix . SftcyWordformBase::$sc_wordform_submission_tbl, $insert_data );
					if ( isset( $insert_record ) && $insert_record ) {
						$last_inserted_id = $wpdb->insert_id;
						self::$output['status']               = 'success';
						self::$output['insertSubmissionData'] = true;
						// self::$output['successMsg']           = '<div class="sc-wordform-submission-success-msg-div-wrapper">We have received your message.</div>';
						self::$output['successMsg'] = '<div class="sc-wordform-submission-success-msg-div-wrapper">' . SftcyWordformBase::wordform_get_form_submission_success_message( $wordform_id ) . '</div>';
						self::wordform_delete_submission_validation_token( $submission_validation_token );

						// Send Email if true - on each form submission
						$insert_data['form_name'] = $wordform_name;
						SftcyWordformBase::sc_wordform_send_email_on_form_submission_by_users( $insert_data );
						self::wordform_record_coupon_usage_from_submission( $wordform_id, $last_inserted_id, $submission_sanitized_form_data );

						// Send Form Submission data to Configured & Connected Active Applications
						self::$output['sentFormsDataIntoConnectedApps'] = self::wordform_send_form_data_to_connected_applications( $submission_sanitized_form_data, $wordform_id, $last_inserted_id );
						

						// Silently Delete Captcha value on Success Submit Form Complete
						if ( ! empty( SftcyWordformFormValidation::$wordform_captcha_session_name ) ) {
							self::$output['deleteUsedCaptcha'] = delete_transient( SftcyWordformFormValidation::$wordform_captcha_session_name );
						}
					} 
					else {
						self::$output['status']               = 'fail';
						self::$output['insertSubmissionData'] = false;
						self::$output['failMsg']              = '<div class="sc-wordform-submisson-fail-msg-div-wrapper">' . __( 'Something went wrong with saving form data, please try again.', 'wordform-pro' ) . '</div>';
					}
				}
				else {
					self::$output['status']               = 'fail';
					self::$output['insertSubmissionData'] = false;
					self::$output['failMsg']              = '<div class="sc-wordform-submisson-fail-msg-div-wrapper">' . __( 'Something went wrong, please try again.', 'wordform-pro' ) . '</div>';
				}
			}

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

		/**
		 * Send Forms data to Connected Applications
		 * @param array $submission_sanitized_form_data - all form fields sumbmitted data by user - required processing to find form fields submitted values
		 * @param string $wordform_id - WordForm ID which wordform data will send to connected applications
		 * Send Forms data to applications which 'configured_status' & 'connection_status' active only in DB Table 'scwordform_configured_applications'
		 * @return mixed boolean | Array
		 */
		public static function wordform_send_form_data_to_connected_applications( $submission_sanitized_form_data = [], $wordform_id = '', $last_inserted_id = 0 ) {
			// return true;
			if ( ! array_filter( $submission_sanitized_form_data ) || empty( $wordform_id ) || $last_inserted_id <= 0 ) {
				return false;
			}
			$sending_data_to_app_info = [];
			SftcyWordformFormSubmission::$sc_wordform_return_processed_raw_data = true; // set true to get raw form fields plain texts data - no html tags
			SftcyWordformFormSubmission::$sc_wordform_submission_array_data = $submission_sanitized_form_data;
			SftcyWordformFormSubmission::$sc_wordform_processed_forms_raw_data = []; // Reset Raw Processed Data Holder Variable
			$forms_data = SftcyWordformFormSubmission::sc_wordform_process_submission_data();
			SftcyWordformFormSubmission::$sc_wordform_return_processed_raw_data = false; // Change back to false when done so it does return normal data format
			$fields_values_arr = array_column( $forms_data, 'formFieldValues' ); // $fields_value_arr will be like [ 'John', 'test@email.com', '65928747455' ]
			$slack_message_payload = self::wordform_prepare_slack_message_payload( $forms_data, $wordform_id, $last_inserted_id );
			$custom_webhook_json_payload = self::wordform_prepare_custom_webhook_json_payload( $forms_data, $wordform_id, $last_inserted_id );

			global $wpdb;
			$configured_table  = $wpdb->prefix . SftcyWordformBase::$sc_wordform_configured_application_tbl;
			$connect_table     = $wpdb->prefix . SftcyWordformBase::$sc_wordform_connects_tbl;
			$status = 'active';
			// Application GoogleSheet
			//$application_slug = 'googlesheet';
			/*$query_results     = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i AS ca, %i AS cd WHERE 
																		ca.id = cd.configured_application_tbl_id AND ca.application_slug = %s AND 
																		ca.configured_status = %s AND cd.connection_status = %s AND cd.wordform_id = %s LIMIT 1', 
																		array( $configured_table, $connect_table, $application_slug, $status, $status, $wordform_id ) ), ARRAY_A );	*/
            // Get all connected active applications to send forms data																		
			$query_results     = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i AS ca, %i AS cd WHERE 
																		ca.id = cd.configured_application_tbl_id AND 
																		ca.configured_status = %s AND 
																		cd.connection_status = %s AND 
																		cd.wordform_id = %s ORDER BY ca.application_slug', 
																		array( $configured_table, $connect_table, $status, $status, $wordform_id ) ), ARRAY_A );	

																		
			//  echo '<pre>';
			// print_r( $query_results );
			//  print_r( $forms_data );
			//  print_r( $fields_values_arr );
			//  echo '</pre>';
			//  exit();																		

			if ( $query_results && array_filter( $query_results ) ) {
				   foreach ( $query_results as $connected_app ) {
						$application_slug = isset( $connected_app['application_slug'] ) ? sanitize_key( $connected_app['application_slug'] ) : '';
						try {
							switch ( $application_slug ) {
							case 'googlesheet':
								$connection_info = isset( $connected_app['connection_info'] )? json_decode( $connected_app['connection_info'], true ) : '';
								if ( isset( $connection_info['spreadsheetId'] ) && ! empty( $connection_info['spreadsheetId'] ) ) {
									$spreadsheet_id = $connection_info['spreadsheetId'];
									$sending_data_to_app_info['googlesheet'] = SftcyWordformConnectGooglesheet::wordform_google_sheet_insert_append_columns_fields( $spreadsheet_id, $fields_values_arr );
								}
								break;
							case 'googlecalendar':
								$connection_info = isset( $connected_app['connection_info'] ) ? json_decode( $connected_app['connection_info'], true ) : [];
								$configured_info = isset( $connected_app['configured_info'] ) ? json_decode( $connected_app['configured_info'], true ) : [];
								$googlecalendar_info = [
									'calendarId' => '',
								];

								if ( isset( $configured_info['calendarId'] ) && ! empty( $configured_info['calendarId'] ) ) {
									$googlecalendar_info['calendarId'] = $configured_info['calendarId'];
								} elseif ( isset( $connection_info['calendarId'] ) && ! empty( $connection_info['calendarId'] ) ) {
									$googlecalendar_info['calendarId'] = $connection_info['calendarId'];
								}

								$sending_data_to_app_info['googlecalendar'] = SftcyWordformConnectGooglecalendar::wordform_send_forms_data_into_googlecalendar( $forms_data, $googlecalendar_info );
								break;

							case 'zapier':
								$connection_info = isset( $connected_app['configured_info'] )? json_decode( $connected_app['configured_info'], true ) : '';								
								if ( isset( $connection_info['webhookPostUrl'] ) && ! empty( $connection_info['webhookPostUrl'] ) ) {
									$sending_data_to_app_info['zapier'] = SftcyWordformConnectZapier::wordform_send_forms_data_into_zapier_post_webhook( $fields_values_arr, $connection_info['webhookPostUrl'] );
								}
								break;

							case 'slack':
								$connection_info = isset( $connected_app['connection_info'] ) ? json_decode( $connected_app['connection_info'], true ) : [];
								$configured_info = isset( $connected_app['configured_info'] ) ? json_decode( $connected_app['configured_info'], true ) : [];
								$webhook_post_url = '';
								if ( isset( $configured_info['webhookPostUrl'] ) && ! empty( $configured_info['webhookPostUrl'] ) ) {
									$webhook_post_url = $configured_info['webhookPostUrl'];
								} else if ( isset( $connection_info['webhookPostUrl'] ) && ! empty( $connection_info['webhookPostUrl'] ) ) {
									$webhook_post_url = $connection_info['webhookPostUrl'];
								}

								if ( ! empty( $webhook_post_url ) ) {
									$sending_data_to_app_info['slack'] = SftcyWordformConnectSlack::wordform_send_forms_data_into_slack_webhook( $slack_message_payload, $webhook_post_url );
								} else {
									$sending_data_to_app_info['slack'] = [
										'applicationSlug' => 'slack',
										'status'          => 'fail',
										'reason'          => 'Slack Webhook URL missing.',
										'comment'         => 'Slack Webhook URL not found for this connection.',
									];
								}
								break;

							case 'mailchimp':
								$connection_info = isset( $connected_app['connection_info'] ) ? json_decode( $connected_app['connection_info'], true ) : [];
								$configured_info = isset( $connected_app['configured_info'] ) ? json_decode( $connected_app['configured_info'], true ) : [];
								$mailchimp_info  = [
									'apiKey'     => '',
									'audienceId' => '',
									'apiServer'  => '',
								];

								if ( isset( $configured_info['apiKey'] ) && ! empty( $configured_info['apiKey'] ) ) {
									$mailchimp_info['apiKey'] = $configured_info['apiKey'];
								} elseif ( isset( $connection_info['apiKey'] ) && ! empty( $connection_info['apiKey'] ) ) {
									$mailchimp_info['apiKey'] = $connection_info['apiKey'];
								}

								if ( isset( $configured_info['audienceId'] ) && ! empty( $configured_info['audienceId'] ) ) {
									$mailchimp_info['audienceId'] = $configured_info['audienceId'];
								} elseif ( isset( $connection_info['audienceId'] ) && ! empty( $connection_info['audienceId'] ) ) {
									$mailchimp_info['audienceId'] = $connection_info['audienceId'];
								}

								if ( isset( $configured_info['apiServer'] ) && ! empty( $configured_info['apiServer'] ) ) {
									$mailchimp_info['apiServer'] = $configured_info['apiServer'];
								} elseif ( isset( $connection_info['apiServer'] ) && ! empty( $connection_info['apiServer'] ) ) {
									$mailchimp_info['apiServer'] = $connection_info['apiServer'];
								}

								$sending_data_to_app_info['mailchimp'] = SftcyWordformConnectMailchimp::wordform_send_forms_data_into_mailchimp_audience( $forms_data, $mailchimp_info );
								break;

							case 'mailerlite':
								$connection_info = isset( $connected_app['connection_info'] ) ? json_decode( $connected_app['connection_info'], true ) : [];
								$configured_info = isset( $connected_app['configured_info'] ) ? json_decode( $connected_app['configured_info'], true ) : [];
								$mailerlite_info = [
									'apiToken' => '',
									'groupId'  => '',
								];

								if ( isset( $configured_info['apiToken'] ) && ! empty( $configured_info['apiToken'] ) ) {
									$mailerlite_info['apiToken'] = $configured_info['apiToken'];
								} elseif ( isset( $connection_info['apiToken'] ) && ! empty( $connection_info['apiToken'] ) ) {
									$mailerlite_info['apiToken'] = $connection_info['apiToken'];
								}

								if ( isset( $configured_info['groupId'] ) && ! empty( $configured_info['groupId'] ) ) {
									$mailerlite_info['groupId'] = $configured_info['groupId'];
								} elseif ( isset( $connection_info['groupId'] ) && ! empty( $connection_info['groupId'] ) ) {
									$mailerlite_info['groupId'] = $connection_info['groupId'];
								}

								$sending_data_to_app_info['mailerlite'] = SftcyWordformConnectMailerlite::wordform_send_forms_data_into_mailerlite( $forms_data, $mailerlite_info );
								break;

							case 'airtable':
								$connection_info = isset( $connected_app['connection_info'] ) ? json_decode( $connected_app['connection_info'], true ) : [];
								$configured_info = isset( $connected_app['configured_info'] ) ? json_decode( $connected_app['configured_info'], true ) : [];
								$airtable_info   = [
									'accessToken' => '',
									'baseId'      => '',
									'tableName'   => '',
								];

								if ( isset( $configured_info['accessToken'] ) && ! empty( $configured_info['accessToken'] ) ) {
									$airtable_info['accessToken'] = $configured_info['accessToken'];
								} elseif ( isset( $connection_info['accessToken'] ) && ! empty( $connection_info['accessToken'] ) ) {
									$airtable_info['accessToken'] = $connection_info['accessToken'];
								}

								if ( isset( $configured_info['baseId'] ) && ! empty( $configured_info['baseId'] ) ) {
									$airtable_info['baseId'] = $configured_info['baseId'];
								} elseif ( isset( $connection_info['baseId'] ) && ! empty( $connection_info['baseId'] ) ) {
									$airtable_info['baseId'] = $connection_info['baseId'];
								}

								if ( isset( $configured_info['tableName'] ) && ! empty( $configured_info['tableName'] ) ) {
									$airtable_info['tableName'] = $configured_info['tableName'];
								} elseif ( isset( $connection_info['tableName'] ) && ! empty( $connection_info['tableName'] ) ) {
									$airtable_info['tableName'] = $connection_info['tableName'];
								}

								$sending_data_to_app_info['airtable'] = SftcyWordformConnectAirtable::wordform_send_forms_data_into_airtable( $forms_data, $airtable_info );
								break;

							case 'brevo':
								$connection_info = isset( $connected_app['connection_info'] ) ? json_decode( $connected_app['connection_info'], true ) : [];
								$configured_info = isset( $connected_app['configured_info'] ) ? json_decode( $connected_app['configured_info'], true ) : [];
								$brevo_info      = [
									'apiKey' => '',
									'listId' => 0,
								];

								if ( isset( $configured_info['apiKey'] ) && ! empty( $configured_info['apiKey'] ) ) {
									$brevo_info['apiKey'] = $configured_info['apiKey'];
								} elseif ( isset( $connection_info['apiKey'] ) && ! empty( $connection_info['apiKey'] ) ) {
									$brevo_info['apiKey'] = $connection_info['apiKey'];
								}

								if ( isset( $configured_info['listId'] ) && ! empty( $configured_info['listId'] ) ) {
									$brevo_info['listId'] = absint( $configured_info['listId'] );
								} elseif ( isset( $connection_info['listId'] ) && ! empty( $connection_info['listId'] ) ) {
									$brevo_info['listId'] = absint( $connection_info['listId'] );
								}

								$sending_data_to_app_info['brevo'] = SftcyWordformConnectBrevo::wordform_send_forms_data_into_brevo( $forms_data, $brevo_info );
								break;

							case 'hubspot':
								$connection_info = isset( $connected_app['connection_info'] ) ? json_decode( $connected_app['connection_info'], true ) : [];
								$configured_info = isset( $connected_app['configured_info'] ) ? json_decode( $connected_app['configured_info'], true ) : [];
								$hubspot_info    = [
									'privateAppToken' => '',
								];

								if ( isset( $configured_info['privateAppToken'] ) && ! empty( $configured_info['privateAppToken'] ) ) {
									$hubspot_info['privateAppToken'] = $configured_info['privateAppToken'];
								} elseif ( isset( $connection_info['privateAppToken'] ) && ! empty( $connection_info['privateAppToken'] ) ) {
									$hubspot_info['privateAppToken'] = $connection_info['privateAppToken'];
								}

								$sending_data_to_app_info['hubspot'] = SftcyWordformConnectHubspot::wordform_send_forms_data_into_hubspot( $forms_data, $hubspot_info );
								break;

							case 'make':
								$connection_info = isset( $connected_app['connection_info'] ) ? json_decode( $connected_app['connection_info'], true ) : [];
								$configured_info = isset( $connected_app['configured_info'] ) ? json_decode( $connected_app['configured_info'], true ) : [];
								$webhook_post_url = '';
								if ( isset( $configured_info['webhookPostUrl'] ) && ! empty( $configured_info['webhookPostUrl'] ) ) {
									$webhook_post_url = $configured_info['webhookPostUrl'];
								} elseif ( isset( $connection_info['webhookPostUrl'] ) && ! empty( $connection_info['webhookPostUrl'] ) ) {
									$webhook_post_url = $connection_info['webhookPostUrl'];
								}

								if ( ! empty( $webhook_post_url ) ) {
									$sending_data_to_app_info['make'] = SftcyWordformConnectMake::wordform_send_forms_data_into_make_post_webhook( $custom_webhook_json_payload, $webhook_post_url );
								} else {
									$sending_data_to_app_info['make'] = [
										'applicationSlug' => 'make',
										'status'          => 'fail',
										'reason'          => 'Make Webhook URL missing.',
										'comment'         => 'Make Webhook URL not found for this connection.',
									];
								}
								break;

							case 'activecampaign':
								$connection_info = isset( $connected_app['connection_info'] ) ? json_decode( $connected_app['connection_info'], true ) : [];
								$configured_info = isset( $connected_app['configured_info'] ) ? json_decode( $connected_app['configured_info'], true ) : [];
								$activecampaign_info = [
									'apiBaseUrl' => '',
									'apiKey'     => '',
									'listId'     => 0,
								];

								if ( isset( $configured_info['apiBaseUrl'] ) && ! empty( $configured_info['apiBaseUrl'] ) ) {
									$activecampaign_info['apiBaseUrl'] = $configured_info['apiBaseUrl'];
								} elseif ( isset( $connection_info['apiBaseUrl'] ) && ! empty( $connection_info['apiBaseUrl'] ) ) {
									$activecampaign_info['apiBaseUrl'] = $connection_info['apiBaseUrl'];
								}

								if ( isset( $configured_info['apiKey'] ) && ! empty( $configured_info['apiKey'] ) ) {
									$activecampaign_info['apiKey'] = $configured_info['apiKey'];
								} elseif ( isset( $connection_info['apiKey'] ) && ! empty( $connection_info['apiKey'] ) ) {
									$activecampaign_info['apiKey'] = $connection_info['apiKey'];
								}

								if ( isset( $configured_info['listId'] ) && ! empty( $configured_info['listId'] ) ) {
									$activecampaign_info['listId'] = absint( $configured_info['listId'] );
								} elseif ( isset( $connection_info['listId'] ) && ! empty( $connection_info['listId'] ) ) {
									$activecampaign_info['listId'] = absint( $connection_info['listId'] );
								}

								$sending_data_to_app_info['activecampaign'] = SftcyWordformConnectActivecampaign::wordform_send_forms_data_into_activecampaign( $forms_data, $activecampaign_info );
								break;

							case 'salesforce':
								$sending_data_to_app_info['salesforce'] = SftcyWordformConnectSalesforce::wordform_send_forms_data_into_salesforce( $forms_data );
								break;

							case 'zohocrm':
								$sending_data_to_app_info['zohocrm'] = SftcyWordformConnectZohocrm::wordform_send_forms_data_into_zohocrm( $forms_data );
								break;

							case 'customwebhook':
								$connection_info = isset( $connected_app['connection_info'] ) ? json_decode( $connected_app['connection_info'], true ) : [];
								$configured_info = isset( $connected_app['configured_info'] ) ? json_decode( $connected_app['configured_info'], true ) : [];
								$webhook_post_url = '';
								// Always prefer latest configured URL from configured_info.
								if ( isset( $configured_info['webhookPostUrl'] ) && ! empty( $configured_info['webhookPostUrl'] ) ) {
									$webhook_post_url = $configured_info['webhookPostUrl'];
								} else if ( isset( $connection_info['webhookPostUrl'] ) && ! empty( $connection_info['webhookPostUrl'] ) ) {
									$webhook_post_url = $connection_info['webhookPostUrl'];
								}

								if ( ! empty( $webhook_post_url ) ) {
									$sending_data_to_app_info['customwebhook'] = SftcyWordformConnectCustomWebhook::wordform_send_forms_data_into_custom_post_webhook( $custom_webhook_json_payload, $webhook_post_url );
								} else {
									$sending_data_to_app_info['customwebhook'] = [
										'applicationSlug' => 'customwebhook',
										'status'          => 'fail',
										'reason'          => 'Custom Webhook URL missing.',
										'comment'         => 'Custom Webhook URL not found for this connection.',
									];
								}
								break;
							} // switch
						} catch ( Throwable $throwable ) {
							if ( ! empty( $application_slug ) ) {
								$sending_data_to_app_info[ $application_slug ] = [
									'applicationSlug' => $application_slug,
									'status'          => 'fail',
									'reason'          => 'Application send process interrupted with exception.',
									'comment'         => 'WordForm isolated the app failure and continued processing the submission.',
									'exceptionType'   => get_class( $throwable ),
									'exceptionMsg'    => substr( sanitize_textarea_field( $throwable->getMessage() ), 0, 500 ),
								];
							}
						}
					} // foreach
			$sending_data_to_app_info['dbStoredStatus'] = self::wordform_save_third_party_application_sending_forms_data_report( $sending_data_to_app_info, $last_inserted_id );		
			return $sending_data_to_app_info;		
			}

			return false;
		}

		/**
		 * Add into DB records
		 * Sending forms submission data into third-party applications like Google, Zaper etc. 
		 * @return boolean
		 */
		public static function wordform_save_third_party_application_sending_forms_data_report( $sending_data_to_app_info = [], $last_inserted_id = 0 ) {
			if ( ! array_filter( $sending_data_to_app_info ) || $last_inserted_id <= 0 ) {
				return false;
			}
			global $wpdb;
			$table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_submission_tbl;
			$where = [ 'id' => $last_inserted_id ];
			$data['data_send_info'] = json_encode( $sending_data_to_app_info );								
			return $wpdb->update( $table, $data, $where );
		}

		/**
		 * Build JSON payload for custom webhook endpoint.
		 * This keeps webhook payload self-descriptive and app-friendly.
		 *
		 * @param array  $forms_data Processed fields data.
		 * @param string $wordform_id WordForm ID.
		 * @param int    $last_inserted_id Submission table record ID.
		 * @return array
		 */
		public static function wordform_prepare_custom_webhook_json_payload( $forms_data = [], $wordform_id = '', $last_inserted_id = 0 ) {
			if ( ! is_array( $forms_data ) || ! array_filter( $forms_data ) || empty( $wordform_id ) || $last_inserted_id <= 0 ) {
				return [];
			}

			$form_name  = '';
			$form_query = SftcyWordformBase::sc_wordform_db_query( $wordform_id );
			if ( $form_query && isset( $form_query[0]['form_name'] ) && ! empty( $form_query[0]['form_name'] ) ) {
				$form_name = sanitize_text_field( $form_query[0]['form_name'] );
			}

			$fields     = [];
			$fields_map = [];
			foreach ( $forms_data as $index => $field_info ) {
				$field_label = isset( $field_info['formLabelName'] ) && ! empty( $field_info['formLabelName'] ) ? sanitize_text_field( $field_info['formLabelName'] ) : 'Field ' . ( $index + 1 );
				$field_value = isset( $field_info['formFieldValues'] ) ? (string) $field_info['formFieldValues'] : '';
				$field_type  = isset( $field_info['formFieldType'] ) ? sanitize_key( $field_info['formFieldType'] ) : '';
				$field_raw   = isset( $field_info['formRawValue'] ) ? (string) $field_info['formRawValue'] : '';
				$field_admin = isset( $field_info['formAdminLabel'] ) ? sanitize_key( $field_info['formAdminLabel'] ) : '';

				$fields[] = [
					'label'      => $field_label,
					'adminLabel' => $field_admin,
					'type'       => $field_type,
					'value'      => $field_value,
					'rawValue'   => $field_raw,
				];

				$field_key = sanitize_key( $field_label );
				if ( empty( $field_key ) ) {
					$field_key = 'field_' . ( $index + 1 );
				}
				if ( isset( $fields_map[ $field_key ] ) ) {
					$field_key = $field_key . '_' . ( $index + 1 );
				}
				$fields_map[ $field_key ] = $field_value;
			}

			return [
				'event'           => 'wordform.form_submission',
				'applicationSlug' => 'customwebhook',
				'submission'      => [
					'id'          => $last_inserted_id,
					'submittedAt' => current_time( 'mysql' ),
				],
				'wordform'        => [
					'id'   => $wordform_id,
					'name' => $form_name,
				],
				'fields'          => $fields,
				'fieldsMap'       => $fields_map,
			];
		}

		/**
		 * Build Slack message payload for incoming webhook.
		 *
		 * @param array  $forms_data Processed fields data.
		 * @param string $wordform_id WordForm ID.
		 * @param int    $last_inserted_id Submission table record ID.
		 * @return array
		 */
		public static function wordform_prepare_slack_message_payload( $forms_data = [], $wordform_id = '', $last_inserted_id = 0 ) {
			if ( ! is_array( $forms_data ) || ! array_filter( $forms_data ) || empty( $wordform_id ) || $last_inserted_id <= 0 ) {
				return [];
			}

			$form_name  = '';
			$form_query = SftcyWordformBase::sc_wordform_db_query( $wordform_id );
			if ( $form_query && isset( $form_query[0]['form_name'] ) && ! empty( $form_query[0]['form_name'] ) ) {
				$form_name = sanitize_text_field( $form_query[0]['form_name'] );
			}

			$message_lines = [];
			$blocks = [
				[
					'type' => 'header',
					'text' => [
						'type' => 'plain_text',
						'text' => 'WordForm Submission',
					],
				],
				[
					'type' => 'section',
					'fields' => [
						[
							'type' => 'mrkdwn',
							'text' => '*Form:*\n' . $form_name,
						],
						[
							'type' => 'mrkdwn',
							'text' => '*Submission ID:*\n' . $last_inserted_id,
						],
					],
				],
			];

			foreach ( $forms_data as $field_info ) {
				$field_label = isset( $field_info['formLabelName'] ) ? sanitize_text_field( $field_info['formLabelName'] ) : 'Field';
				$field_value = isset( $field_info['formFieldValues'] ) ? sanitize_textarea_field( (string) $field_info['formFieldValues'] ) : '';
				$message_lines[] = $field_label . ': ' . $field_value;
				$blocks[] = [
					'type' => 'section',
					'fields' => [
						[
							'type' => 'mrkdwn',
							'text' => '*' . $field_label . '*',
						],
						[
							'type' => 'mrkdwn',
							'text' => $field_value,
						],
					],
				];
			}

			return [
				'text'   => 'WordForm Submission - ' . $form_name . PHP_EOL . implode( PHP_EOL, $message_lines ),
				'blocks' => $blocks,
			];
		}

		/**
		 * Sanitize users submission data
		 * modify reference submission data to be sanitized
		 */
		public static function sc_wordform_front_end_submission_data_sanitize( &$submission_form_data ) {
			// print_r( $submission_form_data );			 
			// exit;
			if ( isset( $submission_form_data ) && array_filter( $submission_form_data ) ) {
				foreach ( $submission_form_data as $input_type => &$input_data ) {
					switch ( $input_type ) {
						case 'text':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_text_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'number':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_text_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'textarea':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_textarea_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'richeditor':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['label'] ) ) {
									$input['label'] = sanitize_text_field( $input['label'] );
								}
								if ( isset( $input['placeholderText'] ) ) {
									$input['placeholderText'] = sanitize_text_field( $input['placeholderText'] );
								}
								if ( isset( $input['minHeight'] ) ) {
									$input['minHeight'] = max( 140, min( 420, absint( $input['minHeight'] ) ) );
								}
								if ( isset( $input['values'] ) && is_array( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											$allowed_html = wp_kses_allowed_html( 'post' );
											$data         = wp_kses( (string) $data, $allowed_html );
											$plain_text   = trim( wp_strip_all_tags( html_entity_decode( $data, ENT_QUOTES, get_bloginfo( 'charset' ) ) ) );
											return '' !== $plain_text ? $data : '';
										},
										$input['values']
									);
								}
							}
							break;
						case 'radio':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_text_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'checkbox':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_text_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'select':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_text_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'url':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_url( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'date':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['defaultDate'] ) ) {
									$input['defaultDate'] = sanitize_text_field( $input['defaultDate'] );
								}
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_text_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'time':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['label'] ) ) {
									$input['label'] = sanitize_text_field( $input['label'] );
								}
								if ( isset( $input['placeholderText'] ) ) {
									$input['placeholderText'] = sanitize_text_field( $input['placeholderText'] );
								}
								if ( isset( $input['defaultTime'] ) ) {
									$input['defaultTime'] = preg_match( '/^\d{2}:\d{2}$/', (string) $input['defaultTime'] ) ? sanitize_text_field( $input['defaultTime'] ) : '';
								}
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return preg_match( '/^\d{2}:\d{2}$/', (string) $data ) ? sanitize_text_field( $data ) : '';
										},
										$input['values']
									);
								}
							}
							break;
						case 'email':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_email( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'address':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['label'] ) ) {
									$input['label'] = sanitize_text_field( $input['label'] );
								}
								if ( isset( $input['values'] ) && is_array( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_text_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'maskinput':
						case 'hidden':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['label'] ) ) {
									$input['label'] = sanitize_text_field( $input['label'] );
								}
								if ( isset( $input['pattern'] ) ) {
									$input['pattern'] = sanitize_text_field( $input['pattern'] );
								}
								if ( isset( $input['defaultValue'] ) ) {
									$input['defaultValue'] = sanitize_text_field( $input['defaultValue'] );
								}
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_text_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'captcha':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['values'] ) && array_filter( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_text_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'upload':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['label'] ) ) {
									$input['label'] = sanitize_text_field( $input['label'] );
								}
								if ( isset( $input['selectFileLabel'] ) ) {
									$input['selectFileLabel'] = sanitize_text_field( $input['selectFileLabel'] );
								}
							}
							break;
						case 'rating':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['label'] ) ) {
									$input['label'] = sanitize_text_field( $input['label'] );
								}
								if ( isset( $input['scale'] ) ) {
									$input['scale'] = max( 3, min( 10, absint( $input['scale'] ) ) );
								}
								if ( isset( $input['lowText'] ) ) {
									$input['lowText'] = sanitize_text_field( $input['lowText'] );
								}
								if ( isset( $input['highText'] ) ) {
									$input['highText'] = sanitize_text_field( $input['highText'] );
								}
								if ( isset( $input['values'] ) && is_array( $input['values'] ) ) {
									$rating_scale = isset( $input['scale'] ) ? max( 3, min( 10, absint( $input['scale'] ) ) ) : 5;
									$input['values'] = array_map(
										function ( $data ) use ( $rating_scale ) {
											$rating_value = absint( $data );
											return ( $rating_value >= 1 && $rating_value <= $rating_scale ) ? (string) $rating_value : '';
										},
										$input['values']
									);
								}
							}
							break;
						case 'likert':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['label'] ) ) {
									$input['label'] = sanitize_text_field( $input['label'] );
								}
								$input['rowLabels'] = isset( $input['rowLabels'] ) && is_array( $input['rowLabels'] )
									? array_values(
										array_filter(
											array_map(
												function ( $data ) {
													return sanitize_text_field( $data );
												},
												$input['rowLabels']
											)
										)
									)
									: array();
								$input['columnLabels'] = isset( $input['columnLabels'] ) && is_array( $input['columnLabels'] )
									? array_values(
										array_filter(
											array_map(
												function ( $data ) {
													return sanitize_text_field( $data );
												},
												$input['columnLabels']
											)
										)
									)
									: array();
								$allowed_columns = $input['columnLabels'];
								if ( isset( $input['values'] ) && is_array( $input['values'] ) ) {
									$sanitized_values = array();
									foreach ( $input['values'] as $row_index => $row_value ) {
										$row_value = sanitize_text_field( $row_value );
										$sanitized_values[ $row_index ] = in_array( $row_value, $allowed_columns, true ) ? $row_value : '';
									}
									$input['values'] = $sanitized_values;
								}
							}
							break;
						case 'signature':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['label'] ) ) {
									$input['label'] = sanitize_text_field( $input['label'] );
								}
								if ( isset( $input['clearButtonText'] ) ) {
									$input['clearButtonText'] = sanitize_text_field( $input['clearButtonText'] );
								}
								if ( isset( $input['canvasHeight'] ) ) {
									$input['canvasHeight'] = max( 120, min( 360, absint( $input['canvasHeight'] ) ) );
								}
								if ( isset( $input['values'] ) && is_array( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											$data = trim( (string) $data );
											if ( preg_match( '/^data:image\/png;base64,[A-Za-z0-9+\/=]+$/', $data ) ) {
												return $data;
											}
											return '';
										},
										$input['values']
									);
								}
							}
							break;
						case 'gdpr':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['label'] ) ) {
									$input['label'] = sanitize_text_field( $input['label'] );
								}
								if ( isset( $input['gdprConsentText'] ) ) {
									$input['gdprConsentText'] = sanitize_text_field( $input['gdprConsentText'] );
								}
								if ( isset( $input['gdprPolicyUrl'] ) ) {
									$input['gdprPolicyUrl'] = esc_url_raw( $input['gdprPolicyUrl'] );
								}
								if ( isset( $input['values'] ) && is_array( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_text_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
						case 'payment_item':
						case 'payment_coupon':
						case 'payment_method':
						case 'payment_custom_amount':
						case 'payment_quantity':
						case 'payment_summary':
						case 'stripe':
						case 'paypal':
						case 'square':
						case 'authorizenet':
							foreach ( $input_data as $key => &$input ) {
								if ( isset( $input['label'] ) ) {
									$input['label'] = sanitize_text_field( $input['label'] );
								}
								if ( isset( $input['description'] ) ) {
									$input['description'] = sanitize_text_field( $input['description'] );
								}
								if ( isset( $input['placeholderText'] ) ) {
									$input['placeholderText'] = sanitize_text_field( $input['placeholderText'] );
								}
								if ( isset( $input['applyButtonText'] ) ) {
									$input['applyButtonText'] = sanitize_text_field( $input['applyButtonText'] );
								}
								if ( isset( $input['removeButtonText'] ) ) {
									$input['removeButtonText'] = sanitize_text_field( $input['removeButtonText'] );
								}
								if ( isset( $input['invalidMessage'] ) ) {
									$input['invalidMessage'] = sanitize_text_field( $input['invalidMessage'] );
								}
								if ( isset( $input['appliedMessage'] ) ) {
									$input['appliedMessage'] = sanitize_text_field( $input['appliedMessage'] );
								}
								if ( isset( $input['couponCode'] ) ) {
									$input['couponCode'] = strtoupper( sanitize_text_field( $input['couponCode'] ) );
								}
								if ( isset( $input['couponId'] ) ) {
									$input['couponId'] = absint( $input['couponId'] );
								}
								if ( isset( $input['discountAmount'] ) ) {
									$input['discountAmount'] = sanitize_text_field( $input['discountAmount'] );
								}
								if ( isset( $input['paymentStatus'] ) ) {
									$input['paymentStatus'] = sanitize_text_field( $input['paymentStatus'] );
								}
								if ( isset( $input['paymentIntentId'] ) ) {
									$input['paymentIntentId'] = sanitize_text_field( $input['paymentIntentId'] );
								}
								if ( isset( $input['paymentMethodId'] ) ) {
									$input['paymentMethodId'] = sanitize_text_field( $input['paymentMethodId'] );
								}
								if ( isset( $input['orderId'] ) ) {
									$input['orderId'] = sanitize_text_field( $input['orderId'] );
								}
								if ( isset( $input['captureId'] ) ) {
									$input['captureId'] = sanitize_text_field( $input['captureId'] );
								}
								if ( isset( $input['payerId'] ) ) {
									$input['payerId'] = sanitize_text_field( $input['payerId'] );
								}
								if ( isset( $input['paymentCurrency'] ) ) {
									$input['paymentCurrency'] = sanitize_text_field( $input['paymentCurrency'] );
								}
								if ( isset( $input['paymentId'] ) ) {
									$input['paymentId'] = sanitize_text_field( $input['paymentId'] );
								}
								if ( isset( $input['sourceId'] ) ) {
									$input['sourceId'] = sanitize_text_field( $input['sourceId'] );
								}
								if ( isset( $input['cardBrand'] ) ) {
									$input['cardBrand'] = sanitize_text_field( $input['cardBrand'] );
								}
								if ( isset( $input['last4'] ) ) {
									$input['last4'] = sanitize_text_field( $input['last4'] );
								}
								if ( isset( $input['receiptUrl'] ) ) {
									$input['receiptUrl'] = esc_url_raw( $input['receiptUrl'] );
								}
								if ( isset( $input['transactionId'] ) ) {
									$input['transactionId'] = sanitize_text_field( $input['transactionId'] );
								}
								if ( isset( $input['responseCode'] ) ) {
									$input['responseCode'] = sanitize_text_field( $input['responseCode'] );
								}
								if ( isset( $input['authCode'] ) ) {
									$input['authCode'] = sanitize_text_field( $input['authCode'] );
								}
								if ( isset( $input['accountNumber'] ) ) {
									$input['accountNumber'] = sanitize_text_field( $input['accountNumber'] );
								}
								if ( isset( $input['accountType'] ) ) {
									$input['accountType'] = sanitize_text_field( $input['accountType'] );
								}
								if ( isset( $input['values'] ) && is_array( $input['values'] ) ) {
									$input['values'] = array_map(
										function ( $data ) {
											return sanitize_text_field( $data );
										},
										$input['values']
									);
								}
							}
							break;
					} // switch
				} // foreach
			}
			return $submission_form_data;
		}

		/**
		 * Collect visited user information data
		 * return - array
		 * since 1.0.0
		 */
		public static function sc_wordform_form_submission_users_data() {
			$user_visited_target_info                    = array();
			$user_visited_target_info['HTTP_HOST']       = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
			$user_visited_target_info['HTTP_USER_AGENT'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
			$user_visited_target_info['SERVER_ADDR']     = isset( $_SERVER['SERVER_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_ADDR'] ) ) : '';
			$user_visited_target_info['REMOTE_ADDR']     = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
			$user_visited_target_info['HTTP_REFERER']    = isset( $_SERVER['HTTP_REFERER'] ) ? esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : '';
			$user_visited_target_info['SERVER_NAME']     = isset( $_SERVER['SERVER_NAME'] ) ? esc_url_raw( wp_unslash( $_SERVER['SERVER_NAME'] ) ) : '';

			return $user_visited_target_info;
		}


		/**
		 * Forms Submission Report
		 * Ajax Request
		 * Request from Ajax datatable
		 * Users Forms Submission Report load & display
		 * If form is deleted then we do not show users submission data of those deleted forms
		 *
		 * @since 1.0.0
		 * return - json
		 */
		public static function sc_wordform_users_submission_report_load() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$output_data = array();
			$output_data = SftcyWordformBase::wordform_submission_report_table_inner_join_with_created_forms_table( $_POST );
			echo wp_json_encode( $output_data );
			wp_die();
		}

		/**
		 * Forms Submission Data Detail
		 * Ajax Request
		 * Request from Ajax datatable
		 * Users Forms Submission Data Detail load & display
		 * If form is deleted then we do not show users submission data of those deleted forms
		 *
		 * @since 1.0.0
		 * return - json
		 */
		public static function sc_wordform_users_submission_data_load() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$output_data = array();
			$output_data = SftcyWordformBase::wordform_submission_data_table_inner_join_with_created_forms_table( $_POST );
			echo wp_json_encode( $output_data );
			wp_die();
		}

		/**
		 * Connection Status send log detail DataTable AJAX source.
		 *
		 * @return void
		 */
		public static function sc_wordform_connection_status_send_log_load() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$output_data = array();
			$output_data = SftcyWordformConnectBase::get_connection_status_send_log_table_data( $_POST );
			echo wp_json_encode( $output_data );
			wp_die();
		}

		/**
		 * Payment reports DataTable AJAX source.
		 *
		 * @return void
		 */
		public static function sc_wordform_payment_reports_load() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$output_data = array();
			$output_data = SftcyWordformBase::wordform_get_payment_reports_table_data( $_POST );
			echo wp_json_encode( $output_data );
			wp_die();
		}


		/**
		 * Ajax Request
		 * Settings Menu - Validation messages data store
		 *
		 * @since 1.0.0
		 * return - json
		 */
		public static function sc_wordform_settings_menu_validation_tab_data_save() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output     = array();
			$sanitized_params = isset( $_POST['formData'] ) ? sanitize_text_field( urldecode_deep( $_POST['formData'] ) ) : '';
			wp_parse_str( $sanitized_params, $params );

			if ( isset( $params ) && array_filter( $params ) ) {
				foreach ( $params as $key => $val ) {
					$params[ $key ] = sanitize_text_field( $val );
				}

				global $wpdb;
				$table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_validation_messages_tbl;

				$validation_messages_data           = wp_json_encode( $params );
				$form_id                            = isset( $params['sc-wordform-validation-tab-selected-form-id'] ) ? sanitize_text_field( $params['sc-wordform-validation-tab-selected-form-id'] ) : '';
				$insert_data['form_id']             = $form_id;
				$insert_data['validation_messages'] = $validation_messages_data;
				$query_results                      = SftcyWordformBase::sc_wordform_check_validation_messages_data_set_or_not( $form_id );
				// Update validation messages - if already exist
				if ( $query_results && array_filter( $query_results ) ) {
					$update_data['validation_messages'] = $validation_messages_data;
					$where_data['form_id']              = $form_id;
					$update_record                      = $wpdb->update( $table, $update_data, $where_data );
					if ( $update_record ) {
						self::$output['status']  = 'success';
						self::$output['Msg']     = self::$success_icon . ' ' . __( 'Updated success.', 'wordform-pro' );
						self::$output['comment'] = 'Validation messages data updated for form ID: ' . $form_id;
					} else {
						self::$output['status']  = 'success';
						self::$output['Msg']     = self::$success_icon . ' ' . __( 'Updated success.', 'wordform-pro' );
						self::$output['comment'] = 'Validation messages data not changes for form ID: ' . $form_id;
					}
				}
				// Insert
				else {
					$insert_record = $wpdb->insert( $table, $insert_data );
					if ( $insert_record ) {
						self::$output['status']  = 'success';
						self::$output['Msg']     = self::$success_icon . ' ' . __( 'Saved success.', 'wordform-pro' );
						self::$output['comment'] = 'Validation messages data inserted successfully.';
					} else {
						self::$output['status']  = 'fail';
						self::$output['Msg']     = self::$error_icon . ' ' . __( 'Saved fail.', 'wordform-pro' );
						self::$output['comment'] = 'Validation messages data inserted fail.';
					}
				}
			} // if ( isset( $params ) && array_filter( $params ) )
			else {
				self::$output['status']  = 'fail';
				self::$output['Msg']     = self::$error_icon . ' ' . __( 'Saved fail.', 'wordform-pro' );
				self::$output['comment'] = 'Something went wrong.';
			}

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

		/**
		 * Ajax Request
		 * Settings menu : Validation Tab
		 * Selected form validation messages save
		 *
		 * @since 1.0.0
		 * return - JSON
		 */
		public static function sc_wordform_settings_menu_validation_tab_selected_form_data_save() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output                     = array();
			$form_name                        = isset( $_POST['params']['FormName'] ) && ! empty( $_POST['params']['FormName'] ) ? sanitize_text_field( $_POST['params']['FormName'] ) : '';
			$form_id                          = isset( $_POST['params']['FormID'] ) && ! empty( $_POST['params']['FormID'] ) ? sanitize_text_field( $_POST['params']['FormID'] ) : '';
			self::$output['selectedFormName'] = $form_name;
			self::$output['selectedFormID']   = $form_id;

			if ( $form_id ) {
				// Get set validation messages if found else default validation messages
				$validation_messages = SftcyWordformBase::sc_wordform_get_validation_messages_data_by_formid( $form_id );
				ob_start();
				include_once SFTCY_WORDFORM_PLUGIN_DIR . 'admin/views/settings_callback_validation_tab_page_template.php';
				self::$output['htmlTemplate'] = ob_get_clean();
				self::$output['status']       = 'success';
				self::$output['comment']      = 'Validation messages checked for form ID [' . $form_id . '].';
			} else {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Valid Form ID missing.';
			}

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

		/**
		 * Ajax - Request
		 * All Forms : Delete form
		 * Delete also added form from posts - pages attached with block inserter
		 * Also delete wordform when not attached with any Post or Page
		 * return - json
		 */
		public static function sc_wordform_all_forms_page_delete_form() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output = array();
			$wordform_id  = isset( $_POST['params']['wordformID'] ) && ! empty( $_POST['params']['wordformID'] ) ? sanitize_text_field( $_POST['params']['wordformID'] ) : '';
			$form_name    = isset( $_POST['params']['wordformName'] ) && ! empty( $_POST['params']['wordformName'] ) ? sanitize_text_field( $_POST['params']['wordformName'] ) : '';

			global $wpdb;
			$table         = $wpdb->prefix . SftcyWordformBase::$sc_wordform_tbl;

			// Get only attached block posts / pages of any status
			$args  = array(
				'post_type'      => array( 'post', 'page' ),
				'post_status'    => 'any',
				's'              => SftcyWordformBase::$wordform_custom_block_name,
				'posts_per_page' => -1,
			);
			$query = new WP_Query( $args );
			// Filtering posts / pages Ids only attached blocks based on specific target attributes 'wordformid'
			if ( isset( $wordform_id ) && ! empty( $wordform_id ) ) {
				$target_wordform_attached_post_ids = array();
				foreach ( $query->posts as $post ) {
					if ( ! is_null( $post->post_content ) && $post->post_content ) {
						$blocks = array();  // Reset
						$blocks = parse_blocks( $post->post_content );
						foreach ( $blocks as $key => $block ) {
							if ( SftcyWordformBase::$wordform_custom_block_name == $block['blockName']
								&& isset( $block['attrs']['wordformid'] )
								&& $block['attrs']['wordformid'] == $wordform_id ) {
								$target_wordform_attached_post_ids[] = $post->ID;
							}
						} // foreach
					}
				} // foreach

				// When Wordform attached with any Post or page - Delete attached worform contents only from attached post Ids
				if ( isset( $target_wordform_attached_post_ids ) && array_filter( $target_wordform_attached_post_ids ) ) {
					// Update attached form contents of Posts / Pages
					self::$output['updateSuccessPostIds'] = array();
					self::$output['updateFailPostIds']    = array();
					self::sc_wordform_block_editor_form_html_delete( $target_wordform_attached_post_ids, $wordform_id );
					// Delete from DB
					if ( count( self::$output['updateSuccessPostIds'] ) == count( $target_wordform_attached_post_ids ) ) {
						$delete_record = $wpdb->delete( $table, array( 'form_id' => $wordform_id ), array( '%s' ) );
						if ( is_wp_error( $delete_record ) ) {
							self::$output['wpdbDeleteError'] = $delete_record->get_error_message();
							self::$output['status']          = 'fail';
							self::$output['comment']         = $wordform_id . ' deleted fail.';
						} else {
							self::$output['status']  = 'success';
							self::$output['comment'] = $wordform_id . ' deleted successfully.';
						}
					} else {
						self::$output['status'][ $postID ]  = 'fail';
						self::$output['comment'][ $postID ] = $wordform_id . ' attached form contents of all Post/pages were not updated.';
					}
				}								
				// When Wordform not yet attached with any Post or Page
				else if ( ! array_filter( $target_wordform_attached_post_ids ) ) {				    
						$delete_record = $wpdb->delete( $table, array( 'form_id' => $wordform_id ), array( '%s' ) );				    
						if ( is_wp_error( $delete_record ) ) {
							self::$output['wpdbDeleteError'] = $delete_record->get_error_message();
							self::$output['status']          = 'fail';
							self::$output['comment']         = $wordform_id . ' deleted fail.';
						} else {
							self::$output['status']  = 'success';
							self::$output['comment'] = $wordform_id . ' deleted successfully.';
						}				
				}				
			} 
			else {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Valid Form ID missing | This form ID not attached with any post or page.';
			}

			// Restore original Post Data
			wp_reset_postdata();

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

		/**
		 * Ajax Request
		 * Setting Menu : General Tab
		 * Save General Tab Form data
		 */
		public static function sc_wordform_settings_general_tab_form() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output     = array();
			$sanitized_params = isset( $_POST['params']['formData'] ) ? sanitize_text_field( urldecode_deep( $_POST['params']['formData'] ) ) : '';
			wp_parse_str( $sanitized_params, $params );
			// print_r($params);
			// exit();

			// Form ID: identify which form settings are being updated
			$form_id = isset( $params['sc-wordform-select-general-tab-settings-for-form-id'] )
				? sanitize_text_field( $params['sc-wordform-select-general-tab-settings-for-form-id'] )
				: 'all_form';

			// Build dynamic option name
			$option_key = ( $form_id === 'all_form' )
				? 'sftcy_wordform_settings_menu_general_tab_info'
				: 'sftcy_wordform_settings_menu_general_tab_info_' . $form_id;


			// Form Width
			if ( isset( $params['sc-wordform-form-width'] ) && ! empty( $params['sc-wordform-form-width'] ) ) {
				$wordform_form_width = sanitize_text_field( $params['sc-wordform-form-width'] );
			} else {
				$wordform_form_width = 40;
			}

			// Submit Button Background Color
			if ( isset( $params['sc-wordform-form-submit-button-background-color'] ) && ! empty( $params['sc-wordform-form-submit-button-background-color'] ) ) {
				if ( preg_match( '/^#[a-f0-9]{6}$/i', $params['sc-wordform-form-submit-button-background-color'] ) ) {
					$submit_background_hex_color = sanitize_hex_color( $params['sc-wordform-form-submit-button-background-color'] );
				} else {
					self::$output['status']  = 'fail';
					self::$output['comment'] = 'Background HEX Color code required.';
					self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Valid background hex color required.', 'wordform-pro' );
				}
			}
			// Submit Button Background Hover Color
			if ( isset( $params['sc-wordform-form-submit-button-background-hover-color'] ) && ! empty( $params['sc-wordform-form-submit-button-background-hover-color'] ) ) {
				if ( preg_match( '/^#[a-f0-9]{6}$/i', $params['sc-wordform-form-submit-button-background-hover-color'] ) ) {
					$submit_background_hover_hex_color = sanitize_hex_color( $params['sc-wordform-form-submit-button-background-hover-color'] );
				} else {
					self::$output['status']  = 'fail';
					self::$output['comment'] = 'Background HEX Hover Color code required.';
					self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Valid background hex hover color required.', 'wordform-pro' );
				}
			}

			// Submit Button Font Color
			if ( isset( $params['sc-wordform-form-submit-button-font-color'] ) && ! empty( $params['sc-wordform-form-submit-button-font-color'] ) ) {
				if ( preg_match( '/^#[a-f0-9]{6}$/i', $params['sc-wordform-form-submit-button-font-color'] ) ) {
					$submit_button_font_hex_color = sanitize_hex_color( $params['sc-wordform-form-submit-button-font-color'] );
				} else {
					self::$output['status']  = 'fail';
					self::$output['comment'] = 'Submit Button Font HEX Color code required.';
					self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Valid font hex color required.', 'wordform-pro' );
				}
			}

			// Submit Button Font Weight
			if ( isset( $params['sc-wordform-form-submit-button-font-weight'] ) && ! empty( $params['sc-wordform-form-submit-button-font-weight'] ) ) {
				$submit_button_font_weight = sanitize_text_field( $params['sc-wordform-form-submit-button-font-weight'] );
			} else {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Submit Button Font weight value required.';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Check font-weight value.', 'wordform-pro' );
			}

			// Submit Button Font size
			if ( isset( $params['sc-wordform-form-submit-button-text-size'] ) && ! empty( $params['sc-wordform-form-submit-button-text-size'] ) ) {
				$submit_button_font_size = sanitize_text_field( $params['sc-wordform-form-submit-button-text-size'] );
			} else {
				$submit_button_font_size = 16;
			}

			// Submit Button Padding (Top-Bottom)
			if ( isset( $params['sc-wordform-form-submit-button-padding-top-bottom'] ) && ! empty( $params['sc-wordform-form-submit-button-padding-top-bottom'] ) ) {
				$submit_button_padding_top_bottom = sanitize_text_field( $params['sc-wordform-form-submit-button-padding-top-bottom'] );
			} else {
				$submit_button_padding_top_bottom = 8;
			}

			// Submit Button Padding (Left-Right)
			if ( isset( $params['sc-wordform-form-submit-button-padding-left-right'] ) && ! empty( $params['sc-wordform-form-submit-button-padding-left-right'] ) ) {
				$submit_button_padding_left_right = sanitize_text_field( $params['sc-wordform-form-submit-button-padding-left-right'] );
			} else {
				$submit_button_padding_left_right = 25;
			}

			// Send Email
			if ( isset( $params['sc-wordform-form-submission-send-email'] ) && $params['sc-wordform-form-submission-send-email'] == 'on' ) {
				$form_submit_send_email = 'yes';
			} else {
				$form_submit_send_email = 'no';
			}

			// Hide Form
			if ( isset( $params['sc-wordform-form-submission-hide-form'] ) && $params['sc-wordform-form-submission-hide-form'] == 'on' ) {
				$form_submit_hide_form = 'yes';
			} else {
				$form_submit_hide_form = 'no';
			}

			// Success Message
			$form_submission_success_message = isset( $params['sc-wordform-form-submission-success-message'] ) && ! empty( $params['sc-wordform-form-submission-success-message'] )
				? sanitize_text_field( $params['sc-wordform-form-submission-success-message'] )
				: SftcyWordformBase::wordform_get_settings_general_tab_default_data()['form_submission_success_message'];

			// Loading Text
			$submit_button_loading_text = isset( $params['sc-wordform-submit-button-loading-text'] ) && ! empty( $params['sc-wordform-submit-button-loading-text'] )
				? sanitize_text_field( $params['sc-wordform-submit-button-loading-text'] )
				: SftcyWordformBase::wordform_get_settings_general_tab_default_data()['submit_button_loading_text'];

			$show_submit_button_spinner   = ( isset( $params['sc-wordform-show-submit-button-spinner'] ) && $params['sc-wordform-show-submit-button-spinner'] === 'on' ) ? 'yes' : 'no';
			$show_submit_progress_text    = ( isset( $params['sc-wordform-show-submit-progress-text'] ) && $params['sc-wordform-show-submit-progress-text'] === 'on' ) ? 'yes' : 'no';
			$show_success_message_as_card = ( isset( $params['sc-wordform-show-success-message-as-card'] ) && $params['sc-wordform-show-success-message-as-card'] === 'on' ) ? 'yes' : 'no';
			$redirect_on_form_submission  = ( isset( $params['sc-wordform-redirect-on-form-submission'] ) && $params['sc-wordform-redirect-on-form-submission'] === 'on' ) ? 'yes' : 'no';
			$redirect_url_on_form_submission = isset( $params['sc-wordform-redirect-url-on-form-submission'] )
				? esc_url_raw( trim( wp_unslash( $params['sc-wordform-redirect-url-on-form-submission'] ) ) )
				: '';

			// Field Gap
			$form_field_gap = isset( $params['sc-wordform-form-field-gap'] ) && $params['sc-wordform-form-field-gap'] !== ''
				? max( 8, min( 48, intval( $params['sc-wordform-form-field-gap'] ) ) )
				: intval( SftcyWordformBase::wordform_get_settings_general_tab_default_data()['form_field_gap'] );

			// Container Padding
			$form_container_padding = isset( $params['sc-wordform-form-container-padding'] ) && $params['sc-wordform-form-container-padding'] !== ''
				? max( 0, min( 48, intval( $params['sc-wordform-form-container-padding'] ) ) )
				: intval( SftcyWordformBase::wordform_get_settings_general_tab_default_data()['form_container_padding'] );

			// Container Border Radius
			$form_container_border_radius = isset( $params['sc-wordform-form-container-border-radius'] ) && $params['sc-wordform-form-container-border-radius'] !== ''
				? max( 0, min( 36, intval( $params['sc-wordform-form-container-border-radius'] ) ) )
				: intval( SftcyWordformBase::wordform_get_settings_general_tab_default_data()['form_container_border_radius'] );

			// If no error
			if ( ! isset( self::$output['status'] ) || self::$output['status'] != 'fail' ) {
				$general_tab_options = array(
					'wordform_form_width'                  => $wordform_form_width,
					'submit_button_background_color'       => $submit_background_hex_color,
					'submit_button_background_hover_color' => $submit_background_hover_hex_color,
					'submit_button_font_color'             => $submit_button_font_hex_color,
					'submit_button_font_size'              => $submit_button_font_size,
					'submit_button_padding_top_bottom'     => $submit_button_padding_top_bottom,
					'submit_button_padding_left_right'     => $submit_button_padding_left_right,
					'submit_button_font_weight'            => $submit_button_font_weight,
					'send_email_on_form_submission'        => $form_submit_send_email,
					'hide_form_on_form_submission'         => $form_submit_hide_form,
					'form_submission_success_message'      => $form_submission_success_message,
					'submit_button_loading_text'           => $submit_button_loading_text,
					'show_submit_button_spinner'           => $show_submit_button_spinner,
					'show_submit_progress_text'            => $show_submit_progress_text,
					'show_success_message_as_card'         => $show_success_message_as_card,
					'redirect_on_form_submission'          => $redirect_on_form_submission,
					'redirect_url_on_form_submission'      => $redirect_url_on_form_submission,
					'form_field_gap'                       => $form_field_gap,
					'form_container_padding'               => $form_container_padding,
					'form_container_border_radius'         => $form_container_border_radius,
				);


				if ( update_option( $option_key, $general_tab_options ) ) {
					self::$output['status']     = 'success';
					self::$output['comment']    = 'Hex Colors are valid.';
					self::$output['successMsg'] = self::$success_icon . ' ' . __( 'Updated success.', 'wordform-pro' );
				} else {
					self::$output['status']     = 'success';
					self::$output['comment']    = 'Nothing changes.';
					self::$output['successMsg'] = self::$success_icon . ' ' . __( 'Nothing changes.', 'wordform-pro' );
				}
			}
			wp_send_json( self::$output );
			wp_die();
		}

		/**
		 *  Ajax Request
		 *  Setting Menu : General Tab Config data load
		 *  When change dropdown value - change Wordform name
		 */		
		public static function sc_wordform_get_general_tab_data() {
			check_ajax_referer('scwordform_wpnonce', 'security');
			$form_id = isset($_POST['form_id']) ? sanitize_text_field($_POST['form_id']) : '';
			$settings = SftcyWordformBase::sc_wordform_get_settings_general_tab_info($form_id);

			wp_send_json([
				'status'   => 'success',
				'message'  => 'Settings loaded successfully.',
				'settings' => $settings,
			]);
		}

		/**
		 * AJAX: Return Central Default General Settings Data
		 */
		public static function sc_wordform_get_general_tab_default_data() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$form_id  = isset($_POST['form_id']) ? sanitize_text_field($_POST['form_id']) : 'all_form';
			$defaults = SftcyWordformBase::wordform_get_settings_general_tab_default_data();
			wp_send_json( [
				'status'   => 'success',
				'form_id'  => $form_id,
				'defaults' => $defaults,
			] );
		}



		/**
		 * Ajax Request
		 * Setting Menu : Upload Tab Config data
		 * Save Upload Tab Config data
		 */
		// public static function sc_wordform_settings_upload_tab_form() {
		// 	check_ajax_referer( 'scwordform_wpnonce', 'security' );
		// 	self::$output     = array();
		// 	$sanitized_params = isset( $_POST['params']['formData'] ) ? sanitize_text_field( urldecode_deep( $_POST['params']['formData'] ) ) : '';
		// 	wp_parse_str( $sanitized_params, $params );
		// 	// print_r($params);
		// 	// exit();

		// 	$upload_config_data = SftcyWordformBase::wordform_settings_page_upload_config();
		// 	// print_r( $upload_config_data );
		// 	// exit();

		// 	// max_num_files_allowed
		// 	if ( isset( $params['sc-wordform-upload-max-numof-files'] ) && ! empty( $params['sc-wordform-upload-max-numof-files'] ) ) {
		// 		$wordform_max_num_files_allowed = sanitize_text_field( $params['sc-wordform-upload-max-numof-files'] );
		// 	} else {
		// 		$wordform_max_num_files_allowed = $upload_config_data['server_max_num_files_allowed'];
		// 	}

		// 	// each_file_max_size_allowed
		// 	if ( isset( $params['sc-wordform-upload-each-file-max-size'] ) && ! empty( $params['sc-wordform-upload-each-file-max-size'] ) ) {
		// 		$wordform_each_file_max_size_allowed = sanitize_text_field( $params['sc-wordform-upload-each-file-max-size'] );
		// 	} else {
		// 		$wordform_each_file_max_size_allowed = $upload_config_data['server_each_file_max_size_allowed'];;
		// 	}

		// 	// all_files_max_size_allowed
		// 	if ( isset( $params['sc-wordform-upload-all-files-max-size'] ) && ! empty( $params['sc-wordform-upload-all-files-max-size'] ) ) {
		// 		$wordform_all_files_max_size_allowed = sanitize_text_field( $params['sc-wordform-upload-all-files-max-size'] );
		// 	} else {
		// 		$wordform_all_files_max_size_allowed = $upload_config_data['server_all_files_max_size_allowed'];;
		// 	}			

		// 	// Show Hide Progress Bar
		// 	if ( isset( $params['sc-wordform-upload-progress-bar-show-hide'] ) && $params['sc-wordform-upload-progress-bar-show-hide'] == 'on' ) {
		// 		$wordform_upload_show_hide_progress_bar = 'yes';
		// 	}
		// 	else {
		// 		$wordform_upload_show_hide_progress_bar = 'no';
		// 	}

		// 	// Uploading Progress bar hex color
		// 	if ( isset( $params['sc-wordform-upload-progress-bar-color'] ) && ! empty( $params['sc-wordform-upload-progress-bar-color'] ) ) {
		// 		$wordform_upload_progress_bar_color = sanitize_hex_color( $params['sc-wordform-upload-progress-bar-color'] );
		// 	} else {
		// 		$wordform_upload_progress_bar_color = $upload_config_data['wordform_upload_progress_bar_color'];
		// 	}			

		// 	// Update Options
		// 	$updated_options_report = [];
        //     if ( $updated_options_report['upload_max_numof_files'] =  update_option( 'wordform_upload_max_numof_files', $wordform_max_num_files_allowed ) || 
		// 			 $updated_options_report['upload_each_file_max_size'] = update_option( 'wordform_upload_each_file_max_size', $wordform_each_file_max_size_allowed ) ||
		// 				 $updated_options_report['upload_all_files_max_size'] = update_option( 'wordform_upload_all_files_max_size', $wordform_all_files_max_size_allowed ) ||
		// 					 $updated_options_report['upload_show_hide_progress_bar'] = update_option( 'wordform_upload_show_hide_progress_bar', $wordform_upload_show_hide_progress_bar ) ||
		// 						 $updated_options_report['upload_progress_bar_color'] = update_option( 'wordform_upload_progress_bar_color', $wordform_upload_progress_bar_color ) )

		// 	{
		// 		self::$output['status']  = 'success';
		// 		self::$output['comment'] = 'All options value saved successfully.';
		// 		self::$output['successMsg'] = self::$success_icon . ' ' . __( 'Updated success.', 'wordform-pro' );
		// 		self::$output['updated_options_report'] = $updated_options_report;
		// 	}		
		// 	else {
		// 		self::$output['status']  = 'warning';
		// 		self::$output['comment'] = 'Nothing changes of option values.';	
		// 		self::$output['warningMsg'] = self::$success_icon . ' ' . __( 'Nothing changes.', 'wordform-pro' );			
		// 		self::$output['updated_options_report'] = $updated_options_report;
		// 	}

		// 	echo wp_json_encode( self::$output );
		// 	wp_die();
		// }


		/**
		 * Ajax Request
		 * Settings Menu : Upload Tab Config data
		 * Save Upload Tab Config data
		 */
		public static function sc_wordform_settings_upload_tab_form() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			self::$output = array();

			// Decode and parse form data
			$sanitized_params = isset( $_POST['params']['formData'] ) ? sanitize_text_field( urldecode_deep( $_POST['params']['formData'] ) ) : '';
			wp_parse_str( $sanitized_params, $params );

			// Load current data and defaults
			$existing_data = get_option( 'wordform_upload_tab_options_data', array() );
			$server_defaults = SftcyWordformBase::wordform_settings_page_upload_config();

			// Build new options array
			$new_options = array(
				'upload_max_numof_files'         => ! empty( $params['sc-wordform-upload-max-numof-files'] ) 
					? sanitize_text_field( $params['sc-wordform-upload-max-numof-files'] )
					: $server_defaults['server_max_num_files_allowed'],

				'upload_each_file_max_size'      => ! empty( $params['sc-wordform-upload-each-file-max-size'] ) 
					? sanitize_text_field( $params['sc-wordform-upload-each-file-max-size'] )
					: $server_defaults['server_each_file_max_size_allowed'],

				'upload_all_files_max_size'      => ! empty( $params['sc-wordform-upload-all-files-max-size'] ) 
					? sanitize_text_field( $params['sc-wordform-upload-all-files-max-size'] )
					: $server_defaults['server_all_files_max_size_allowed'],

				'upload_show_hide_progress_bar'  => ( isset( $params['sc-wordform-upload-progress-bar-show-hide'] ) && $params['sc-wordform-upload-progress-bar-show-hide'] === 'on' ) 
					? 'yes' 
					: 'no',

				'upload_progress_bar_color'      => ! empty( $params['sc-wordform-upload-progress-bar-color'] ) 
					? sanitize_hex_color( $params['sc-wordform-upload-progress-bar-color'] )
					: $server_defaults['upload_progress_bar_color'],
			);

			// Add metadata
			$new_options['last_updated'] = current_time( 'mysql' );
			$new_options['version']      = isset( $existing_data['version'] ) 
				? (int) $existing_data['version'] + 1 
				: 1;

			// Update if changes exist
			if ( $existing_data !== $new_options ) {
				$update_result = update_option( 'wordform_upload_tab_options_data', $new_options );

				if ( $update_result ) {
					self::$output['status']  = 'success';
					self::$output['comment'] = 'Upload tab options updated successfully.';
					self::$output['successMsg'] = self::$success_icon . ' ' . __( 'Updated successfully.', 'wordform-pro' );
				} else {
					self::$output['status']  = 'error';
					self::$output['comment'] = 'Failed to update upload tab settings.';
					self::$output['errorMsg'] = self::$error_icon . ' ' . __( 'Update failed.', 'wordform-pro' );
				}
			} else {
				self::$output['status']  = 'warning';
				self::$output['comment'] = 'No changes detected.';
				self::$output['warningMsg'] = self::$warning_icon . ' ' . __( 'Nothing changed.', 'wordform-pro' );
			}

			self::$output['saved_data'] = $new_options;

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

		/**
		 * Ajax Request
		 * Settings Menu - Validation messages reset to defaults
		 *
		 * @since 1.0.0
		 * @return void
		 */
		public static function sc_wordform_settings_menu_validation_tab_data_reset() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output = array();

			$form_id   = isset( $_POST['form_id'] ) ? sanitize_text_field( wp_unslash( $_POST['form_id'] ) ) : 'all_form';
			$form_name = isset( $_POST['form_name'] ) ? sanitize_text_field( wp_unslash( $_POST['form_name'] ) ) : 'All Forms';

			global $wpdb;
			$table                              = $wpdb->prefix . SftcyWordformBase::$sc_wordform_validation_messages_tbl;
			$validation_messages                = SftcyWordformBase::wordform_default_validation_messages();
			$validation_messages_data           = wp_json_encode( $validation_messages );
			$insert_data                        = array();
			$insert_data['form_id']             = $form_id;
			$insert_data['validation_messages'] = $validation_messages_data;

			$query_results = SftcyWordformBase::sc_wordform_check_validation_messages_data_set_or_not( $form_id );
			if ( $query_results && array_filter( $query_results ) ) {
				$update_record = $wpdb->update(
					$table,
					array( 'validation_messages' => $validation_messages_data ),
					array( 'form_id' => $form_id )
				);

				if ( false === $update_record ) {
					self::$output['status']  = 'fail';
					self::$output['Msg']     = self::$error_icon . ' ' . __( 'Reset failed.', 'wordform-pro' );
					self::$output['comment'] = 'Validation messages reset failed for form ID: ' . $form_id;
					echo wp_json_encode( self::$output );
					wp_die();
				}
			} else {
				$insert_record = $wpdb->insert( $table, $insert_data );
				if ( ! $insert_record ) {
					self::$output['status']  = 'fail';
					self::$output['Msg']     = self::$error_icon . ' ' . __( 'Reset failed.', 'wordform-pro' );
					self::$output['comment'] = 'Validation messages default insert failed for form ID: ' . $form_id;
					echo wp_json_encode( self::$output );
					wp_die();
				}
			}

			ob_start();
			require SFTCY_WORDFORM_PLUGIN_DIR . 'admin/views/settings_callback_validation_tab_page_template.php';
			self::$output['htmlTemplate']     = ob_get_clean();
			self::$output['selectedFormName'] = $form_name;
			self::$output['selectedFormID']   = $form_id;
			self::$output['status']           = 'success';
			self::$output['Msg']              = self::$success_icon . ' ' . __( 'Reset to defaults.', 'wordform-pro' );
			self::$output['comment']          = 'Validation messages reset to defaults for form ID: ' . $form_id;

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


		/**
		 * Ajax Request
		 * Settings Menu : Payment Tab
		 * Save Stripe / PayPal foundation settings.
		 *
		 * @return void
		 */
		public static function sc_wordform_settings_payment_tab_form() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			self::$output = array();

			$sanitized_params = isset( $_POST['params']['formData'] ) ? sanitize_text_field( urldecode_deep( $_POST['params']['formData'] ) ) : '';
			wp_parse_str( $sanitized_params, $params );

			$existing_data = get_option( 'wordform_payment_tab_options_data', array() );
			$existing_data = is_array( $existing_data ) ? $existing_data : array();
			$defaults      = SftcyWordformBase::wordform_get_settings_payment_tab_default_data();

			$payment_currency = isset( $params['wordform-payment-currency'] ) ? strtoupper( sanitize_text_field( $params['wordform-payment-currency'] ) ) : $defaults['payment_currency'];
			if ( ! preg_match( '/^[A-Z]{3}$/', $payment_currency ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Payment currency must be a 3-letter ISO code.';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Enter a valid 3-letter currency code like USD or EUR.', 'wordform-pro' );
				wp_send_json( self::$output );
			}

			$currency_position = isset( $params['wordform-payment-currency-symbol-position'] ) ? sanitize_text_field( $params['wordform-payment-currency-symbol-position'] ) : $defaults['payment_currency_symbol_position'];
			if ( ! in_array( $currency_position, array( 'before', 'after' ), true ) ) {
				$currency_position = $defaults['payment_currency_symbol_position'];
			}

			$stripe_mode = isset( $params['wordform-stripe-mode'] ) ? sanitize_text_field( $params['wordform-stripe-mode'] ) : $defaults['stripe_mode'];
			if ( ! in_array( $stripe_mode, array( 'test', 'live' ), true ) ) {
				$stripe_mode = $defaults['stripe_mode'];
			}

			$paypal_mode = isset( $params['wordform-paypal-mode'] ) ? sanitize_text_field( $params['wordform-paypal-mode'] ) : $defaults['paypal_mode'];
			if ( ! in_array( $paypal_mode, array( 'sandbox', 'live' ), true ) ) {
				$paypal_mode = $defaults['paypal_mode'];
			}

			$square_mode = isset( $params['wordform-square-mode'] ) ? sanitize_text_field( $params['wordform-square-mode'] ) : $defaults['square_mode'];
			if ( ! in_array( $square_mode, array( 'sandbox', 'live' ), true ) ) {
				$square_mode = $defaults['square_mode'];
			}

			$authorizenet_mode = isset( $params['wordform-authorizenet-mode'] ) ? sanitize_text_field( $params['wordform-authorizenet-mode'] ) : $defaults['authorizenet_mode'];
			if ( ! in_array( $authorizenet_mode, array( 'sandbox', 'live' ), true ) ) {
				$authorizenet_mode = $defaults['authorizenet_mode'];
			}

			$square_available       = class_exists( 'SftcyWordformFeatures' ) ? SftcyWordformFeatures::wordform_is_feature_available( 'square_gateway' ) : true;
			$authorizenet_available = class_exists( 'SftcyWordformFeatures' ) ? SftcyWordformFeatures::wordform_is_feature_available( 'authorizenet_gateway' ) : true;

			$new_options = array(
				'payment_currency'                 => $payment_currency,
				'payment_currency_symbol_position' => $currency_position,
				'stripe_enabled'                  => ( isset( $params['wordform-stripe-enabled'] ) && 'on' === $params['wordform-stripe-enabled'] ) ? 'yes' : 'no',
				'stripe_mode'                     => $stripe_mode,
				'stripe_publishable_key'          => isset( $params['wordform-stripe-publishable-key'] ) ? trim( sanitize_text_field( $params['wordform-stripe-publishable-key'] ) ) : '',
				'stripe_secret_key'               => isset( $params['wordform-stripe-secret-key'] ) ? trim( sanitize_text_field( $params['wordform-stripe-secret-key'] ) ) : '',
				'stripe_webhook_secret'           => isset( $params['wordform-stripe-webhook-secret'] ) ? trim( sanitize_text_field( $params['wordform-stripe-webhook-secret'] ) ) : '',
				'paypal_enabled'                  => ( isset( $params['wordform-paypal-enabled'] ) && 'on' === $params['wordform-paypal-enabled'] ) ? 'yes' : 'no',
				'paypal_mode'                     => $paypal_mode,
				'paypal_client_id'                => isset( $params['wordform-paypal-client-id'] ) ? trim( sanitize_text_field( $params['wordform-paypal-client-id'] ) ) : '',
				'paypal_client_secret'            => isset( $params['wordform-paypal-client-secret'] ) ? trim( sanitize_text_field( $params['wordform-paypal-client-secret'] ) ) : '',
				'paypal_webhook_id'               => isset( $params['wordform-paypal-webhook-id'] ) ? trim( sanitize_text_field( $params['wordform-paypal-webhook-id'] ) ) : '',
				'square_enabled'                  => $square_available ? ( ( isset( $params['wordform-square-enabled'] ) && 'on' === $params['wordform-square-enabled'] ) ? 'yes' : 'no' ) : ( isset( $existing_data['square_enabled'] ) ? sanitize_text_field( $existing_data['square_enabled'] ) : $defaults['square_enabled'] ),
				'square_mode'                     => $square_available ? $square_mode : ( isset( $existing_data['square_mode'] ) ? sanitize_text_field( $existing_data['square_mode'] ) : $defaults['square_mode'] ),
				'square_application_id'           => $square_available ? ( isset( $params['wordform-square-application-id'] ) ? trim( sanitize_text_field( $params['wordform-square-application-id'] ) ) : '' ) : ( isset( $existing_data['square_application_id'] ) ? sanitize_text_field( $existing_data['square_application_id'] ) : '' ),
				'square_access_token'             => $square_available ? ( isset( $params['wordform-square-access-token'] ) ? trim( sanitize_text_field( $params['wordform-square-access-token'] ) ) : '' ) : ( isset( $existing_data['square_access_token'] ) ? sanitize_text_field( $existing_data['square_access_token'] ) : '' ),
				'square_location_id'              => $square_available ? ( isset( $params['wordform-square-location-id'] ) ? trim( sanitize_text_field( $params['wordform-square-location-id'] ) ) : '' ) : ( isset( $existing_data['square_location_id'] ) ? sanitize_text_field( $existing_data['square_location_id'] ) : '' ),
				'authorizenet_enabled'            => $authorizenet_available ? ( ( isset( $params['wordform-authorizenet-enabled'] ) && 'on' === $params['wordform-authorizenet-enabled'] ) ? 'yes' : 'no' ) : ( isset( $existing_data['authorizenet_enabled'] ) ? sanitize_text_field( $existing_data['authorizenet_enabled'] ) : $defaults['authorizenet_enabled'] ),
				'authorizenet_mode'               => $authorizenet_available ? $authorizenet_mode : ( isset( $existing_data['authorizenet_mode'] ) ? sanitize_text_field( $existing_data['authorizenet_mode'] ) : $defaults['authorizenet_mode'] ),
				'authorizenet_api_login_id'       => $authorizenet_available ? ( isset( $params['wordform-authorizenet-api-login-id'] ) ? trim( sanitize_text_field( $params['wordform-authorizenet-api-login-id'] ) ) : '' ) : ( isset( $existing_data['authorizenet_api_login_id'] ) ? sanitize_text_field( $existing_data['authorizenet_api_login_id'] ) : '' ),
				'authorizenet_client_key'         => $authorizenet_available ? ( isset( $params['wordform-authorizenet-client-key'] ) ? trim( sanitize_text_field( $params['wordform-authorizenet-client-key'] ) ) : '' ) : ( isset( $existing_data['authorizenet_client_key'] ) ? sanitize_text_field( $existing_data['authorizenet_client_key'] ) : '' ),
				'authorizenet_transaction_key'    => $authorizenet_available ? ( isset( $params['wordform-authorizenet-transaction-key'] ) ? trim( sanitize_text_field( $params['wordform-authorizenet-transaction-key'] ) ) : '' ) : ( isset( $existing_data['authorizenet_transaction_key'] ) ? sanitize_text_field( $existing_data['authorizenet_transaction_key'] ) : '' ),
				'last_updated'                    => current_time( 'mysql' ),
				'version'                         => isset( $existing_data['version'] ) ? (int) $existing_data['version'] + 1 : 1,
			);

			if ( $existing_data !== $new_options ) {
				if ( update_option( 'wordform_payment_tab_options_data', $new_options ) ) {
					self::$output['status']     = 'success';
					self::$output['comment']    = 'Payment settings updated successfully.';
					self::$output['successMsg'] = self::$success_icon . ' ' . __( 'Payment settings updated successfully.', 'wordform-pro' );
				} else {
					self::$output['status']   = 'fail';
					self::$output['comment']  = 'Payment settings update failed.';
					self::$output['failMsg']  = self::$error_icon . ' ' . __( 'Payment settings could not be saved.', 'wordform-pro' );
				}
			} else {
				self::$output['status']     = 'success';
				self::$output['comment']    = 'Nothing changed in payment settings.';
				self::$output['successMsg'] = self::$info_icon . ' ' . __( 'Nothing changed.', 'wordform-pro' );
			}

			self::$output['saved_data'] = $new_options;

			wp_send_json( self::$output );
		}

		/**
		 * Render coupon table rows HTML.
		 *
		 * @return string
		 */
		private static function wordform_render_coupon_rows_html() {
			$coupon_rows = SftcyWordformBase::wordform_get_all_coupons();
			ob_start();
			require SFTCY_WORDFORM_PLUGIN_DIR . 'admin/views/settings-callback-coupons-tab-table-rows.php';
			return (string) ob_get_clean();
		}

		/**
		 * Save coupon data from Coupons settings tab.
		 *
		 * @return void
		 */
		public static function sc_wordform_coupon_save() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output = array();
			SftcyWordformBase::sc_wordform_db_tables_install();

			$sanitized_params = isset( $_POST['params']['formData'] ) ? sanitize_text_field( urldecode_deep( $_POST['params']['formData'] ) ) : '';
			wp_parse_str( $sanitized_params, $params );

			global $wpdb;
			$table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_coupons_tbl;

			$coupon_id            = isset( $params['coupon-id'] ) ? absint( $params['coupon-id'] ) : 0;
			$coupon_code_raw      = isset( $params['coupon-code'] ) ? sanitize_text_field( $params['coupon-code'] ) : '';
			$coupon_code          = strtoupper( preg_replace( '/[^A-Za-z0-9\-_]/', '', $coupon_code_raw ) );
			$discount_type        = isset( $params['coupon-discount-type'] ) ? sanitize_key( $params['coupon-discount-type'] ) : 'fixed';
			$discount_value       = isset( $params['coupon-discount-value'] ) ? (float) $params['coupon-discount-value'] : 0;
			$coupon_status        = isset( $params['coupon-status'] ) ? sanitize_key( $params['coupon-status'] ) : 'active';
			$start_date           = isset( $params['coupon-start-date'] ) ? sanitize_text_field( $params['coupon-start-date'] ) : '';
			$expiry_date          = isset( $params['coupon-expiry-date'] ) ? sanitize_text_field( $params['coupon-expiry-date'] ) : '';
			$usage_limit          = isset( $params['coupon-usage-limit'] ) ? absint( $params['coupon-usage-limit'] ) : 0;
			$minimum_amount       = isset( $params['coupon-minimum-amount'] ) ? (float) $params['coupon-minimum-amount'] : 0;
			$apply_to_custom      = ( isset( $params['coupon-apply-to-custom-amount'] ) && 'on' === $params['coupon-apply-to-custom-amount'] ) ? 'yes' : 'no';
			$allowed_forms        = isset( $params['coupon-allowed-forms'] ) ? array_map( 'sanitize_text_field', (array) $params['coupon-allowed-forms'] ) : array();
			$apply_to_all_forms   = isset( $params['coupon-apply-to-all-forms'] ) && 'yes' === sanitize_text_field( $params['coupon-apply-to-all-forms'] );
			$coupon_note          = isset( $params['coupon-note'] ) ? sanitize_textarea_field( $params['coupon-note'] ) : '';

			if ( empty( $coupon_code ) ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Enter a valid coupon code.', 'wordform-pro' );
				wp_send_json( self::$output );
			}

			if ( ! in_array( $discount_type, array( 'fixed', 'percentage' ), true ) ) {
				$discount_type = 'fixed';
			}

			if ( $discount_value <= 0 ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Discount value must be greater than zero.', 'wordform-pro' );
				wp_send_json( self::$output );
			}

			if ( 'percentage' === $discount_type && $discount_value > 100 ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Percentage discount cannot be greater than 100.', 'wordform-pro' );
				wp_send_json( self::$output );
			}

			if ( ! in_array( $coupon_status, array( 'active', 'inactive' ), true ) ) {
				$coupon_status = 'active';
			}

			if ( ! empty( $start_date ) && ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $start_date ) ) {
				$start_date = '';
			}

			if ( ! empty( $expiry_date ) && ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $expiry_date ) ) {
				$expiry_date = '';
			}

			if ( ! empty( $start_date ) && ! empty( $expiry_date ) && strtotime( $expiry_date ) < strtotime( $start_date ) ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Expiry date must be on or after the start date.', 'wordform-pro' );
				wp_send_json( self::$output );
			}

			$allowed_forms = $apply_to_all_forms ? array() : array_values( array_unique( array_filter( $allowed_forms ) ) );

			$existing_id = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT id FROM {$table} WHERE UPPER(coupon_code) = %s LIMIT 1",
					$coupon_code
				)
			);

			if ( $existing_id && absint( $existing_id ) !== $coupon_id ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Coupon code already exists. Use a unique code.', 'wordform-pro' );
				wp_send_json( self::$output );
			}

			$data = array(
				'coupon_code'            => $coupon_code,
				'discount_type'          => $discount_type,
				'discount_value'         => number_format( $discount_value, 2, '.', '' ),
				'coupon_status'          => $coupon_status,
				'start_date'             => ! empty( $start_date ) ? $start_date : null,
				'expiry_date'            => ! empty( $expiry_date ) ? $expiry_date : null,
				'usage_limit'            => $usage_limit,
				'minimum_amount'         => number_format( $minimum_amount, 2, '.', '' ),
				'apply_to_custom_amount' => $apply_to_custom,
				'allowed_forms'          => wp_json_encode( $allowed_forms ),
				'coupon_note'            => $coupon_note,
			);

			if ( $coupon_id > 0 ) {
				$saved = $wpdb->update( $table, $data, array( 'id' => $coupon_id ) );
				$success_text = __( 'Coupon updated successfully.', 'wordform-pro' );
			} else {
				$saved = $wpdb->insert( $table, $data );
				$success_text = __( 'Coupon created successfully.', 'wordform-pro' );
			}

			if ( false === $saved ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Coupon could not be saved.', 'wordform-pro' );
				wp_send_json( self::$output );
			}

			self::$output['status']      = 'success';
			self::$output['successMsg']  = self::$success_icon . ' ' . $success_text;
			self::$output['rowsHtml']    = self::wordform_render_coupon_rows_html();
			self::$output['savedCoupon'] = SftcyWordformBase::wordform_get_coupon_by_id( $coupon_id > 0 ? $coupon_id : (int) $wpdb->insert_id );
			wp_send_json( self::$output );
		}

		/**
		 * Delete coupon from Coupons settings tab.
		 *
		 * @return void
		 */
		public static function sc_wordform_coupon_delete() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output = array();
			SftcyWordformBase::sc_wordform_db_tables_install();

			$coupon_id = isset( $_POST['coupon_id'] ) ? absint( $_POST['coupon_id'] ) : 0;
			if ( $coupon_id <= 0 ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Invalid coupon selected.', 'wordform-pro' );
				wp_send_json( self::$output );
			}

			global $wpdb;
			$table       = $wpdb->prefix . SftcyWordformBase::$sc_wordform_coupons_tbl;
			$usage_table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_coupon_usage_tbl;

			$wpdb->delete( $usage_table, array( 'coupon_id' => $coupon_id ) );
			$deleted = $wpdb->delete( $table, array( 'id' => $coupon_id ) );

			if ( false === $deleted ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Coupon could not be deleted.', 'wordform-pro' );
				wp_send_json( self::$output );
			}

			self::$output['status']     = 'success';
			self::$output['successMsg'] = self::$success_icon . ' ' . __( 'Coupon deleted successfully.', 'wordform-pro' );
			self::$output['rowsHtml']   = self::wordform_render_coupon_rows_html();
			wp_send_json( self::$output );
		}



		/**
		 * Ajax Request
		 * Setting Menu : Google reCaptcha Tab
		 * Save Google reCaptcha Tab Form data
		 */
		public static function sc_wordform_settings_google_recaptcha_tab_form() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			$errors = 0;
			self::$output     = array();
			$sanitized_params = isset( $_POST['params']['formData'] ) ? sanitize_text_field( urldecode_deep( $_POST['params']['formData'] ) ) : '';
			wp_parse_str( $sanitized_params, $params );
			//  print_r($params);
			//  exit();
			 
			// reCaptcha Type Classic | Enterprise
			if ( isset( $params['wordform-gcaptcha-type'] ) && ! empty( $params['wordform-gcaptcha-type'] ) ) {
				$wordform_gcaptcha_type = trim( sanitize_text_field( $params['wordform-gcaptcha-type'] ) );
			}
			else {				
				$errors++;
			}

			// reCaptcha Version v2 | v3
			if ( isset( $params['wordform-gcaptcha-version'] ) && ! empty( $params['wordform-gcaptcha-version'] ) ) {
				$wordform_gcaptcha_version = trim( sanitize_text_field( $params['wordform-gcaptcha-version'] ) );
			}
			else {				
				$errors++;
			}

			// reCaptcha theme light | dark | default : light
			if ( isset( $params['wordform-gcaptcha-theme'] ) && ! empty( $params['wordform-gcaptcha-theme'] ) ) {
				$wordform_gcaptcha_theme = trim( sanitize_text_field( $params['wordform-gcaptcha-theme'] ) );
			}
			else {				
				$wordform_gcaptcha_theme = 'light';
			}

			// reCaptcha Site Key
			if ( isset( $params['wordform-gcaptcha-site-key'] ) && ! empty( $params['wordform-gcaptcha-site-key'] ) ) {
				$wordform_gcaptcha_site_key = trim( sanitize_text_field( $params['wordform-gcaptcha-site-key'] ) );
			} else {
				$wordform_gcaptcha_site_key = '';
			}
			// reCaptcha Secret Key
			if ( isset( $params['wordform-gcaptcha-secret-key'] ) && ! empty( $params['wordform-gcaptcha-secret-key'] ) ) {
				$wordform_gcaptcha_secret_key = trim( sanitize_text_field( $params['wordform-gcaptcha-secret-key'] ) );
			} else {
				$wordform_gcaptcha_secret_key = '';
			}

			 // Check Input Data			
			 if ( empty( $wordform_gcaptcha_site_key ) && empty( $wordform_gcaptcha_secret_key ) || $errors > 0 ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Values are empty.';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'reCaptcha Version not selected or keys not entered.', 'wordform-pro' );
			 }			 
			 else {				
				$recaptcha_type_update = update_option( 'wordform_gcaptcha_type', $wordform_gcaptcha_type );
				$recaptcha_version_update = update_option( 'wordform_gcaptcha_version', $wordform_gcaptcha_version );
				$recaptcha_theme_update = update_option( 'wordform_gcaptcha_theme', $wordform_gcaptcha_theme );
				$site_key_update = update_option( 'wordform_gcaptcha_site_key', $wordform_gcaptcha_site_key );
				$secret_key_update = update_option( 'wordform_gcaptcha_secret_key', $wordform_gcaptcha_secret_key );

				if ( $site_key_update || $secret_key_update || $recaptcha_type_update || $recaptcha_version_update || $recaptcha_theme_update ) { 								
							self::$output['status']     = 'success';
							self::$output['comment']    = 'Updated greCaptchaa setting.';
							self::$output['successMsg'] = self::$success_icon . ' ' . __( 'Updated success.', 'wordform-pro' );
				} else {
							self::$output['status']     = 'success';
							self::$output['comment']    = 'Nothing changes.';
							self::$output['successMsg'] = self::$success_icon . ' ' . __( 'Nothing changes.', 'wordform-pro' );
				}
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		/**
		 * Ajax Request
		 * Settings Menu : hCaptcha Tab
		 * Save hCaptcha tab form data
		 */
		public static function sc_wordform_settings_hcaptcha_tab_form() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output     = array();
			$sanitized_params = isset( $_POST['params']['formData'] ) ? sanitize_text_field( urldecode_deep( $_POST['params']['formData'] ) ) : '';
			wp_parse_str( $sanitized_params, $params );

			$site_key   = isset( $params['wordform-hcaptcha-site-key'] ) ? trim( sanitize_text_field( $params['wordform-hcaptcha-site-key'] ) ) : '';
			$secret_key = isset( $params['wordform-hcaptcha-secret-key'] ) ? trim( sanitize_text_field( $params['wordform-hcaptcha-secret-key'] ) ) : '';
			$theme      = isset( $params['wordform-hcaptcha-theme'] ) ? trim( sanitize_text_field( $params['wordform-hcaptcha-theme'] ) ) : 'light';

			if ( empty( $site_key ) || empty( $secret_key ) ) {
				self::$output['status']  = 'fail';
				self::$output['comment'] = 'Values are empty.';
				self::$output['failMsg'] = self::$error_icon . ' ' . __( 'Site key and secret key are required.', 'wordform-pro' );
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$site_key_update   = update_option( 'wordform_hcaptcha_site_key', $site_key );
			$secret_key_update = update_option( 'wordform_hcaptcha_secret_key', $secret_key );
			$theme_update      = update_option( 'wordform_hcaptcha_theme', $theme );

			if ( $site_key_update || $secret_key_update || $theme_update ) {
				self::$output['status']     = 'success';
				self::$output['comment']    = 'Updated hCaptcha setting.';
				self::$output['successMsg'] = self::$success_icon . ' ' . __( 'Updated success.', 'wordform-pro' );
			} else {
				self::$output['status']     = 'success';
				self::$output['comment']    = 'Nothing changes.';
				self::$output['successMsg'] = self::$success_icon . ' ' . __( 'Nothing changes.', 'wordform-pro' );
			}

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


		/**
		 * Ajax Request
		 * Generate Captcha Image with Captcha data
		 * return - json
		 */
		public static function wordform_generate_captcha_image() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output        = array();
			$captcha_create_info = SftcyWordformCaptcha::wordform_create_captcha_image();
			if ( isset( $captcha_create_info['status'] ) && $captcha_create_info['status'] === 'success' ) {
				self::$output['imageBase64Src'] = $captcha_create_info['imageBase64Src'];
				self::$output['image']          = '<img src="' . $captcha_create_info['imageBase64Src'] . '" alt="Captcha Image" />';
				self::$output['status']         = 'success';
				self::$output['comment']        = 'Captcha image created successfully.';
			} else {
				self::$output['status']     = 'fail';
				self::$output['failDetail'] = $captcha_create_info;
				self::$output['comment']    = 'Captcha image failed to create.';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}


		/**
		 * Ajax Request
		 * Activate - Deactivate Users Form submission data to connected & configured Applications
		 * return - json
		 */
		public static function wordform_forms_data_send_activate_deactivate() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			// print_r( $_POST['params'] );
			// exit;
			$application_slug = isset( $_POST['params']['applicationSlug'] )? sanitize_text_field( $_POST['params']['applicationSlug'] ) : '';
			$configured_status = isset( $_POST['params']['statusChangeTo'] )? sanitize_text_field( $_POST['params']['statusChangeTo'] ) : '';									
			self::$output     = [];						
			if ( isset( $application_slug ) && ! empty( $application_slug ) && isset( $configured_status ) && ! empty( $configured_status ) ) {
				global $wpdb;
				$table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_configured_application_tbl;
				$where = [ 'application_slug' => $application_slug ];														
				$data['configured_status'] = $configured_status; 
				switch ( $application_slug ) {
					case 'googlesheet':																		    
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );													
							self::$output['reason'] = 'Google Sheet updated.';
							self::$output['comment'] = 'Status updated successfully.';
						break;
					case 'googlecalendar':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'Google Calendar app updated.';
							self::$output['comment'] = 'Google Calendar App status updated successfully.';
						break;
					case 'zapier':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );													
							self::$output['reason'] = 'Zapier app updated.';
							self::$output['comment'] = 'Zapier App status updated successfully.';
						break;
					case 'customwebhook':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'Custom Webhook app updated.';
							self::$output['comment'] = 'Custom Webhook App status updated successfully.';
						break;
					case 'slack':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'Slack app updated.';
							self::$output['comment'] = 'Slack App status updated successfully.';
						break;
					case 'mailchimp':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'Mailchimp app updated.';
							self::$output['comment'] = 'Mailchimp App status updated successfully.';
						break;
					case 'mailerlite':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'MailerLite app updated.';
							self::$output['comment'] = 'MailerLite App status updated successfully.';
						break;
					case 'airtable':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'Airtable app updated.';
							self::$output['comment'] = 'Airtable App status updated successfully.';
						break;
					case 'brevo':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'Brevo app updated.';
							self::$output['comment'] = 'Brevo App status updated successfully.';
						break;
					case 'hubspot':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'HubSpot app updated.';
							self::$output['comment'] = 'HubSpot App status updated successfully.';
						break;
					case 'make':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'Make app updated.';
							self::$output['comment'] = 'Make App status updated successfully.';
						break;
					case 'activecampaign':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'ActiveCampaign app updated.';
							self::$output['comment'] = 'ActiveCampaign App status updated successfully.';
						break;
					case 'salesforce':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'Salesforce app updated.';
							self::$output['comment'] = 'Salesforce App status updated successfully.';
						break;
					case 'zohocrm':
							self::$output['status'] = 'success';
							self::$output['dbUpdateReturn'] = $wpdb->update( $table, $data, $where );
							self::$output['reason'] = 'Zoho CRM app updated.';
							self::$output['comment'] = 'Zoho CRM App status updated successfully.';
						break;
				}																
				self::$output['configuredApplication'] = SftcyWordformConnectBase::get_configured_application_option_payload( $application_slug );
				self::$output['configuredStatus']      = $configured_status;
			} else {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Application Slug not found.';
				self::$output['comment'] = 'Application Name not found.';
			}
			echo wp_json_encode( self::$output );
			wp_die();
		}

		/**
		 * Check whether a webhook endpoint URL is reachable without sending a POST payload.
		 * This is a low-risk connectivity check only, not a delivery test.
		 *
		 * @return void
		 */
		public static function wordform_connect_check_webhook_endpoint() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$webhook_url      = isset( $_POST['params']['webhookUrl'] ) ? esc_url_raw( trim( wp_unslash( $_POST['params']['webhookUrl'] ) ) ) : '';
			$application_slug = isset( $_POST['params']['applicationSlug'] ) ? sanitize_key( wp_unslash( $_POST['params']['applicationSlug'] ) ) : '';
			self::$output     = [];

			if ( empty( $webhook_url ) || ! filter_var( $webhook_url, FILTER_VALIDATE_URL ) ) {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Webhook URL is invalid.';
				self::$output['comment'] = 'Please enter a valid webhook URL first.';
				if ( ! empty( $application_slug ) ) {
					SftcyWordformConnectBase::log_connection_configuration_event(
						$application_slug,
						'endpoint_check',
						self::$output['comment'],
						array(),
						'error'
					);
				}
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$request_args = array(
				'timeout'            => 8,
				'redirection'        => 2,
				'method'             => 'HEAD',
				'reject_unsafe_urls' => true,
				'sslverify'          => true,
				'headers'            => array(
					'Accept'     => '*/*',
					'User-Agent' => 'WordForm-Pro/' . ( defined( 'SFTCY_WORDFORM_VERSION' ) ? SFTCY_WORDFORM_VERSION : '1.0.0' ) . '; ' . home_url(),
				),
			);

			$response = wp_remote_request( $webhook_url, $request_args );
			if ( is_wp_error( $response ) ) {
				$request_args['method'] = 'GET';
				$response               = wp_remote_request( $webhook_url, $request_args );
			}

			if ( is_wp_error( $response ) ) {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Webhook endpoint is not reachable.';
				self::$output['comment'] = 'The endpoint could not be reached from this WordPress site. Please check the URL, firewall, or outbound request settings.';
				if ( ! empty( $application_slug ) ) {
					SftcyWordformConnectBase::log_connection_configuration_event(
						$application_slug,
						'endpoint_check',
						self::$output['comment'],
						array(
							'requestError' => $response->get_error_message(),
						),
						'error'
					);
				}
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$response_code = (int) wp_remote_retrieve_response_code( $response );
			$app_label_map = array(
				'zapier'        => 'Zapier',
				'slack'         => 'Slack',
				'make'          => 'Make',
				'customwebhook' => 'Custom Webhook',
			);
			$app_label     = isset( $app_label_map[ $application_slug ] ) ? $app_label_map[ $application_slug ] : 'Webhook';

			if ( $response_code >= 200 && $response_code < 400 ) {
				self::$output['status']  = 'success';
				self::$output['reason']  = $app_label . ' endpoint responded successfully.';
				self::$output['comment'] = $app_label . ' endpoint is reachable from this WordPress site (HTTP ' . $response_code . ').';
			} else {
				self::$output['status']  = 'warning';
				self::$output['reason']  = $app_label . ' endpoint responded with a non-success HTTP code.';
				self::$output['comment'] = $app_label . ' endpoint is reachable (HTTP ' . $response_code . '). This can still be normal for webhook endpoints because WordForm did not send a POST payload during this check.';
			}

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

	} // End Class
}
