<?php
/**
 * Handles all the events that happens in the field editor feature.
 *
 * @package PeachPay
 */

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

require_once PEACHPAY_ABSPATH . 'core/modules/field-editor/admin/settings-field-editor.php';
require_once PEACHPAY_ABSPATH . 'core/modules/field-editor/pp-field-editor-functions.php';

peachpay_setup_field_editor();

/**
 * Sets up the field editor.
 */
function peachpay_setup_field_editor() {
	peachpay_initialize_fields( 'shipping' );
	peachpay_initialize_fields( 'billing' );

	add_filter( 'woocommerce_checkout_fields', 'peachpay_virtual_product_fields_preset', 9999 );
	add_filter( 'peachpay_register_feature', 'peachpay_filter_register_field_editor_support', 10, 1 );

	add_filter( 'woocommerce_checkout_fields', 'peachpay_billing_fields', 10, 1 );
	add_filter( 'woocommerce_checkout_fields', 'peachpay_shipping_fields', 10, 1 );
	add_action( 'woocommerce_checkout_fields', 'peachpay_additional_fields', 10, 1 );

	add_filter( 'woocommerce_form_field', 'peachpay_render_custom_field_types', 10, 3 );
	add_filter( 'pp_checkout_form_field', 'peachpay_render_custom_field_types', 10, 3 );

	// save fields to order meta.
	add_action( 'woocommerce_checkout_update_order_meta', 'peachpay_save_new_fields_data' );
	// WooCommerce handles required field validation automatically based on the 'required' field config.
	// Render a table of custom fields in receipt page.
	add_action( 'woocommerce_order_details_after_order_table', 'peachpay_render_additional_fields_receipt' );

	// Enqueue frontend assets for custom field types.
	add_action( 'wp_enqueue_scripts', 'peachpay_enqueue_field_types_assets' );
	// Also enqueue for Express Checkout (separate page that dequeues all scripts).
	add_action( 'pp_checkout_enqueue_scripts', 'peachpay_enqueue_field_types_assets_express' );
	// Fallback: directly output scripts in Express Checkout if pp_checkout_enqueue_scripts doesn't work.
	add_action( 'wp_head', 'peachpay_maybe_output_field_types_scripts_direct', PHP_INT_MAX );
}

/**
 * Directly outputs field types scripts in Express Checkout context.
 * This is a fallback in case pp_checkout_enqueue_scripts doesn't work.
 */
function peachpay_maybe_output_field_types_scripts_direct() {
	static $already_output = false;

	// Prevent double output.
	if ( $already_output ) {
		return;
	}

	// Only run in Express Checkout context.
	if ( ! function_exists( 'pp_is_express_checkout' ) || ! pp_is_express_checkout() ) {
		return;
	}
	
	// Check if we have any custom field types enabled.
	if ( ! peachpay_has_custom_field_types() ) {
		return;
	}
	
	$already_output = true;
	
	$css_url           = plugin_dir_url( __FILE__ ) . 'assets/css/field-types.css';
	$js_url            = plugin_dir_url( __FILE__ ) . 'assets/js/field-types.js';
	$signature_pad_url = plugin_dir_url( __FILE__ ) . 'assets/js/signature_pad.min.js';
	
	// Output CSS.
	echo '<link rel="stylesheet" href="' . esc_url( $css_url ) . '?ver=' . esc_attr( PEACHPAY_VERSION ) . '" />' . "\n";
	
	// Output scripts.
	echo '<script src="' . esc_url( $signature_pad_url ) . '"></script>' . "\n";
	echo '<script src="' . esc_url( $js_url ) . '?ver=' . esc_attr( PEACHPAY_VERSION ) . '"></script>' . "\n";
}

/**
 * Enqueues the frontend assets for scrollable text and signature field types.
 * This is for classic WooCommerce checkout.
 */
function peachpay_enqueue_field_types_assets() {
	// Check if we have any scrollable_text or signature fields enabled.
	$has_custom_fields = peachpay_has_custom_field_types();

	if ( ! $has_custom_fields ) {
		return;
	}

	// Enqueue CSS.
	wp_enqueue_style(
		'peachpay-field-types',
		plugin_dir_url( __FILE__ ) . 'assets/css/field-types.css',
		array(),
		PEACHPAY_VERSION
	);

	// Enqueue signature_pad library first (dependency for our script).
	wp_enqueue_script(
		'signature-pad',
		plugin_dir_url( __FILE__ ) . 'assets/js/signature_pad.min.js',
		array(),
		PEACHPAY_VERSION,
		true
	);

	// Enqueue JS (depends on signature-pad).
	wp_enqueue_script(
		'peachpay-field-types',
		plugin_dir_url( __FILE__ ) . 'assets/js/field-types.js',
		array( 'signature-pad' ),
		PEACHPAY_VERSION,
		true
	);
}

/**
 * Enqueues the frontend assets for scrollable text and signature field types in Express Checkout.
 * Express Checkout dequeues all normal scripts and requires using PeachPay::enqueue_* methods.
 */
function peachpay_enqueue_field_types_assets_express() {
	// Check if we have any scrollable_text or signature fields enabled.
	$has_custom_fields = peachpay_has_custom_field_types();

	if ( ! $has_custom_fields ) {
		return;
	}

	// For Express Checkout, we need to enqueue using PeachPay methods.
	// CSS - use relative path from plugin root.
	PeachPay::enqueue_style(
		'peachpay-field-types',
		'core/modules/field-editor/assets/css/field-types.css'
	);

	// NOTE: Express Checkout does NOT call wp_footer(), only wp_head()
	// So we must enqueue with in_footer = false for scripts to load.
	
	// Signature pad library - local file (must load before our script).
	PeachPay::enqueue_script(
		'signature-pad',
		'core/modules/field-editor/assets/js/signature_pad.min.js',
		array(),
		false,
		true
	);
	
	// Our main script - depends on signature-pad.
	PeachPay::enqueue_script(
		'peachpay-field-types',
		'core/modules/field-editor/assets/js/field-types.js',
		array( 'signature-pad' ),
		false
	);
}

/**
 * Checks if there are any enabled scrollable_text or signature field types.
 * Result is cached to avoid repeated database queries.
 *
 * @return bool True if custom field types exist.
 */
function peachpay_has_custom_field_types() {
	static $cached_result = null;

	if ( null !== $cached_result ) {
		return $cached_result;
	}

	$sections = array( 'billing', 'shipping', 'additional' );

	foreach ( $sections as $section ) {
		$field_option = get_option( 'peachpay_field_editor_' . $section );

		if ( ! isset( $field_option[ $section ] ) || ! is_array( $field_option[ $section ] ) ) {
			continue;
		}

		foreach ( $field_option[ $section ] as $field ) {
			if ( ! isset( $field['field_enable'] ) || 'yes' !== $field['field_enable'] ) {
				continue;
			}

			if ( isset( $field['type_list'] ) && in_array( $field['type_list'], array( 'scrollable_text', 'signature' ), true ) ) {
				$cached_result = true;
				return true;
			}
		}
	}

	$cached_result = false;
	return false;
}

/**
 * Render function for custom field types specific to the PeachPay field editor.
 *
 * @param string $field The existing field html.
 * @param string $key The fields name/key attribute.
 * @param array  $args The field arguments.
 */
function peachpay_render_custom_field_types( $field, $key, $args ) {
	if ( 'header' === $args['type'] ) {
		return '<h3 class="form-row form-row-wide" data-priority="' . $args['priority'] . '">' . $args['label'] . '</h3>';
	}

	if ( 'scrollable_text' === $args['type'] ) {
		return peachpay_render_scrollable_text_field( $key, $args );
	}

	if ( 'signature' === $args['type'] ) {
		return peachpay_render_signature_field( $key, $args );
	}

	return $field;
}

/**
 * Renders a scrollable text field for terms and conditions.
 *
 * @param string $key The field key/name.
 * @param array  $args The field arguments.
 */
function peachpay_render_scrollable_text_field( $key, $args ) {
	$content        = isset( $args['content'] ) ? $args['content'] : '';
	$required       = isset( $args['required'] ) && $args['required'] ? true : false;
	$required_html  = $required ? '&nbsp;<abbr class="required" title="required">*</abbr>' : '';
	$label          = isset( $args['label'] ) ? $args['label'] : '';
	$class          = isset( $args['class'] ) ? implode( ' ', $args['class'] ) : '';
	$priority       = isset( $args['priority'] ) ? $args['priority'] : 10;

	// Use consistent container: flex col relative (Express Checkout) + form-row (Classic).
	$html = '<div class="form-row flex col relative ' . esc_attr( $class ) . ' pp-scrollable-text-wrapper" id="' . esc_attr( $key ) . '_field" data-priority="' . esc_attr( $priority ) . '" data-field="' . esc_attr( $key ) . '">';

	// Label at top (always visible).
	if ( ! empty( $label ) ) {
		$html .= '<label for="' . esc_attr( $key ) . '" class="pp-scrollable-label">' . esc_html( $label ) . $required_html . '</label>';
	}

	// Always visible scrollable content wrapper (no dropdown, no checkbox).
	$html .= '<div class="pp-scrollable-content-wrapper">';
	$html .= '<div class="pp-scrollable-content" id="' . esc_attr( $key ) . '_content">';
	$html .= wp_kses_post( $content );
	$html .= '</div>';
	// Scroll indicator that shows "✓ Viewed" when scrolled to bottom
	$html .= '<div class="pp-scroll-indicator" id="' . esc_attr( $key ) . '_indicator">';
	$html .= '<span class="pp-scroll-arrow">↓</span>';
	$html .= '<span class="pp-scroll-text">' . esc_html__( 'Please scroll down to acknowledge and accept the ' . $label . '.', 'peachpay-for-woocommerce' ) . '</span>';
	$html .= '</div>';
	$html .= '</div>';

	// Hidden input to track if user has scrolled to bottom (validated state).
	$html .= '<input type="hidden" name="' . esc_attr( $key ) . '" id="' . esc_attr( $key ) . '" class="pp-scrollable-input" data-required="' . ( $required ? '1' : '0' ) . '" />';
	$html .= '</div>';
	return $html;
}

/**
 * Renders a signature field with draw and type modes.
 *
 * @param string $key The field key/name.
 * @param array  $args The field arguments.
 */
function peachpay_render_signature_field( $key, $args ) {
	$required         = isset( $args['required'] ) && $args['required'] ? true : false;
	$required_html    = $required ? '&nbsp;<abbr class="required" title="required">*</abbr>' : '';
	$label            = isset( $args['label'] ) ? $args['label'] : '';
	$class            = isset( $args['class'] ) ? implode( ' ', $args['class'] ) : '';
	$priority         = isset( $args['priority'] ) ? $args['priority'] : 10;

	// Use consistent container: flex col relative (Express Checkout) + form-row (Classic).
	// Always visible - no linked checkbox support for draw-only mode.
	$html = '<div class="form-row flex col relative ' . esc_attr( $class ) . ' pp-signature-wrapper" id="' . esc_attr( $key ) . '_field" data-priority="' . esc_attr( $priority ) . '" data-field="' . esc_attr( $key ) . '">';

	// Label at top.
	$html .= '<label for="' . esc_attr( $key ) . '" class="pp-signature-label">' . esc_html( $label ) . $required_html . '</label>';

	// Draw mode only - no tabs, no type mode.
	$html .= '<div class="pp-signature-draw">';
	$html .= '<canvas class="pp-signature-canvas" id="' . esc_attr( $key ) . '_canvas"></canvas>';
	$html .= '<button type="button" class="pp-signature-clear">' . esc_html__( 'Clear', 'peachpay-for-woocommerce' ) . '</button>';
	$html .= '</div>';

	$html .= '<input type="hidden" name="' . esc_attr( $key ) . '" id="' . esc_attr( $key ) . '" value="" class="pp-signature-data" />';
	$html .= '</div>';

	return $html;
}

/**
 * Sets up all the fields automatically without opening the settings page.
 *
 * @param string $section the target section either billing or shipping.
 */
function peachpay_initialize_fields( $section ) {
	if ( empty( get_option( 'peachpay_field_editor_' . $section ) ) ) {
		peachpay_reset_region_presets_default_fields( $section );
	}
}

/**
 * Registers field editor support.
 *
 * @param array $base_features The existing registered features.
 */
function peachpay_filter_register_field_editor_support( $base_features ) {

	$base_features['enable_virtual_product_fields'] = array(
		'enabled' => peachpay_get_settings_option( 'peachpay_express_checkout_window', 'enable_virtual_product_fields' ),
	);

	return $base_features;
}

/**
 * Init the billing fields.
 *
 * @param array $fields the billing fields that are in the checkout form that is to be adjusted accordingly.
 */
function peachpay_billing_fields( $fields ) {
	return field_adjustments( $fields, 'billing', 'billing' );
}

/**
 * Init the shipping fields.
 *
 * @param array $fields the shipping fields that are in the checkout form that is to be adjusted accordingly.
 */
function peachpay_shipping_fields( $fields ) {
	return field_adjustments( $fields, 'shipping', 'shipping' );
}

/**
 * Sets the WC checkout fields based on the configuration of the PeachPay field editor settings.
 *
 * @param array  $wc_fields The default WC checkout fields for the given section.
 * @param string $section The section of fields to reconfigure.
 * @param string $settings The settings to use field reconfiguration.
 */
function field_adjustments( $wc_fields, $section, $settings ) {
	$priority     = 10;
	$field_option = get_option( 'peachpay_field_editor_' . $settings );

	$field_name_keys = array();
	if ( isset( $field_option[ $settings . '_order' ] ) && is_array( $field_option[ $settings . '_order' ] ) ) {
		foreach ( $field_option[ $settings . '_order' ] as $order ) {

			if ( isset( $field_option[ $settings ][ $order ]['type_list'] ) && 'header' === $field_option[ $settings ][ $order ]['type_list'] ) {
				continue;
			}

			if ( ! isset( $field_option[ $settings ][ $order ]['field_enable'] ) || 'yes' !== $field_option[ $settings ][ $order ]['field_enable'] ) {
				continue;
			}

			array_push( $field_name_keys, $field_option[ $settings ][ $order ]['field_name'] );
		}
	}

	// Remove fields that have been disabled.
	foreach ( $wc_fields[ $section ] as $key => $field ) {
		if ( ! in_array( $key, $field_name_keys, true ) ) {
			if ( 'additional' === $settings && 'order_comments' === $key ) {
				if ( ! function_exists( 'pp_is_express_checkout' ) || ! pp_is_express_checkout() ) {
					continue;
				} elseif ( peachpay_get_settings_option( 'peachpay_express_checkout_window', 'enable_order_notes' ) ) {
					continue;
				}
			}

			unset( $wc_fields[ $section ][ $key ] );
		}
	}

	// Reconfigure and reorder fields
	if ( isset( $field_option[ $settings ] ) && is_array( $field_option[ $settings ] ) ) {
		foreach ( $field_option[ $settings ] as $key => $value ) {
			if ( ! isset( $value['field_enable'] ) || 'yes' !== $value['field_enable'] ) {
				continue;
			}

			if ( is_array( $wc_fields[ $section ] ) && array_key_exists( $value['field_name'], $wc_fields[ $section ] ) ) {
				// Reconfigure existing field.

				$wc_fields[ $section ][ $value['field_name'] ]['priority'] = $priority;
				$wc_fields[ $section ][ $value['field_name'] ]['class'][]  = 'pp-fw-' . $value['width'];

				if ( ! isset( $value['field_required'] ) || '' === $value['field_required'] ) {
					$wc_fields[ $section ][ $value['field_name'] ]['required'] = '';
				}
			} else {
				// Add non default field.

				$field_config = array(
					'type'        => $value['type_list'],
					'label'       => $value['field_label'],
					'label_class' => array( 'peachpay-radio-label' ),
					'required'    => isset( $value['field_required'] ) && 'yes' === $value['field_required'] ? 1 : '',
					'priority'    => $priority,
					'options'     => isset( $value['option'] ) && ! empty( $value['option'] ) ? $value['option'] : '',
					'default'     => $value['field_default'],
					'class'       => array( 'pp-fw-' . $value['width'] ),
				);

				// Add scrollable_text specific config.
				if ( 'scrollable_text' === $value['type_list'] ) {
					if ( isset( $value['field_content'] ) ) {
						$field_config['content'] = $value['field_content'];
					}
				}

				$wc_fields[ $section ][ $value['field_name'] ] = $field_config;

			}
			$priority += 10;
		}
	}

	if ( 'additional' === $settings && isset( $wc_fields[ $section ]['order_comments'] ) ) {
		$wc_fields[ $section ]['order_comments']['priority'] = $priority;
	}

	return $wc_fields;
}

/**
 * Render all additional fields to the checkout page.
 *
 * @param array $checkout The checkout form data that will be used to render new fields.
 */
function peachpay_additional_fields( $checkout ) {
	return field_adjustments( $checkout, 'order', 'additional' );
}

/**
 * Prepares the options array with a default value.
 *
 * @param array  $options the option array from the php data.
 * @param string $default_option the default value for the select box.
 */
function peachpay_set_options_list( $options, $default_option = 'Please select' ) {
	return array_replace( array( '' => $default_option ), $options );
}

/**
 * Update the metadata to all three section of the form section.
 *
 * @param object $order_id takes in the order id.
 */
function peachpay_save_new_fields_data( $order_id ) {
	save_what_we_added( $order_id, 'billing' );
	save_what_we_added( $order_id, 'shipping' );
	save_what_we_added( $order_id, 'additional' );

	save_klaviyo_options();
}

/**
 * Update the metadata when a new field input is added.
 *
 * @param object $order_id takes in the order id.
 * @param string $section the section that is targeted.
 */
function save_what_we_added( $order_id, $section ) {
	$order = wc_get_order( $order_id );

	// phpcs:disable
	if ( 'shipping' === $section && ( empty( $_POST['ship_to_different_address'] ) || ! isset( $_POST['ship_to_different_address'] ) ) ) {
		return;
	}
	// phpcs:enable
	$field_option = get_option( 'peachpay_field_editor_' . $section );
	if ( ! isset( $field_option[ $section . '_order' ] ) || empty( $field_option[ $section . '_order' ] ) ) {
		return;
	}
	foreach ( $field_option[ $section . '_order' ] as $order_number ) {
		$field_name = $field_option[ $section ][ $order_number ]['field_name'];
		$field_type = isset( $field_option[ $section ][ $order_number ]['type_list'] ) ? $field_option[ $section ][ $order_number ]['type_list'] : '';
		
		// Skip headers - they have no data.
		if ( 'header' === $field_type ) {
			continue;
		}
		
		// Skip billing/shipping default fields (they're handled by WooCommerce).
		// But allow additional section default fields (signature, scrollable_text, consent) to be saved.
		if ( 'additional' !== $section && peachpay_is_default_field( $section, $field_name ) ) {
			continue;
		}
		
		if ( ! isset( $field_option[ $section ][ $order_number ]['field_enable'] ) || 'yes' !== $field_option[ $section ][ $order_number ]['field_enable'] ) {
			continue;
		}
		// phpcs:disable
		if ( ! empty( $_POST[ $field_name ] ) ) {
			$order->add_meta_data( $field_name, $_POST[ $field_name ] );
		}
		// phpcs:enable
	}

	$order->save();
}

/**
 * Klaviyo integration-- due to a different submission structure, we need to
 * submit these here rather than integrated into our form save.
 */
function save_klaviyo_options() {
	if ( ! is_plugin_active( 'klaviyo/klaviyo.php' ) ) {
		return;
	}
	$klaviyo_settings = get_option( 'klaviyo_settings' );
	// phpcs:disable WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput
	$email   = isset( $_POST['billing_email'] ) ? esc_html( wp_unslash( $_POST['billing_email'] ) ) : null;
	$phone   = isset( $_POST['billing_phone'] ) ? esc_html( wp_unslash( $_POST['billing_phone'] ) ) : null;
	$country = isset( $_POST['billing_country'] ) ? esc_html( wp_unslash( $_POST['billing_country'] ) ) : null;
	$url     = 'https://a.klaviyo.com/api/webhook/integration/woocommerce?c=' . $klaviyo_settings['klaviyo_public_api_key'];
	$body    = array(
		'data' => array(),
	);

	if ( isset( $_POST['kl_sms_consent_checkbox'] ) && $_POST['kl_sms_consent_checkbox'] ) {
		array_push(
			$body['data'],
			array(
				'customer'     => array(
					'email'   => $email,
					'country' => $country,
					'phone'   => $phone,
				),
				'consent'      => true,
				'updated_at'   => gmdate( DATE_ATOM, date_timestamp_get( date_create() ) ),
				'consent_type' => 'sms',
				'group_id'     => $klaviyo_settings['klaviyo_sms_list_id'],
			)
		);
	}

	if ( isset( $_POST['kl_newsletter_checkbox'] ) && esc_html( wp_unslash( $_POST['kl_newsletter_checkbox'] ) ) ) {
		array_push(
			$body['data'],
			array(
				'customer'     => array(
					'email' => $email,
					'phone' => $phone,
				),
				'consent'      => true,
				'updated_at'   => gmdate( DATE_ATOM, date_timestamp_get( date_create() ) ),
				'consent_type' => 'email',
				'group_id'     => $klaviyo_settings['klaviyo_newsletter_list_id'],
			)
		);
	}
	// phpcs:enable WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput

	wp_remote_post(
		$url,
		array(
			'method'      => 'POST',
			'httpversion' => '1.0',
			'blocking'    => false,
			'headers'     => array(
				'X-WC-Webhook-Topic' => 'custom/consent',
				'Content-Type'       => 'application/json',
			),
			'body'        => wp_json_encode( $body ),
			'data_format' => 'body',
		)
	);
}

/**
 * A custom method to test if the field in the native checkout is require must be filled in else it post a error message banner.
 */
function peachpay_add_form_require_validation() {
	check_if_required( 'additional' );
}

/**
 * Validates all custom fields across all sections (billing, shipping, additional).
 * This is called on woocommerce_checkout_process hook.
 */
function peachpay_validate_all_custom_fields() {
	check_if_required( 'billing' );
	check_if_required( 'shipping' );
	check_if_required( 'additional' );
}

/**
 * A custom method to test if the field in the native checkout is require must be filled in else it post a error message banner.
 *
 * @param string $section the section that is targeted.
 */
function check_if_required( $section ) {
	$field_option = get_option( 'peachpay_field_editor_' . $section );
	if ( ! isset( $field_option[ $section . '_order' ] ) || empty( $field_option[ $section . '_order' ] ) ) {
		return;
	}
	foreach ( $field_option[ $section . '_order' ] as $order_number ) {
		//phpcs:disable
		$field = $field_option[ $section ][ $order_number ];
		
		if ( ! isset( $field['field_enable'] ) || 'yes' !== $field['field_enable'] ) {
			continue;
		}
		
		if ( ! isset( $field['field_required'] ) || 'yes' !== $field['field_required'] ) {
			continue;
		}
		
		$field_name  = $field['field_name'];
		$field_label = $field['field_label'];
		$field_value = isset( $_POST[ $field_name ] ) ? sanitize_text_field( wp_unslash( $_POST[ $field_name ] ) ) : '';
		
		// Standard field validation - WooCommerce handles scrollable_text and signature validation
		// based on whether the hidden input has a value
		if ( empty( $field_value ) ) {
			wc_add_notice( 
				/* translators: %s: Field label */
				sprintf( __( '%s is a required field.', 'peachpay-for-woocommerce' ), $field_label ), 
				'error' 
			);
		}
		//phpcs:enable
	}
}

/**
 * Returns a list of all the enabled field data for rendering in the modal.
 *
 * @param string $section the section that is targeted.
 * @param bool   $ignore_defaults when true, default values will not be included in result.
 */
function peachpay_enabled_field_list( $section, $ignore_defaults = false ) {
	$field_option      = get_option( 'peachpay_field_editor_' . $section );
	$result            = array();
	$next_order_number = 0;

	if ( isset( $field_option[ $section . '_order' ] ) ) {
		foreach ( $field_option[ $section . '_order' ] as $order_number ) {
			$field_name = $field_option[ $section ][ $order_number ]['field_name'];
			$add_field  = ! $ignore_defaults || ! peachpay_is_default_field( $section, $field_name );

			if ( $add_field && isset( $field_option[ $section ][ $order_number ]['field_enable'] ) && 'yes' === $field_option[ $section ][ $order_number ]['field_enable'] ) {
				$result[ $order_number ] = $field_option[ $section ][ $order_number ];
				if ( isset( $field_option[ $section ][ $order_number ]['option'] ) ) {
					$result[ $order_number ]['option_order'] = array();
					foreach ( $field_option[ $section ][ $order_number ]['option'] as $value => $name ) {
						$result[ $order_number ]['option_order'][] = array( $value, $name );
					}
				}
			}
			$next_order_number = $order_number;
		}
		++$next_order_number;
	}

	// Support for third party field editors
	$extra_results = array();

	// Flexible Checkout Fields for WooCommerce
	$fcfw_fields = peachpay_import_fcfw_fields( $section );
	if ( $fcfw_fields ) {
		$extra_results = array_merge( $extra_results, $fcfw_fields );
	}

	// Checkout Field Editor for WooCommerce
	$cfew_fields = peachpay_import_cfew_fields( $section );
	if ( $cfew_fields ) {
		$extra_results = array_merge( $extra_results, $cfew_fields );
	}

	// Checkout Field Manager for WooCommerce
	$cfm_fields = peachpay_import_cfm_fields( $section );
	if ( $cfm_fields ) {
		$extra_results = array_merge( $extra_results, $cfm_fields );
	}

	// Klaviyo integration
	$klaviyo_fields = peachpay_import_klaviyo_checkbox( $section );
	if ( $klaviyo_fields ) {
		$extra_results = array_merge( $extra_results, $klaviyo_fields );
	}

	if ( 0 === count( $result ) ) {
		$next_order_number = 1;
	}
	if ( $extra_results ) {
		foreach ( $extra_results as $extra ) {
			$result[ $next_order_number ] = $extra;
			++$next_order_number;
		}
	}

	return $result;
}

/**
 * Returns a list of enabled field data from the Flexible Checkout Fields for WooCommerce formatted for use in the PeachPay modal.
 *
 * @param string $section the section that is targeted.
 */
function peachpay_import_fcfw_fields( $section ) {
	if ( ! is_plugin_active( 'flexible-checkout-fields/flexible-checkout-fields.php' ) ) {
		return array();
	}

	$fcfw_option = get_option( 'inspire_checkout_fields_settings' );
	if ( 'shipping' === $section ) {
		$fcfw_option = $fcfw_option['shipping'];
	} elseif ( 'billing' === $section ) {
		$fcfw_option = $fcfw_option['billing'];
	} else {
		$fcfw_option = $fcfw_option['order'];
	}

	if ( ! $fcfw_option ) {
		return array();
	}

	$result        = array();
	$result_number = 1;
	foreach ( $fcfw_option as $option ) {
		// Strip out woocommerce defaults
		if ( isset( $option['external_field'] ) || ( isset( $option['type'] ) && peachpay_starts_with( $option['type'], 'inspire' ) ) ) {
			// Convert to PeachPay standard
			if ( '1' === $option['visible'] ) {
				// This feels backwards, but yes, '0' is on and '1' is off.
				continue;
			}
			// Only enable fields our field editor is currently able to support.
			if ( peachpay_is_valid_import_field( 'fcfw', $option['type'] ) ) {
				$result[ $result_number ]['field_enable'] = 'yes';
			} else {
				continue;
			}
			$result[ $result_number ]['field_default']  = isset( $option['default'] ) ? $option['default'] : '';
			$result[ $result_number ]['field_label']    = $option['label'];
			$result[ $result_number ]['field_name']     = $option['name'];
			$result[ $result_number ]['field_required'] = '1' === $option['required'] ? 'yes' : 'no';
			// Some type_list types need to be converted.
			switch ( $option['type'] ) {
				case 'textarea':
				case 'number':
				case 'url':
					$result[ $result_number ]['type_list'] = 'text';
					break;
				case 'phone':
					$result[ $result_number ]['type_list'] = 'tel';
					break;
				case 'inspirecheckbox':
					$result[ $result_number ]['type_list'] = 'checkbox';
					break;
				default: // text, email
					$result[ $result_number ]['type_list'] = $option['type'];
			}
			$result[ $result_number ]['width'] = '100'; // FCFW has no setting for this; default to 100% width

			++$result_number;
		}
	}

	return $result;
}

/**
 * Returns a list of enabled field data from the Checkout Field Editor for WooCommerce formatted for use in the PeachPay modal.
 *
 * @param string $section the section that is targeted.
 */
function peachpay_import_cfew_fields( $section ) {
	// Support for Flexible Checkout Fields for WooCommerce
	if ( ! is_plugin_active( 'woo-checkout-field-editor-pro/checkout-form-designer.php' ) ) {
		return array();
	}

	$fce_option = null;
	if ( 'shipping' === $section ) {
		$fce_option = get_option( 'wc_fields_shipping' );
	} elseif ( 'billing' === $section ) {
		$fce_option = get_option( 'wc_fields_billing' );
	} else {
		$fce_option = get_option( 'wc_fields_additional' );
	}

	if ( ! $fce_option ) {
		return array();
	}

	$result        = array();
	$result_number = 1;
	foreach ( $fce_option as $option ) {
		// Strip out WooCommerce default fields
		if ( isset( $option['type'] ) && isset( $option['name'] ) ) {
			// Convert to PeachPay standard
			if ( ! $option['enabled'] ) {
				continue;
			}
			// Only enable fields our field editor is currently able to support.
			if ( peachpay_is_valid_import_field( 'cfew', $option['type'] ) ) {
				$result[ $result_number ]['field_enable'] = 'yes';
			} else {
				continue;
			}
			$result[ $result_number ]['field_default']  = isset( $option['default'] ) ? $option['default'] : '';
			$result[ $result_number ]['field_label']    = $option['label'];
			$result[ $result_number ]['field_name']     = $option['name'];
			$result[ $result_number ]['field_required'] = '1' === $option['required'] ? 'yes' : 'no';
			// Some type_list types need to be converted.
			switch ( $option['type'] ) {
				case 'textarea':
				case 'number':
				case 'url':
					$result[ $result_number ]['type_list'] = 'text';
					break;
				case 'phone':
					$result[ $result_number ]['type_list'] = 'tel';
					break;
				case 'radio':
					$result[ $result_number ]['type_list'] = 'radio';
					$numoptions                            = count( $option['options'] );
					for ( $i = 0; $i < $numoptions; $i++ ) {
						$n                                        = $i + 1;
						$result[ $result_number ]['option'][ $n ] = $option['options'][ $n ];
						$result[ $result_number ]['option_order'][ $i ] = array( $n, strval( $n ) );
					}
					break;
				default: // text, email
					$result[ $result_number ]['type_list'] = $option['type'];
			}
			$result[ $result_number ]['width'] = '100'; // CFEW has no setting for this; default to 100% width

			++$result_number;
		}
	}

	return $result;
}

/**
 * Returns a list of enabled field data from Klaviyo formatted for use in the PeachPay modal.
 *
 * @param string $section the section that is targeted.
 */
function peachpay_import_klaviyo_checkbox( $section ) {
	// Support for Klaviyo
	if ( ! is_plugin_active( 'klaviyo/klaviyo.php' ) || 'billing' !== $section ) {
		return array();
	}
	$klaviyo_settings = get_option( 'klaviyo_settings' );
	if ( ! $klaviyo_settings || ! $klaviyo_settings['klaviyo_subscribe_checkbox'] ) {
		return array();
	}
	// At least 1 of the newsletter and sms checkbox are active!
	$result = array();
	$i      = 0;

	// Newsletter.
	if ( $klaviyo_settings['klaviyo_subscribe_checkbox'] ) {
		$result[ $i ]['field_default']  = 1;
		$result[ $i ]['field_enable']   = 'yes';
		$result[ $i ]['field_label']    = $klaviyo_settings['klaviyo_newsletter_text'];
		$result[ $i ]['field_name']     = 'kl_newsletter_checkbox';
		$result[ $i ]['field_required'] = 'no';
		$result[ $i ]['type_list']      = 'checkbox';
		$result[ $i ]['width']          = '100'; // default to 100% width
		++$i;
	}

	// SMS.
	if ( $klaviyo_settings['klaviyo_sms_subscribe_checkbox'] ) {
		$result[ $i ]['field_default']  = 1;
		$result[ $i ]['field_enable']   = 'yes';
		$result[ $i ]['field_label']    = $klaviyo_settings['klaviyo_sms_consent_text'];
		$result[ $i ]['field_name']     = 'kl_sms_consent_checkbox';
		$result[ $i ]['field_required'] = 'no';
		$result[ $i ]['type_list']      = 'checkbox';
		$result[ $i ]['width']          = '100'; // default to 100% width
		++$i;
	}

	return $result;
}

/**
 * Returns a list of enabled field data from the Checkout Field Manager for WooCommerce formatted for use in the PeachPay modal.
 *
 * @param string $section the section that is targeted.
 */
function peachpay_import_cfm_fields( $section ) {
	// Support for Checkout Field Manager for WooCommerce
	if ( ! is_plugin_active( 'woocommerce-checkout-manager/woocommerce-checkout-manager.php' ) ) {
		return array();
	}

	$cfm_option = null;
	if ( 'shipping' === $section ) {
		$cfm_option = get_option( 'wooccm_shipping' );
	} elseif ( 'billing' === $section ) {
		$cfm_option = get_option( 'wooccm_billing' );
	} else {
		$cfm_option = get_option( 'wooccm_additional' );
	}

	if ( ! $cfm_option ) {
		return array();
	}

	$result        = array();
	$result_number = 1;
	foreach ( $cfm_option as $option ) {
		// Strip out WooCommerce default fields
		if ( str_contains( $option['key'], 'wooccm' ) ) {
			// Convert to PeachPay standard
			if ( $option['disabled'] ) {
				continue;
			}
			// Only enable fields our field editor is currently able to support.
			if ( peachpay_is_valid_import_field( 'cfm', $option['type'] ) ) {
				$result[ $result_number ]['field_enable'] = 'yes';
			} else {
				continue;
			}
			$result[ $result_number ]['field_default']  = isset( $option['default'] ) ? $option['default'] : '';
			$result[ $result_number ]['field_label']    = $option['label'];
			$result[ $result_number ]['field_name']     = $option['key'];
			$result[ $result_number ]['field_required'] = true === $option['required'] ? 'yes' : 'no';
			// Some type_list types need to be converted.
			switch ( $option['type'] ) {
				case 'textarea':
				case 'number':
					$result[ $result_number ]['type_list'] = 'text';
					break;
				case 'heading':
					$result[ $result_number ]['type_list'] = 'header';
					break;
				case 'radio':
					$result[ $result_number ]['type_list'] = 'radio';
					$numoptions                            = count( $option['options'] );
					for ( $i = 0; $i < $numoptions; $i++ ) {
						$n                                        = $i + 1;
						$label                                    = $option['options'][ $i ]['label'];
						$result[ $result_number ]['option'][ $n ] = $label;
						$result[ $result_number ]['option_order'][ $i ] = array( $label, $label );
					}
					break;
				case 'select':
					$result[ $result_number ]['type_list'] = 'select';
					$numoptions                            = count( $option['options'] );
					for ( $i = 0; $i < $numoptions; $i++ ) {
						$n                                        = $i + 1;
						$label                                    = $option['options'][ $i ]['label'];
						$result[ $result_number ]['option'][ $n ] = $label;
						$result[ $result_number ]['option_order'][ $i ] = array( $label, $label );
					}
					break;
				default: // text, email, tel, checkbox
					$result[ $result_number ]['type_list'] = $option['type'];
			}
			$result[ $result_number ]['width'] = '100'; // default to 100% width

			++$result_number;
		}
	}

	return $result;
}

/**
 * A helper method to determine whether a checkout field in a supported integration is usable by the PeachPay modal or not.
 *
 * @param string $plugin the plugin the field being checked is from.
 * @param string $type the field type being checked.
 */
function peachpay_is_valid_import_field( $plugin, $type ) {
	if ( 'fcfw' === $plugin ) {
		switch ( $type ) {
			case 'header':
			case 'textarea':
			case 'number':
			case 'url':
			case 'phone':
			case 'inspirecheckbox':
			case 'text':
			case 'email':
				return true;
			default:
				return false;
		}
	} elseif ( 'cfew' === $plugin ) {
		switch ( $type ) {
			case 'header':
			case 'textarea':
			case 'number':
			case 'url':
			case 'phone':
			case 'radio':
			case 'text':
			case 'email':
				return true;
			default:
				return false;
		}
	} elseif ( 'cfm' === $plugin ) {
		switch ( $type ) {
			case 'heading':
			case 'textarea':
			case 'number':
			case 'tel':
			case 'radio':
			case 'checkbox':
			case 'text':
			case 'email':
			case 'select':
				return true;
			default:
				return false;
		}
	}
	return false;
}

/**
 * Returns a list of all the enabled field order arrangements for rendering in the modal.
 *
 * @param object $section This is to determin which section it is to pull data from.
 */
function peachpay_enabled_field_list_order( $section ) {
	$field_option = get_option( 'peachpay_field_editor_' . $section );
	$result       = array();
	if ( isset( $field_option[ $section . '_order' ] ) ) {
		foreach ( $field_option[ $section . '_order' ] as $order_number ) {
			if ( isset( $field_option[ $section ][ $order_number ]['field_enable'] ) && 'yes' === $field_option[ $section ][ $order_number ]['field_enable'] ) {
				$result[] = $order_number;
			}
		}
	}

	// Support for third party field editors
	$extra_results = array();

	// Flexible Checkout Fields for WooCommerce
	$fcfw_fields = peachpay_import_fcfw_fields( $section );
	if ( $fcfw_fields ) {
		$extra_results = array_merge( $extra_results, $fcfw_fields );
	}

	// Checkout Field Editor for WooCommerce
	$cfew_fields = peachpay_import_cfew_fields( $section );
	if ( $cfew_fields ) {
		$extra_results = array_merge( $extra_results, $cfew_fields );
	}

	// Checkout Field Manager for WooCommerce
	$cfm_fields = peachpay_import_cfm_fields( $section );
	if ( $cfm_fields ) {
		$extra_results = array_merge( $extra_results, $cfm_fields );
	}

	// Klaviyo
	$klaviyo_fields = peachpay_import_klaviyo_checkbox( $section );
	if ( $klaviyo_fields ) {
		$extra_results = array_merge( $extra_results, $klaviyo_fields );
	}

	if ( $extra_results ) {
		$num_fields        = count( $result );
		$num_new_fields    = count( $extra_results );
		$next_order_number = 0 === $num_fields ? 0 : $result[ $num_fields - 1 ];
		++$next_order_number;
		for ( $i = 0; $i < $num_new_fields; $i++ ) {
			$result[ $num_fields ] = $next_order_number;
			++$num_fields;
			++$next_order_number;
		}
	}

	return $result;
}

/**
 * Returns a list of all peachpay additional fields (enabled or not).
 */
function peachpay_additional_field_list() {
	$field_option = get_option( 'peachpay_field_editor_additional' );
	if ( ! isset( $field_option['additional_order'] ) ) {
		return;
	}
	return $field_option['additional'];
}

/**
 * An additional field in this function's scope is considered a field either in the additional field section
 * or a non-default field within the any of the other sections (such as billing or shipping). All fields
 * that made this criteria and are enabled will be returned as a list.
 */
function peachpay_all_additional_enabled_field_list() {
	$fields         = array();
	$check_sections = array(
		'billing'    => true,
		'shipping'   => true,
		'additional' => false,
	);

	foreach ( $check_sections as $section => $drop_defaults ) {
		$result = peachpay_enabled_field_list( $section, $drop_defaults );
		if ( isset( $result ) ) {
			$fields = array_merge( $fields, $result );
		}
	}

	return $fields;
}

// Display peachpay additional fields in the order admin panel.
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'peachpay_display_additional_fields_in_admin' );

/**
 * Gets order meta only for the given field names. Avoids get_meta_data() which in HPOS can trigger
 * get_orders_type() for every meta row when the order has many meta entries.
 *
 * @param WC_Order $order      Order object.
 * @param array    $fields_list Array of field configs with 'field_name' key.
 * @return array Keyed by field_name, value is array( 'key' => field_name, 'value' => meta value ).
 */
function peachpay_get_order_meta_for_fields( $order, $fields_list ) {
	$result = array();
	if ( ! is_object( $order ) || ! method_exists( $order, 'get_meta' ) ) {
		return $result;
	}
	foreach ( $fields_list as $field ) {
		$name = isset( $field['field_name'] ) ? $field['field_name'] : null;
		if ( empty( $name ) ) {
			continue;
		}
		$value = $order->get_meta( $name, true );
		$result[ $name ] = array(
			'key'   => $name,
			'value' => $value,
		);
	}
	return $result;
}

/**
 * Displays peachpay additional fields in the order admin panel.
 *
 * @param WC_Order $order Order object.
 */
function peachpay_display_additional_fields_in_admin( $order ) {
	$all_additional_fields = peachpay_all_additional_enabled_field_list();  // get list of enabled peachpay additional fields.
	$order_meta            = peachpay_get_order_meta_for_fields( $order, $all_additional_fields );

	if ( empty( $order_meta ) || empty( $all_additional_fields ) ) {
		return;
	}

	?>
	<div class="address">
		<h3><?php esc_html_e( 'Additional information', 'peachpay-for-woocommerce' ); ?></h3>
		<div style="margin-top: 10px;">
			<?php
			foreach ( $all_additional_fields as $array ) {
				$field_label = $array['field_label'];
				$field_type  = isset( $array['type_list'] ) ? $array['type_list'] : 'text';
				
				// Skip headers - they have no data to display.
				if ( 'header' === $field_type ) {
					continue;
				}
				?>
				<div style="margin-bottom: 10px;">
					<strong> <?php echo esc_html( $field_label . ':' ); ?> </strong>
					<?php

					if ( isset( $order_meta[ $array['field_name'] ] ) ) {
						$field_value = $order_meta[ $array['field_name'] ]['value'];

						// Display signature fields as images.
						if ( 'signature' === $field_type && strpos( $field_value, 'data:image/' ) === 0 ) {
							?>
							<br />
							<img 
								src="<?php echo esc_attr( $field_value ); ?>" 
								alt="<?php echo esc_attr( $field_label ); ?>" 
								style="max-width: 300px; border: 1px solid #ccc; background: #fff; padding: 5px; margin-top: 5px;"
							/>
							<?php
						} elseif ( 'scrollable_text' === $field_type ) {
							// Display scrollable text acknowledgment.
							if ( '1' === $field_value ) {
								echo '<span style="color: #28a745;">&#10003; ' . esc_html__( 'Acknowledged', 'peachpay-for-woocommerce' ) . '</span>';
							} else {
								echo '<span style="color: #dc3545;">' . esc_html__( 'Not acknowledged', 'peachpay-for-woocommerce' ) . '</span>';
							}
						} else {
							// Converts option value to option text (more readable for customer).
							if ( isset( $array['option'] ) && isset( $array['option'][ $field_value ] ) ) {
								$field_value = $array['option'][ $field_value ];
							}
							echo esc_html( $field_value );
						}
					} else {
						echo esc_html( 'empty' );
					}
					?>
				</div>
				<?php
			}
			?>
		</div>
	</div>
	<?php
}

/**
 * Returns the "intersetion" of two arrays as follows: each input is an array of keyed arrays;
 * find the matching keys and return a keyed array with the matching keys and corresponding values.
 *
 * This function is different than PHP's array_intersect in that it matches on keys. This one does
 * some pre-processing on the input arrays, then calls array_intersect_key.
 *
 * @param Array $meta_data An array whose keys to compare to the other array's keys.
 * @param Array $fields_list An array whose keys to compare to the other array's keys.
 * @return Array An array with the matching keys and corresponding values.
 */
function get_array_intersection( $meta_data, $fields_list ) {
	$meta_extracted = array_map(
		function ( $v ) {
            return [ $v->get_data()['key'] => $v->get_data() ];  // phpcs:ignore
		},
		$meta_data
	);

	$meta_extracted_keyed = array_merge( ...$meta_extracted );
	$fields_extracted     = array_map(
		function ( $v ) {
            return [ $v['field_name'] => $v ];  // phpcs:ignore
		},
		$fields_list
	);

	if ( empty( $fields_extracted ) ) {
		return array();
	}

	$fields_extracted_keyed = array_merge( ...$fields_extracted );
	return array_intersect_key( $meta_extracted_keyed, $fields_extracted_keyed );
}

/**
 * Renders a table of custom fields in the receipt page under Order Details.
 * If there are no custom fields. Nothing will be echoed.
 *
 * @param Object $param an object passed in by a hook that contains useful data such as order number.
 */
function peachpay_render_additional_fields_receipt( $param ) {
	if ( ! is_object( $param ) || ! method_exists( $param, 'get_id' ) ) {
		return;
	}

	$order = wc_get_order( $param->get_id() );
	if ( ! $order ) {
		return;
	}
	$fields     = peachpay_all_additional_enabled_field_list();
	$order_data = peachpay_get_order_meta_for_fields( $order, $fields );

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

	?>
	<table id='pp-receipt_additional_fields' style='table-layout: fixed;'>
	<tr>
		<th> <?php esc_html_e( 'Additional information', 'peachpay-for-woocommerce' ); ?> </th>
		<th></th>
	</tr>
	<?php

	foreach ( $fields as $array ) {
		$field_type = isset( $array['type_list'] ) ? $array['type_list'] : 'text';
		
		// Skip headers - they have no data to display.
		if ( 'header' === $field_type ) {
			continue;
		}
		
		if ( isset( $order_data[ $array['field_name'] ]['value'] ) ) {
			$value = $order_data[ $array['field_name'] ]['value'];
			?>
			<tr style='word-wrap: break-word'>
				<td> <?php echo esc_html( $array['field_label'] ); ?> </td>
				<td>
				<?php
				// Display signature fields as images.
				if ( 'signature' === $field_type && strpos( $value, 'data:image/' ) === 0 ) {
					?>
					<img 
						src="<?php echo esc_attr( $value ); ?>" 
						alt="<?php echo esc_attr( $array['field_label'] ); ?>" 
						style="max-width: 200px; border: 1px solid #ccc; background: #fff; padding: 3px;"
					/>
					<?php
				} elseif ( 'scrollable_text' === $field_type ) {
					// Display scrollable text acknowledgment.
					if ( '1' === $value ) {
						echo '<span style="color: #28a745;">&#10003; ' . esc_html__( 'Acknowledged', 'peachpay-for-woocommerce' ) . '</span>';
					} else {
						echo '<span style="color: #dc3545;">' . esc_html__( 'Not acknowledged', 'peachpay-for-woocommerce' ) . '</span>';
					}
				} else {
					// Converts option value to option text (more readable for customer).
					if ( isset( $array['option'] ) && isset( $array['option'][ $value ] ) ) {
						$value = $array['option'][ $value ];
					}
					echo esc_html( $value );
				}
				?>
				</td>
			</tr>
			<?php
		}
	}
	?>
	</table>
	<?php
}

/**
 * Adds enabled field data to the order emails.
 *
 * @param Array    $fields to be added to.
 * @param Boolean  $sent_to_admin flag.
 * @param WC_Order $order in question.
 */
function peachpay_add_fields_to_emails( $fields, $sent_to_admin, $order ) {
	$custom_field_sections = array();

	$billing_fields = get_option( 'peachpay_field_editor_billing', array( 'billing' => array() ) );
	if ( is_array( $billing_fields ) && isset( $billing_fields['billing'] ) ) {
		$custom_field_sections['billing'] = $billing_fields['billing'];
	}

	$shipping_fields = get_option( 'peachpay_field_editor_shipping', array( 'shipping' => array() ) );
	if ( is_array( $shipping_fields ) && isset( $shipping_fields['shipping'] ) ) {
		$custom_field_sections['shipping'] = $shipping_fields['shipping'];
	}

	$additional_fields = get_option( 'peachpay_field_editor_additional', array( 'additional' => array() ) );
	if ( is_array( $additional_fields ) && isset( $additional_fields['additional'] ) ) {
		$custom_field_sections['additional'] = $additional_fields['additional'];
	}

	foreach ( $custom_field_sections as $section => $custom_fields ) {
		foreach ( $custom_fields as $custom_field ) {
			// Skip if field_name is not set
			if ( ! isset( $custom_field['field_name'] ) ) {
				continue;
			}
			
			// Skip billing/shipping default fields but allow additional section fields.
			$is_default = peachpay_is_default_field( $section, $custom_field['field_name'] );
			if ( 'additional' !== $section && $is_default ) {
				continue;
			}
			
			// Skip if field_enable is not set or not enabled
			if ( ! isset( $custom_field['field_enable'] ) || 'yes' !== $custom_field['field_enable'] ) {
				continue;
			}
			
			$field_value = $order->get_meta( $custom_field['field_name'], true );
			$field_type  = isset( $custom_field['type_list'] ) ? $custom_field['type_list'] : 'text';
			
			// Format signature and scrollable_text values for email.
			if ( 'signature' === $field_type && ! empty( $field_value ) && strpos( $field_value, 'data:image/' ) === 0 ) {
				$field_value = '<img src="' . esc_attr( $field_value ) . '" alt="' . esc_attr( $custom_field['field_label'] ) . '" style="max-width: 200px;" />';
			} elseif ( 'scrollable_text' === $field_type ) {
				$field_value = '1' === $field_value ? 'Acknowledged' : 'Not acknowledged';
			}

			$fields[ $custom_field['field_name'] ] = array(
				'label' => $custom_field['field_label'],
				'value' => $field_value,
			);
		}
	}

	return $fields;
}
add_filter( 'woocommerce_email_order_meta_fields', 'peachpay_add_fields_to_emails', 10, 3 );
