<?php

/**
 * The file that defines the core plugin formatter class
 *
 * @link       https://wpconfiguratorbuilder.com
 * @since      1.0.0
 *
 * @package    wcb-configurator-builder
 * @subpackage wcb-configurator-builder/includes
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * The core plugin formatter handler class.
 *
 * This is used to define all formatting and sanitization hooks.
 *
 * @since      1.0.0
 * @package    wcb-configurator-builder
 * @subpackage wcb-configurator-builder/includes
 * @author     WPCB <support@wpconfiguratorbuilder.com>
 */
class WPCB_Formatter {

	/**
	 * Format configurator form output
	 *
	 * @since    1.0.0
	 */
	public static function get_configurator_form_fields( $wpcb_configurator_id ) {
		global $wpcb_price_rates;
		if ( ! $wpcb_price_rates ) {
			wpcb_define_price_rates();
		}

		$price_visible = 'no' !== get_post_meta( $wpcb_configurator_id, '_show_price', true );
		if ( ! is_user_logged_in() && wpcb_get_option( 'wpcb_show_prices_logged_in_users' ) ) {
			$price_visible = false;
		}
		$wpcb_price_rates['price_visible'] = $price_visible;

		$formatted_fields = array();

		$post = get_post( $wpcb_configurator_id ); 
		if ( ! has_blocks( $post->post_content ) ) {
			return $formatted_fields;
		}
	
		$configurator_fields = parse_blocks( $post->post_content );
		if ( ! is_array( $configurator_fields ) || 0 === count( $configurator_fields ) ) {
			return $formatted_fields;
		}

		$step_index = 1;

		foreach ( $configurator_fields as $index => $configurator_field ) {

			if ( 'carbon-fields/wcb-accordeon' === $configurator_field['blockName'] ) {
				if ( ! isset( $configurator_field['attrs']['data']['wpcb_accordeon_title'] ) ) {
					continue;
				}

				$accordeon = array(
					'template' => 'accordeon',
					'id' => wpcb_sanitize_title( $configurator_field['attrs']['data']['wpcb_accordeon_title'] ),
					'title' => wpcb__( $configurator_field['attrs']['data']['wpcb_accordeon_title'], 'accordeon_' . $index . '_title' ),
					'description' => '',
					'collapsed' => false,
				);

				if ( isset( $configurator_field['attrs']['data']['wpcb_accordeon_description'] ) ) {
					$accordeon['description'] = wpcb__( $configurator_field['attrs']['data']['wpcb_accordeon_description'], 'accordeon_' . $index . '_description' );
				}
				if ( isset( $configurator_field['attrs']['data']['wpcb_accordeon_collapsible_state'] ) ) {
					$accordeon['collapsed'] = $configurator_field['attrs']['data']['wpcb_accordeon_collapsible_state'];
				}

				$accordeon = self::get_configurator_sub_fields( $accordeon, $configurator_field );

				$formatted_fields[] = $accordeon;

			} else if ( 'carbon-fields/wcb-tab' === $configurator_field['blockName'] ) {

				if ( ! isset( $configurator_field['attrs']['data']['wpcb_tab_title'] ) ) {
					continue;
				}

				$tab = self::get_configurator_tab( $configurator_field, $index );;
				if ( ! $tab ) {
					continue;
				}

				$formatted_fields[] = $tab;

			} else if ( 'carbon-fields/wcb-step' === $configurator_field['blockName'] ) {
				if ( ! isset( $configurator_field['attrs']['data']['wpcb_step_title'] ) ) {
					continue;
				}

				$step = array(
					'template' => 'step',
					'id' => wpcb_sanitize_title( $configurator_field['attrs']['data']['wpcb_step_title'] ),
					'number' => $step_index,
					'icon' => '',
					'title' => wpcb__( $configurator_field['attrs']['data']['wpcb_step_title'], 'step_' . $index . '_title' ),
					'description' => '',
					'button' => '',
					'hidden' => isset( $configurator_field['attrs']['data']['wpcb_hide_step_title'] ) ? $configurator_field['attrs']['data']['wpcb_hide_step_title'] : '',
				);
				if ( isset( $configurator_field['attrs']['data']['wpcb_step_icon'] ) ) {
					$step['icon'] = wp_get_attachment_image( $configurator_field['attrs']['data']['wpcb_step_icon'], 'thumbnail' );
				}
				if ( isset( $configurator_field['attrs']['data']['wpcb_step_description'] ) ) {
					$step['description'] = wpcb__( $configurator_field['attrs']['data']['wpcb_step_description'], 'step_' . $index . '_description' );
				}
				if ( isset( $configurator_field['attrs']['data']['wpcb_step_button_text'] ) ) {
					$step['button'] = wpcb__( $configurator_field['attrs']['data']['wpcb_step_button_text'], 'step_' . $index . '_button' );
				}

				$step = self::get_configurator_sub_fields( $step, $configurator_field );

				$formatted_fields[] = $step;

				$step_index++;

			} else if ( 'carbon-fields/wcb-group' === $configurator_field['blockName'] ) {

				$formatted_fields[] = self::get_configurator_field_group( $configurator_field, 'fieldgroup_' . $index );

			} else if ( 'carbon-fields/wcb-filter' === $configurator_field['blockName'] ) {

				$formatted_fields[] = self::get_configurator_field_filter( $configurator_field, 'fieldfilter_' . $index );

			} else if ( 'carbon-fields/wcb-repeater' === $configurator_field['blockName'] ) {

				$formatted_fields[] = self::get_configurator_repeater( $configurator_field, 'repeater' . $index );

			} else if ( 'carbon-fields/wcb-input' === $configurator_field['blockName'] ) {
				$field_data = self::get_configurator_input( $configurator_field );

				if ( $field_data ) {
					$formatted_fields[] = $field_data;
				}
			} else if ( 'carbon-fields/wcb-choice' === $configurator_field['blockName'] ) {

				$input_data = self::get_configurator_choice( $configurator_field );

				if ( $input_data ) {
					$formatted_fields[] = $input_data;
				}

			} else if ( 'carbon-fields/wcb-summary' === $configurator_field['blockName'] ) {

				$formatted_fields[] = array(
					'template' => 'summary',
				);

			} else if ( 'carbon-fields/wcb-shortcode' === $configurator_field['blockName'] ) {

				$formatted_fields[] = array(
					'template' => 'shortcode',
					'shortcode' => $configurator_field['attrs']['data']['wpcb_shortcode']
				);

			} else if ( 'carbon-fields/wcb-html' === $configurator_field['blockName'] ) {

				$formatted_fields[] = array(
					'template' => 'html',
					'html' => $configurator_field['attrs']['data']['wpcb_html']
				);
			}
		}

		$formatted_fields = apply_filters( 'wpcb_get_formatted_fields', $formatted_fields, $wpcb_configurator_id );

		return $formatted_fields;
	}

	/**
	 * Format configurator field group data
	 *
	 * @since    1.0.0
	 */
	public static function get_configurator_field_filter( $field, $context = ''  ) {
		$filter = array(
			'template' => 'field-filter',
			'subfields' => array(),
		);

		$field_data = $field['attrs']['data'];

		$filter['label'] = wpcb__( $field_data['wpcb_fieldfilter_label'], $context . '_label' );
		$filter['description'] = isset( $field_data['wpcb_fieldfilter_description'] ) ? wpcb__( $field_data['wpcb_fieldfilter_description'], $context . '_description' ) : '';
		$filter['clear_label'] = isset( $field_data['wpcb_fieldfilter_clear_label'] ) ? wpcb__( $field_data['wpcb_fieldfilter_clear_label'], $context . '_clear_label' ) : '';
		$filter['show_inline'] = $field_data['wpcb_fieldfilter_inline'] ?? false;
		// $filter['collapsible'] = $field_data['wpcb_fieldfilter_collapsible'] ?? false;
		// $filter['collapsed'] = $field_data['wpcb_fieldfilter_collapsible_state'] ?? false;

		if ( isset( $field_data['wpcb_fieldfilter_button'] ) ) {
			$filter['button_text'] = wpcb__( $field_data['wpcb_fieldfilter_button'], $context . '_button' );
		}

		$subfields = $field_data['wpcb_fieldfilter_choices'] ?? [];
		if ( is_array( $subfields ) && count( $subfields ) > 0 ) {
			foreach ( $subfields as $subfield_id ) {
				$subfield_data = self::get_configurator_choice( '', $subfield_id );

				if ( isset( $field_data['wpcb_fieldfilter_collapsible'] ) ) {
					$subfield_data['field']['collapsible'] = $field_data['wpcb_fieldfilter_collapsible'];
				}
				if ( isset( $field_data['wpcb_fieldfilter_collapsible_state'] ) ) {
					$subfield_data['field']['collapsed'] = $field_data['wpcb_fieldfilter_collapsible_state'];
				}

				$filter['subfields'][] = $subfield_data;
			}
		}

		$filter = apply_filters( 'wpcb_get_formatted_field_filter', $filter, $field );

		return $filter;
	}

	/**
	 * Format configurator tab data
	 *
	 * @since    1.0.0
	 */
	public static function get_configurator_tab( $field, $index ) {
		$tab = array(
			'template' => 'tab',
			'id' => '',
			'title' => '',
			'icon' => ''
		);

		if ( isset( $field['attrs']['data']['wpcb_tab_title'] ) ) {
			$tab['id'] = wpcb_sanitize_title( $field['attrs']['data']['wpcb_tab_title'] );
			$tab['title'] = wpcb__( $field['attrs']['data']['wpcb_tab_title'], 'tab_' . $index . '_title' );
		}

		if ( isset( $field['attrs']['data']['wpcb_tab_icon'] ) && $field['attrs']['data']['wpcb_tab_icon'] ) {
			$tab['icon'] = wp_get_attachment_image( $field['attrs']['data']['wpcb_tab_icon'], 'thumbnail' );

			if ( '' == $tab['id'] ) {
				$tab['id'] = $field['attrs']['data']['wpcb_tab_icon'];
			}
		}

		if ( '' == $tab['id'] ) {
			// No tab title or icon set. Abort.
			return false;
		}

		$tab = self::get_configurator_sub_fields( $tab, $field );

		return $tab;
	}

	/**
	 * Format configurator field group data
	 *
	 * @since    1.0.0
	 */
	public static function get_configurator_field_group( $field, $context = '' ) {
		$group = array(
			'template' => 'field-group',
			'subfields' => array(),
		);

		$field_data = $field['attrs']['data'];

		$group['label'] = isset( $field_data['wpcb_fieldgroup_label'] ) ? wpcb__( $field_data['wpcb_fieldgroup_label'], $context . '_label' ) : '';
		$group['description'] = isset( $field_data['wpcb_fieldgroup_description'] ) ? wpcb__( $field_data['wpcb_fieldgroup_description'], $context . '_description' ) : '';
		$group['single_value'] = $field_data['wpcb_fieldgroup_single_value'] ?? false;
		$group['single_price'] = $field_data['single_price'] ?? false;

		if ( isset( $field_data['wpcb_fieldgroup_collapsible'] ) ) {
			$group['collapsible'] = $field_data['wpcb_fieldgroup_collapsible'];
		}
		if ( isset( $field_data['wpcb_fieldgroup_collapsible_state'] ) ) {
			$group['collapsed'] = $field_data['wpcb_fieldgroup_collapsible_state'];
		}

		if ( $group['single_value'] ) {
			$group['group_value'] = $field_data['wpcb_fieldgroup_value'];
		}

		if ( $group['single_price'] && function_exists('wpcb_get_formula_equasion') ) {
			// Advanced calculation plugin active.
			$group['price_type'] = $field_data['price_type'];

			if ( ( 'formula' == $group['price_type'] || 'matrix-formula' == $group['price_type'] ) ) {
				$group['price_formula'] = wpcb_get_formula_equasion( $field_data['price_formula'] );
				$group['price_rounding'] = wpcb_get_formula_rounding( $field_data['price_formula'] );
			}

			if ( 'matrix' == $group['price_type'] || 'matrix-formula' == $group['price_type'] ) {
				$group['price_table'] = $field_data['price_table'];
				$group['price_table_x'] = get_post_meta( $field_data['price_table_x'], '_label', true );
				$group['price_table_y'] = get_post_meta( $field_data['price_table_y'], '_label', true );
				$group['price_table_tx'] = ( get_post_type( $field_data['price_table_x'] ) === 'wpcb_choice' ) ? 'text' : 'numeric';
				$group['price_table_ty'] = ( get_post_type( $field_data['price_table_y'] ) === 'wpcb_choice' ) ? 'text' : 'numeric';
			}
		}

		$group = self::get_configurator_sub_fields( $group, $field );

		$group = self::get_configurator_conditional_rules( $group, $field );

		$group = apply_filters( 'wpcb_get_formatted_field_group', $group, $field );

		return $group;
	}

	/**
	 * Format configurator field group data
	 *
	 * @since    1.0.0
	 */
	public static function get_configurator_repeater( $field, $context = ''  ) {
		$labels = $field['attrs']['data'];

		$repeater = array(
			'template' => 'repeater',
			'label' => isset( $labels['wpcb_repeater_label'] ) ? wpcb__( $labels['wpcb_repeater_label'], $context . '_label' ) : '',
			'empty_text' => isset( $labels['wpcb_repeater_empty_note'] ) ? wpcb__( $labels['wpcb_repeater_empty_note'], $context . '_empty_note' ) : '',
			'add_text' => isset( $labels['wpcb_repeater_add_text'] ) ? wpcb__( $labels['wpcb_repeater_add_text'], $context . '_add_text' ) : '',
			'collapsible' => ( isset( $labels['wpcb_repeater_collapsible'] ) && $labels['wpcb_repeater_collapsible'] ),
			'min' => 0,
			'max' => isset( $labels['wpcb_repeater_max'] ) && $labels['wpcb_repeater_max'] ? intval( $labels['wpcb_repeater_max'] ) : 999,
		);

		$repeater['id'] = wpcb_sanitize_title( $repeater['label'] );

		$repeater = self::get_configurator_sub_fields( $repeater, $field );

		$repeater = self::get_configurator_conditional_rules( $repeater, $field );

		$repeater = apply_filters( 'wpcb_get_formatted_repeater', $repeater, $field );

		return $repeater;
	}

	/**
	 * Format configurator field group data
	 *
	 * @since    1.0.0
	 */
	public static function get_configurator_sub_fields( $wpcb_field, $block_field ) {
		if ( is_array( $block_field['innerBlocks'] ) && 0 < count( $block_field['innerBlocks'] ) ) {
			$wpcb_field['subfields'] = array();

			foreach ( $block_field['innerBlocks'] as $subindex => $subfield ) {
				$subfield_data = false;

				if ( 'carbon-fields/wcb-input' === $subfield['blockName'] ) {

					$subfield_data = self::get_configurator_input( $subfield );

				} else if ( 'carbon-fields/wcb-choice' === $subfield['blockName'] ) {

					$subfield_data = self::get_configurator_choice( $subfield );

				} else if ( 'carbon-fields/wcb-tab' === $subfield['blockName'] ) {

					$subfield_data = self::get_configurator_tab( $subfield, $subindex );

				} else if ( 'carbon-fields/wcb-repeater' === $subfield['blockName'] ) {

					$subfield_data = self::get_configurator_repeater( $subfield, 'repeater' . $subindex );

				} else if ( 'carbon-fields/wcb-filter' === $subfield['blockName'] ) {

					$subfield_data = self::get_configurator_field_filter( $subfield, 'fieldfilter_' . $subindex  );

				} else if ( 'carbon-fields/wcb-group' === $subfield['blockName'] ) {

					$subfield_data = self::get_configurator_field_group( $subfield, 'fieldgroup_' . $subindex );

				} else if ( 'carbon-fields/wcb-html' === $subfield['blockName'] ) {

					$subfield_data = array(
						'template' => 'html',
						'html' => $subfield['attrs']['data']['wpcb_html']
					);

				} else if ( 'carbon-fields/wcb-summary' === $subfield['blockName'] ) {

					$subfield_data = array(
						'template' => 'summary',
					);

				} else if ( 'carbon-fields/wcb-shortcode' === $subfield['blockName'] ) {

					$subfield_data = array(
						'template' => 'shortcode',
						'shortcode' => $subfield['attrs']['data']['wpcb_shortcode']
					);

				}

				if ( 'carbon-fields/wcb-input' === $subfield['blockName'] || 'carbon-fields/wcb-choice' === $subfield['blockName'] ) {
					if ( $subfield_data && isset( $subfield['attrs']['data']['width'] ) ) {
						$subfield_data['width'] = $subfield['attrs']['data']['width'];
						$subfield_data['width_mobile'] = $subfield['attrs']['data']['width_mobile'];
					}
				}

				if ( $subfield_data ) {
					$wpcb_field['subfields'][] = $subfield_data;
				}
			}
		}

		return $wpcb_field;
	}

	/**
	 * Format configurator choice field data
	 *
	 * @since    1.0.0
	 */
	public static function get_configurator_choice( $wpcb_field, $wpcb_field_id = '' ) {
		global $wpcb_price_rates;

		$field_data = false;
		$field_hidden = false;
		if ( isset( $wpcb_field['attrs']['data'] ) ) {
			$field_data = $wpcb_field['attrs']['data'];
			$wpcb_field_id = $field_data['wpcb_field'];
			$field_hidden = isset( $field_data['wpcb_field_hidden'] ) ? $field_data['wpcb_field_hidden'] : false;
		}

		if ( ! $wpcb_field_id ) {
			return false;
		}
		
		$wpcb_field_meta = get_post_meta( $wpcb_field_id );
		if ( ! isset( $wpcb_field_meta['_type'][0] ) ) {
			return false;
		}

		$option_type = $wpcb_field_meta['_type'][0];
		$context = wpcb_sanitize_title( get_the_title( $wpcb_field_id ) );

		$choice = array(
			'id' => $wpcb_field_id,
			'post_id' => $wpcb_field_id,
			'template' => 'choice',
			'field' => array(
				'type' => $option_type,
				'template' => $wpcb_field_meta['_template'][0],
				'label' => wpcb__( $wpcb_field_meta['_label'][0], $context . '_label' ),
				'class' => $wpcb_field_meta['_class'][0],
				'hidden' => $field_hidden,
				'default' => array(),
				'tax_percent' => 0,
			),
			'visual' => array(),
			'options' => array(),
		);

		if ( isset( $field_data['wpcb_field_default_option'] ) && isset( $field_data['wpcb_field_set_default_option'] ) && $field_data['wpcb_field_set_default_option'] ) {
			$choice['field']['default'][] = $field_data['wpcb_field_default_option'];
		}

		if ( isset( $wpcb_field_meta['_tax_class'] ) && class_exists( 'WC_Tax' ) && 'yes' === get_option( 'woocommerce_calc_taxes' ) ) {
			$tax_class = sanitize_text_field( $wpcb_field_meta['_tax_class'][0] );
			$tax_rates = WC_Tax::get_rates_for_tax_class( $tax_class );

			if ( is_array( $tax_rates ) && count( $tax_rates ) > 0 ) {
				$tax = reset( $tax_rates );
				$choice['field']['tax_percent'] = $tax->tax_rate;
			}
		}

		if ( isset( $field_data['wpcb_field_collapsible'] ) ) {
			$choice['field']['collapsible'] = $field_data['wpcb_field_collapsible'];
			$choice['field']['collapsed']   = $field_data['wpcb_field_collapsible_state'];
		}

		$i18n_meta_keys = array( '_placeholder', '_note', '_description' );
		$field_meta_keys = wpcb_get_choice_field_meta_keys();

		foreach ( $field_meta_keys as $field_key => $field_meta_key ) {
			if ( isset( $wpcb_field_meta[ $field_meta_key ] ) && '' !== $wpcb_field_meta[ $field_meta_key ] ) {
				if ( '_swatch_inline_display' === $field_meta_key || '_dropdown_display' === $field_meta_key ) {
					$value = unserialize( $wpcb_field_meta[ $field_meta_key ][0] );

					if ( $value && is_array( $value ) ) {
						$choice['field'][ $field_key ] = array_column( $value, 'value' );
					} else {
						$choice['field'][ $field_key ] = array();
					}
				}
				else if ( '_gallery' == $field_meta_key ) {
					$meta = carbon_get_post_meta( $wpcb_field_id, 'gallery' );
					$choice['field'][ $field_key ] = $meta;
				}
				else if ( in_array( $field_meta_key, $i18n_meta_keys ) ) {
					$choice['field'][ $field_key ] = wpcb__( $wpcb_field_meta[ $field_meta_key ][0], $context . $field_meta_key );
				}
				else {
					$choice['field'][ $field_key ] = $wpcb_field_meta[ $field_meta_key ][0];
				}
			}
		}
		
		$visual_meta_keys = wpcb_get_choice_visual_meta_keys();
		foreach ( $visual_meta_keys as $field_key => $field_meta_key ) {
			if ( 'reference' === $field_key && $field_values = get_post_meta( $wpcb_field_id, $field_meta_key, true ) ) {
				$references = array_column( $field_values, 'value' );
				$reference_ids = array();

				foreach ( $references as $ref_id ) {
					if ( 'model' === wpcb_get_option( 'wpcb_configuration_visual_type' ) || 'model' === get_post_meta( $wpcb_field_id, '_visual_type', true ) ) {
						$ref_id = get_post_meta( $ref_id, '_material_name', true );
					}
					$reference_ids[] = $ref_id;
				}

				$choice['visual'][ $field_key ] = implode( ', ', $reference_ids );
			}
			else if ( isset( $wpcb_field_meta[ $field_meta_key ] ) && '' !== $wpcb_field_meta[ $field_meta_key ] ) {
				$choice['visual'][ $field_key ] = $wpcb_field_meta[ $field_meta_key ][0];
			}
		}

		/**
		 * Load default options
		 */
		$options = unserialize( $wpcb_field_meta['_options'][0] );

		foreach ( $options as $index => $option ) {
			$option_id   = $wpcb_field_id . '-' . $index; // wpcb_sanitize_title( wpcb_get_value( $option['label'] ) );
			$option_data = wpcb_get_choice_option_data( $option_type, $option, $context . '_' . ($index + 1) );

			if ( function_exists( 'wpcb_get_template_details' ) && 'template' == $option_type ) {
				// Fill out template details.
				foreach ( $option_data as $option_key => $option_val ) {
					if ( 'template' == $option_key ) {
						$option_data[ $option_key ] = wpcb_get_template_details( $option_val );
					}
				}
			}

			if ( $option_data['price'] ) {
				$option_data = wpcb_get_field_price_details( $option_data, $choice['field']['tax_percent'], 'price' );
			}

			if ( $option_data['sale_price'] ) {
				$option_data = wpcb_get_field_price_details( $option_data, $choice['field']['tax_percent'], 'sale_price' );
			}

			if ( isset( $wpcb_price_rates['discounts'] ) && $option_data['price'] ) {
				$discount = false;
				if ( array_key_exists( $option_id, $wpcb_price_rates['discounts'] ) ) {
					$discount = $wpcb_price_rates['discounts'][ $option_id ];
				} else if ( array_key_exists( $wpcb_field_id, $wpcb_price_rates['discounts'] ) ) {
					$discount = $wpcb_price_rates['discounts'][ $wpcb_field_id ];
				}

				if ( $discount ) {
					if ( 'percentage' === $discount['type'] ) {
						$discount_price = ( ( 100 - floatval( $discount['value'] ) ) / 100 ) * floatval( $option_data['price'] );
					} else {
						$discount_value = wpcb_get_field_price_details( 
							array( 'price' => floatval( $discount['value'] ) ), 
							$choice['field']['tax_percent'], 
							'price'
						);
						$discount_price = floatval( $option_data['price'] - $discount_value['price'] );
					}
					
					if ( isset( $discount['rules'] ) ) {
						$option_data['discount_price'] = $discount_price;
						$option_data['discount_rules'] = json_encode( $discount['rules'] );
					} else if ( $discount_price > 0 ) {
						$option_data['sale_price'] = $discount_price;
					}
				}
			}

			$option_data = apply_filters( 'wpcb_formatted_option_data', $option_data, $option_type, $option, $context . '_' . ($index + 1) );

			$choice['options'][ $option_id ] = $option_data;
		}

		if ( ! $wpcb_price_rates['price_visible'] ) {
			$choice['field']['price_hidden'] = 'yes';
		}

		// Allow passing values via URL
		$name = wpcb_sanitize_title( $choice['field']['label'] );
		if ( isset( $choice['name'] ) ) {
			$name = wpcb_sanitize_title( $choice['name'] );
		}

		if ( isset( $_GET[ $name ] ) ) {
			$option_values = sanitize_text_field( wp_unslash( $_GET[ $name ] ) );
			$choice['field']['default'] = explode(',', $option_values);
		}

		if ( $wpcb_field ) {
			/**
			 * Conditional rules
			 */
			$choice = self::get_configurator_conditional_rules( $choice, $wpcb_field );

			$choice = self::get_configurator_conditional_option_rules( $choice, $wpcb_field );
		}

		$choice = apply_filters( 'wpcb_get_formatted_choice', $choice, $wpcb_field );

		return $choice;
	}

	/**
	 * Format configurator input field data
	 *
	 * @since    1.0.0
	 */
	public static function get_configurator_input( $wpcb_input ) {
		global $wpcb_price_rates;

		$field_data = $wpcb_input['attrs']['data'];

		$wpcb_input_id = $field_data['wpcb_field'];

		$wpcb_input_meta = get_post_meta( $wpcb_input_id );
		if ( ! isset( $wpcb_input_meta['_type'][0] ) ) {
			return false;
		}

		$input_type = $wpcb_input_meta['_type'][0];
		$context = wpcb_sanitize_title( get_the_title( $wpcb_input_id ) );

		$input = array(
			'id' => $wpcb_input_id,
			'post_id' => $wpcb_input_id,
			'template' => 'input',
			'field' => array(
				'type' => $input_type,
				'label' => wpcb__( $wpcb_input_meta['_label'][0], $context . '_label' ),
				'hidden' => isset( $field_data['wpcb_field_hidden'] ) ? $field_data['wpcb_field_hidden'] : false,
				'tax_percent' => 0,
			),
			'visual' => array(),
		);

		$tax_rates = array();
		if ( isset( $wpcb_input_meta['_tax_class'] ) && class_exists( 'WC_Tax' ) && 'yes' === get_option( 'woocommerce_calc_taxes' ) ) {
			$tax_class = sanitize_text_field( $wpcb_input_meta['_tax_class'][0] );
			$tax_rates = WC_Tax::get_rates_for_tax_class( $tax_class );

			if ( is_array( $tax_rates ) && count( $tax_rates ) > 0 ) {
				$tax = reset( $tax_rates );
				$input['field']['tax_percent'] = $tax->tax_rate;
			}
		}

		if ( isset( $field_data['wpcb_field_collapsible'] ) ) {
			$input['field']['collapsible'] = $field_data['wpcb_field_collapsible'];
			$input['field']['collapsed']   = $field_data['wpcb_field_collapsible_state'];
		}

		$input_i18n_keys = array( '_note', '_description','_placeholder', '_default_value', '_unit' );
		$optional_field_options = wpcb_get_input_field_meta_keys();

		foreach ( $optional_field_options as $field_key => $field_meta_key ) {
			if ( isset( $wpcb_input_meta[ $field_meta_key ][0] ) ) {
				if ( in_array( $field_meta_key, $input_i18n_keys ) ) {
					$input['field'][ $field_key ] = wpcb__( $wpcb_input_meta[ $field_meta_key ][0], $context . $field_meta_key );
				} else if ( 'days_blocked' === $field_key ) {
					$value = maybe_unserialize($wpcb_input_meta[ $field_meta_key ][0]);
					$meta = [];
					if ( is_array( $value ) ){
						foreach ( $value as $val) {
							$meta[] = $val['value'];
						}
					}
					$input['field'][ $field_key ] = implode( ', ', $meta );
				} else if ( 'gallery' === $field_key ) {
					$meta = carbon_get_post_meta( $wpcb_input_id, 'gallery' );
					$input['field'][ $field_key ] = $meta;
				} else {
					$input['field'][ $field_key ] = $wpcb_input_meta[ $field_meta_key ][0];
				}
			}
		}

		$optional_visual_options = wpcb_get_input_visual_meta_keys();
		if ( ! isset( $wpcb_input_meta[ '_preview' ][0] ) || 'yes' !== $wpcb_input_meta[ '_preview'][0] ) {
			if ( isset( $wpcb_input_meta[ '_preview_type' ][0] ) ) {
				if ( 'input_value' === $wpcb_input_meta[ '_preview_type'][0] ) {
					$input['visual']['has-preview'] = '1';
				}

				if ( 'input_value' === $wpcb_input_meta[ '_preview_type'][0] || 'reference' === $wpcb_input_meta[ '_preview_type'][0] ) {
					foreach ( $optional_visual_options as $visual_key => $visual_meta_key ) {
						if ( isset( $wpcb_input_meta[ $visual_meta_key ] ) && '' !== $wpcb_input_meta[ $visual_meta_key ] ) {
							if ( 'reference' === $visual_key ) {
								$references = maybe_unserialize( $wpcb_input_meta[ $visual_meta_key ][0] );
								$reference_ids = array();
								if ( is_array( $references ) ) {
									if ( 'model' === wpcb_get_option( 'wpcb_configuration_visual_type' ) || 'model' === get_post_meta( $wpcb_input_id, '_visual_type', true ) ) {
										foreach ( $references as $ref_id ) {
											$ref_value = get_post_meta( $ref_id['value'], '_material_name', true );
											$reference_ids[] = $ref_value;
										}
									} else {
										foreach ( $references as $ref_id ) {
											$reference_ids[] = $ref_id['value'];
										}
									}
								}
								$input['visual'][ $visual_key ] = implode( ',', $reference_ids );
							} else {
								$input['visual'][ $visual_key ] = $wpcb_input_meta[ $visual_meta_key ][0];
							}
						}
					}
				}
			}
		}

		if ( isset( $input['field']['price'] ) && $input['field']['price'] ) {
			$input['field'] = wpcb_get_field_price_details( $input['field'], $input['field']['tax_percent'], 'price' );
		}
		if ( isset( $input['field']['sale'] ) && $input['field']['sale'] ) {
			$input['field'] = wpcb_get_field_price_details( $input['field'], $input['field']['tax_percent'], 'sale' );
		}
		if ( isset( $input['field']['price_unit'] ) && $input['field']['price_unit'] ) {
			$input['field'] = wpcb_get_field_price_details( $input['field'], $input['field']['tax_percent'], 'price_unit' );
		}
		if ( isset( $input['field']['price_unit_sale'] ) && $input['field']['price_unit_sale'] ) {
			$input['field'] = wpcb_get_field_price_details( $input['field'], $input['field']['tax_percent'], 'price_unit_sale' );
		}

		if ( ! $wpcb_price_rates['price_visible'] ) {
			$input['field']['price_hidden'] = 'yes';
		}

		$input = self::get_configurator_conditional_rules( $input, $wpcb_input );

		$input = self::get_configurator_conditional_option_rules( $input, $wpcb_input );

		// Allow passing values via URL
		$name = wpcb_sanitize_title( $input['field']['label'] );
		if ( isset( $input['name'] ) ) {
			$name = wpcb_sanitize_title( $input['name'] );
		}

		if ( isset( $_GET[ $name ] ) ) {
			$input['field']['value'] = sanitize_text_field( wp_unslash( $_GET[ $name ] ) );
		}

		$input = apply_filters( 'wpcb_get_formatted_input', $input, $wpcb_input );

		return $input;
	}

	/**
	 * Format configurator field group data
	 *
	 * @since    1.0.0
	 */
	public static function get_configurator_conditional_rules( $wpcb_field, $block_field ) {
		$field_data = $block_field['attrs']['data'];

		if ( ! isset( $field_data['wpcb_field_apply_rules'] ) || ! $field_data['wpcb_field_apply_rules'] ) {
			return $wpcb_field;
		}

		$wpcb_field['rules'] = array(
			'display' => isset( $field_data['wpcb_field_rule_type'] ) && '' !== $field_data['wpcb_field_rule_type'] ? $field_data['wpcb_field_rule_type'] : 'show',
			'relation' => isset( $field_data['wpcb_field_rule_relation'] ) && '' !== $field_data['wpcb_field_rule_relation'] ? $field_data['wpcb_field_rule_relation'] : 'OR',
			'conditions' => array(),
		);
		
		foreach ( $field_data['wpcb_field_display_rules'] as $rule ) {
			$wpcb_field['rules']['conditions'][] = self::get_rule_data( $rule );
		}

		return $wpcb_field;
	}

	/**
	 * Format configurator field group data
	 *
	 * @since    1.0.0
	 */
	public static function get_configurator_conditional_option_rules( $wpcb_field, $block_field ) {
		$field_data = $block_field['attrs']['data'];

		if ( ! isset( $field_data['wpcb_field_edit_options'] ) || ! $field_data['wpcb_field_edit_options'] ) {
			return $wpcb_field;
		}

		if ( ! isset( $field_data['wpcb_field_options'] ) || ! is_array( $field_data['wpcb_field_options'] ) ) {
			return $wpcb_field;
		}

		foreach ( $field_data['wpcb_field_options'] as $conditional_option ) {
			$option_rules = array(
				'display' => isset( $conditional_option['wpcb_field_option_rule_type'] ) && '' !== $conditional_option['wpcb_field_option_rule_type'] ? $conditional_option['wpcb_field_option_rule_type'] : 'show',
				'relation' => isset( $conditional_option['wpcb_field_option_rule_relation'] ) && '' !== $conditional_option['wpcb_field_option_rule_relation'] ? $conditional_option['wpcb_field_option_rule_relation'] : 'OR',
				'conditions' => array(),
			);

			foreach ( $conditional_option['wpcb_field_option_display_rules'] as $rule ) {
				$option_rules['conditions'][] = self::get_rule_data( $rule );
			}

			$key = $conditional_option['wpcb_field_option'];
			$wpcb_field['options'][ $key ]['rules'] = $option_rules;

			if ( isset( $conditional_option['wpcb_field_option_default'] ) && $conditional_option['wpcb_field_option_default'] ) {
				$wpcb_field['field']['default'][] = $key;
			}
		}

		return $wpcb_field;
	}

	/**
	 * Format configurator input field data
	 *
	 * @since    1.0.0
	 */
	public static function get_rule_data( $rule ) {
		if ( 'input' === $rule['wpcb_rule_type'] ) {
			return array(
				'field' => $rule['wpcb_rule_input'],
				'compare' => isset( $rule['wpcb_rule_input_compare'] ) && '' !== $rule['wpcb_rule_input_compare'] ? $rule['wpcb_rule_input_compare'] : '==',
				'value' => $rule['wpcb_rule_input_value']
			);
		} else if ( $rule['wpcb_rule_choice'] ) {
			return array(
				'field' => $rule['wpcb_rule_choice'],
				'compare' => isset( $rule['wpcb_rule_choice_compare'] ) && '' !== $rule['wpcb_rule_choice_compare'] ? $rule['wpcb_rule_choice_compare'] : '==',
				'value' => $rule['wpcb_rule_choice_value']
			);
		}

		return false;
	}
}
