<?php // phpcs:ignore
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Rendered HTML for the Algolia Autocomplete block.
 *
 * @package WLC_Algolia
 *
 * @param array    $attributes Block attributes.
 * @param string   $content    Block content.
 * @param WP_Block $block      Block object.
 */

( static function () use ( $attributes, $content, $block ) {

$wlc_algolia_block_wrapper_attributes = get_block_wrapper_attributes(); // phpcs:ignore

	$wlc_algolia_query_suggestions_index = isset( $attributes['querySuggestionsIndex'] ) ? sanitize_text_field( (string) $attributes['querySuggestionsIndex'] ) : '';
	$wlc_algolia_selected_post_types     = isset( $attributes['selectedPostTypes'] ) && is_array( $attributes['selectedPostTypes'] ) ? $attributes['selectedPostTypes'] : array();
	$wlc_algolia_max_suggestions         = isset( $attributes['maxSuggestions'] ) ? absint( $attributes['maxSuggestions'] ) : 5;
	$wlc_algolia_max_results_per_type    = isset( $attributes['maxResultsPerType'] ) ? absint( $attributes['maxResultsPerType'] ) : 3;
	$wlc_algolia_placeholder             = isset( $attributes['placeholder'] ) ? sanitize_text_field( (string) $attributes['placeholder'] ) : 'Search...';
	$wlc_algolia_show_suggestions        = ! empty( $attributes['showSuggestions'] );
	$wlc_algolia_accent_color            = isset( $attributes['accentColor'] ) ? sanitize_hex_color( (string) $attributes['accentColor'] ) : '#DB002F';
	$wlc_algolia_result_layout           = isset( $attributes['resultLayout'] ) ? sanitize_key( (string) $attributes['resultLayout'] ) : 'vertical';
	if ( ! in_array( $wlc_algolia_result_layout, array( 'vertical', 'grid' ), true ) ) {
		$wlc_algolia_result_layout = 'vertical';
	}
	$wlc_algolia_result_layout_columns       = isset( $attributes['resultLayoutColumns'] ) ? absint( $attributes['resultLayoutColumns'] ) : 2;
	$wlc_algolia_search_page_url             = isset( $attributes['searchPageUrl'] ) ? esc_url_raw( (string) $attributes['searchPageUrl'] ) : '';
	$wlc_algolia_show_all_button_label       = isset( $attributes['showAllButtonLabel'] ) ? sanitize_text_field( (string) $attributes['showAllButtonLabel'] ) : __( 'Show all', 'wlc-search-integration-with-algolia' );
	$wlc_algolia_templates_by_post_type_attr = isset( $attributes['templatesByPostType'] ) && is_array( $attributes['templatesByPostType'] )
		? $attributes['templatesByPostType']
		: array();

	// Get base index name.
	$wlc_algolia_general_settings = get_option( 'wlc_algolia_settings_general', array() );
	$wlc_algolia_base_index       = '';
	if ( is_array( $wlc_algolia_general_settings ) && isset( $wlc_algolia_general_settings['general']['index_name'] ) ) {
		$wlc_algolia_base_index = sanitize_text_field( (string) $wlc_algolia_general_settings['general']['index_name'] );
	}

	// Build index names for post types.
	$wlc_algolia_post_type_indexes = array();
	foreach ( $wlc_algolia_selected_post_types as $wlc_algolia_pt ) {
		$wlc_algolia_pt               = sanitize_key( (string) $wlc_algolia_pt );
		$wlc_algolia_post_type_object = '' !== $wlc_algolia_pt ? get_post_type_object( $wlc_algolia_pt ) : null;
		$wlc_algolia_is_searchable_pt = $wlc_algolia_post_type_object
			&& ! empty( $wlc_algolia_post_type_object->public )
			&& ! empty( $wlc_algolia_post_type_object->show_ui )
			&& empty( $wlc_algolia_post_type_object->exclude_from_search )
			&& ! empty( $wlc_algolia_post_type_object->show_in_nav_menus );
		if ( '' !== $wlc_algolia_pt && $wlc_algolia_is_searchable_pt ) {
			$wlc_algolia_post_type_indexes[] = array(
				'post_type'  => $wlc_algolia_pt,
				'index_name' => $wlc_algolia_base_index . '_' . $wlc_algolia_pt,
			);
		}
	}

	// Extract template blocks from inner blocks.
	$wlc_algolia_template_blocks        = array();
	$wlc_algolia_templates_by_post_type = array();

	$wlc_algolia_extract_template_blocks = static function ( $blocks ) use ( &$wlc_algolia_extract_template_blocks ) {
		$out = array();
		if ( ! is_array( $blocks ) ) {
			return $out;
		}
		foreach ( $blocks as $b ) {
			if ( ! is_array( $b ) ) {
				continue;
			}
			$name  = isset( $b['blockName'] ) ? (string) $b['blockName'] : '';
			$attrs = isset( $b['attrs'] ) && is_array( $b['attrs'] ) ? $b['attrs'] : array();

			$common = array(
				'hideIfEmpty' => isset( $attrs['hideIfEmpty'] ) ? (bool) $attrs['hideIfEmpty'] : true,
			);

			if ( 'wlc-algolia/result-title' === $name ) {
				$out[] = array_merge(
					$common,
					array(
						'type'          => 'title',
						'fieldPath'     => sanitize_text_field( (string) ( $attrs['fieldPath'] ?? 'post_title' ) ),
						'linkType'      => sanitize_key( (string) ( $attrs['linkType'] ?? 'permalink' ) ),
						'linkFieldPath' => sanitize_text_field( (string) ( $attrs['linkFieldPath'] ?? '' ) ),
					)
				);
			} elseif ( 'wlc-algolia/result-image' === $name ) {
				$out[] = array_merge(
					$common,
					array(
						'type'          => 'image',
						'fieldPath'     => sanitize_text_field( (string) ( $attrs['fieldPath'] ?? 'images.thumbnail.url' ) ),
						'linkType'      => sanitize_key( (string) ( $attrs['linkType'] ?? 'permalink' ) ),
						'linkFieldPath' => sanitize_text_field( (string) ( $attrs['linkFieldPath'] ?? '' ) ),
					)
				);
			} elseif ( 'wlc-algolia/result-excerpt' === $name ) {
				$out[] = array_merge(
					$common,
					array(
						'type'      => 'excerpt',
						'fieldPath' => sanitize_text_field( (string) ( $attrs['fieldPath'] ?? 'post_excerpt' ) ),
						'maxLength' => absint( $attrs['maxLength'] ?? 220 ),
					)
				);
			} elseif ( 'wlc-algolia/result-meta' === $name ) {
				$out[] = array_merge(
					$common,
					array(
						'type'       => 'meta',
						'metaDate'   => ! empty( $attrs['metaDate'] ),
						'metaAuthor' => ! empty( $attrs['metaAuthor'] ),
					)
				);
			} elseif ( 'wlc-algolia/result-field' === $name ) {
				$out[] = array_merge(
					$common,
					array(
						'type'          => 'field',
						'label'         => sanitize_text_field( (string) ( $attrs['label'] ?? '' ) ),
						'fieldPath'     => sanitize_text_field( (string) ( $attrs['fieldPath'] ?? '' ) ),
						'linkType'      => sanitize_key( (string) ( $attrs['linkType'] ?? 'none' ) ),
						'linkFieldPath' => sanitize_text_field( (string) ( $attrs['linkFieldPath'] ?? '' ) ),
					)
				);
			} elseif ( 'wlc-algolia/result-button' === $name ) {
				$out[] = array_merge(
					array( 'hideIfEmpty' => isset( $attrs['hideIfEmpty'] ) ? (bool) $attrs['hideIfEmpty'] : false ),
					array(
						'type'          => 'button',
						'label'         => sanitize_text_field( (string) ( $attrs['label'] ?? 'View' ) ),
						'linkType'      => sanitize_key( (string) ( $attrs['linkType'] ?? 'permalink' ) ),
						'linkFieldPath' => sanitize_text_field( (string) ( $attrs['linkFieldPath'] ?? '' ) ),
					)
				);
			}

			if ( isset( $b['innerBlocks'] ) && is_array( $b['innerBlocks'] ) && ! empty( $b['innerBlocks'] ) ) {
				$out = array_merge( $out, $wlc_algolia_extract_template_blocks( $b['innerBlocks'] ) );
			}
		}
		return $out;
	};

	$wlc_algolia_template_defs_to_blocks = static function ( $template_defs ) {
		$out = array();
		if ( ! is_array( $template_defs ) ) {
			return $out;
		}
		foreach ( $template_defs as $template_def ) {
			if ( ! is_array( $template_def ) ) {
				continue;
			}
			$name  = isset( $template_def['name'] ) ? (string) $template_def['name'] : '';
			$attrs = isset( $template_def['attrs'] ) && is_array( $template_def['attrs'] ) ? $template_def['attrs'] : array();
			$out[] = array(
				'blockName'   => $name,
				'attrs'       => $attrs,
				'innerBlocks' => array(),
			);
		}
		return $out;
	};

	// Try to get innerBlocks from $block first (most reliable for dynamic blocks).
	$wlc_algolia_inner_blocks = null;
	if ( isset( $block ) ) {
		if ( is_object( $block ) && method_exists( $block, 'get_parsed_block' ) ) {
			$wlc_algolia_parsed       = $block->get_parsed_block();
			$wlc_algolia_inner_blocks = isset( $wlc_algolia_parsed['innerBlocks'] ) ? $wlc_algolia_parsed['innerBlocks'] : null;
		} elseif ( is_object( $block ) && isset( $block->parsed_block['innerBlocks'] ) ) {
			$wlc_algolia_inner_blocks = $block->parsed_block['innerBlocks'];
		} elseif ( is_array( $block ) && isset( $block['innerBlocks'] ) ) {
			$wlc_algolia_inner_blocks = $block['innerBlocks'];
		}
	}

	if ( $wlc_algolia_inner_blocks && is_array( $wlc_algolia_inner_blocks ) && ! empty( $wlc_algolia_inner_blocks ) ) {
		$wlc_algolia_template_blocks = $wlc_algolia_extract_template_blocks( $wlc_algolia_inner_blocks );
	} elseif ( isset( $content ) && is_string( $content ) && '' !== trim( $content ) ) {
		// Fallback: parse content HTML if innerBlocks not available.
		$wlc_algolia_parsed          = parse_blocks( $content );
		$wlc_algolia_template_blocks = $wlc_algolia_extract_template_blocks( $wlc_algolia_parsed );
	}

	foreach ( $wlc_algolia_templates_by_post_type_attr as $wlc_algolia_pt => $wlc_algolia_template_defs ) {
		$wlc_algolia_pt = sanitize_key( (string) $wlc_algolia_pt );
		if ( '' === $wlc_algolia_pt ) {
			continue;
		}
		$wlc_algolia_templates_by_post_type[ $wlc_algolia_pt ] = $wlc_algolia_extract_template_blocks(
			$wlc_algolia_template_defs_to_blocks( $wlc_algolia_template_defs )
		);
	}

	$wlc_algolia_config = array(
		'querySuggestionsIndex' => $wlc_algolia_query_suggestions_index,
		'postTypeIndexes'       => $wlc_algolia_post_type_indexes,
		'maxSuggestions'        => $wlc_algolia_max_suggestions,
		'maxResultsPerType'     => $wlc_algolia_max_results_per_type,
		'placeholder'           => $wlc_algolia_placeholder,
		'showSuggestions'       => $wlc_algolia_show_suggestions,
		'accentColor'           => $wlc_algolia_accent_color ? $wlc_algolia_accent_color : '#DB002F',
		'templateBlocks'        => $wlc_algolia_template_blocks,
		'templatesByPostType'   => $wlc_algolia_templates_by_post_type,
		'resultLayout'          => $wlc_algolia_result_layout,
		'resultLayoutColumns'   => $wlc_algolia_result_layout_columns,
		'searchPageUrl'         => $wlc_algolia_search_page_url,
		'showAllButtonLabel'    => $wlc_algolia_show_all_button_label,
	);

	// Get Algolia API keys for frontend.
	$wlc_algolia_general_settings = get_option( 'wlc_algolia_settings_general', array() );
	$wlc_algolia_app_id           = '';
	$wlc_algolia_search_api_key   = '';

	if ( is_array( $wlc_algolia_general_settings ) && isset( $wlc_algolia_general_settings['general'] ) ) {
		$wlc_algolia_app_id         = isset( $wlc_algolia_general_settings['general']['application_id'] ) ? sanitize_text_field( (string) $wlc_algolia_general_settings['general']['application_id'] ) : '';
		$wlc_algolia_search_api_key = isset( $wlc_algolia_general_settings['general']['search_api_key'] ) ? sanitize_text_field( (string) $wlc_algolia_general_settings['general']['search_api_key'] ) : '';
	}

	// Get WooCommerce currency if available.
	$wlc_algolia_currency = 'USD'; // Default fallback.
	if ( function_exists( 'get_woocommerce_currency' ) ) {
		$wlc_algolia_currency = get_woocommerce_currency();
	}

	$wlc_algolia_config['appId']    = $wlc_algolia_app_id;
	$wlc_algolia_config['apiKey']   = $wlc_algolia_search_api_key;
	$wlc_algolia_config['currency'] = $wlc_algolia_currency;
	?>
<div <?php echo $wlc_algolia_block_wrapper_attributes; // phpcs:ignore ?>
	data-config="<?php echo esc_attr( wp_json_encode( $wlc_algolia_config ) ); ?>"
	style="--wlc-accent: <?php echo esc_attr( $wlc_algolia_accent_color ? $wlc_algolia_accent_color : '#DB002F' ); ?>;"
>
	<div class="wp-block-wlc-algolia-autocomplete__container"></div>
</div>
	<?php
} )();
