<?php //phpcs:disable

/**
 * The file contains definition of WLC_Algolia class
 *
 * @package WLC\Algolia
 *
 */

namespace wlc_algolia;

use wlc_algolia\Helpers as helper;

defined( 'ABSPATH' ) || die( 'Direct file access is forbidden' );

/**
 * Algolia Index helper class
 */
class Algolia_Index_Helper extends Client_Helper {
	/**
	 * Get post images.
	 *
	 * @param int $post_id The ID of post.
	 *
	 * @return array
	 */
	public static function wlc_get_post_images( int $post_id ): array {
		$image_data        = array();
		$post_type         = get_post_type( $post_id );
		$post_thumbnail_id = get_post_thumbnail_id( $post_id );
		if ( 'attachment' === $post_type ) {
			$post_thumbnail_id = $post_id;
		}

		$sizes = array(
			'thumbnail',
			'medium',
			'large',
		);
		if ( $post_thumbnail_id ) {

			foreach ( $sizes as $size ) {
				$image = wp_get_attachment_image_src( $post_thumbnail_id, $size );
				if ( ! $image ) {
					continue;
				}
				$image_data[ $size ] = array(
					'url'    => esc_url( $image[0] ),
					'width'  => esc_attr( $image[1] ),
					'height' => esc_attr( $image[2] ),
				);
			}

		}

		return $image_data;
	}

	/**
	 * Remove Unnecessary code blocks from content.
	 *
	 * @param string $content Content to be removed blocks from.
	 *
	 * @return string
	 */
	public static function wlc_remove_unnecessary_content_blocks_for_indexing( string $content ): string {
		$patterns = array(
			'/<[^>]*(wp-(?:block-[^"]*")|gutenberg|has-[^\s]*"[^"]*")[^>]*>/'
		);

		$patterns = apply_filters( 'wlc_algolia_remove_unnecessary_content_block', $patterns );

		foreach ( $patterns as $pattern ) {
			$content = preg_replace( $pattern, '', $content );
		}

		$content = str_replace( '&nbsp;', ' ', $content );

		return html_entity_decode( $content );
	}

	/**
	 * Prepare content for indexing.
	 *
	 * @param string $content Content to be indexed.
	 *
	 * @return string
	 */
	public static function wlc_prepare_content( string $content ): string {
		$content = self::wlc_remove_unnecessary_content_blocks_for_indexing( $content );

		return wp_strip_all_tags( $content );
	}

	/**
	 * Get post.
	 *
	 * @param string $post_type Post type to retrieve.
	 *
	 * @return array
	 */
	protected static function wlc_get_post( string $post_type ): array {
		$args = array(
			'post_type'   => $post_type,
			'numberposts' => 1,
		);

		return get_posts( $args );
	}

	/**
	 * Prepare default fields for Schema.
	 *
	 * @return array
	 */
	public static function wlc_prepare_cpt_fields_array(): array {
		$current_section = $_GET['section'] ?? '';
		if ( isset( $_GET['tab'] ) && ! isset( $_GET['section'] ) ) {
			$current_section = 'post';
		}

		$post       = self::wlc_get_post( sanitize_text_field( $current_section ) );
		$cpt_fields = array();
		if ( ! empty( $post ) ) {
			foreach ( $post as $fields ) {
				unset( $fields->post_password );
				$cpt_fields = array_keys( (array) $fields );
			}
		}

		/**
		 * WooCommerce: key fields like price / sku are stored in post meta, not in wp_posts columns.
		 * WP_Post::__get can read meta keys transparently, but we still need to expose those keys in the CPT UI.
		 */
		if ( 'product' === $current_section ) {
			$wc_meta_fields = array(
				'_sku',
				'_price',
				'_regular_price',
				'_sale_price',
				'_stock',
				'_stock_status',
				'_manage_stock',
				'_weight',
				'_length',
				'_width',
				'_height',
			);

			$cpt_fields = array_values( array_unique( array_merge( $cpt_fields, $wc_meta_fields ) ) );
		}

		$cpt_fields[] = 'post_permalink';
		$cpt_fields[] = 'taxonomies';
		$cpt_fields[] = 'images';

		return apply_filters( 'wlc_cpt_default_schema', $cpt_fields );
	}

	/**
	 * Get current section name.
	 *
	 * @return string
	 */
	public static function wlc_retrieve_current_section_name(): string {
		$current_section = $_GET['section'] ?? '';
		if ( isset( $_GET['tab'] ) && 'cpt' === $_GET['tab'] && ! isset( $_GET['section'] ) ) {
			$current_section = 'post';
		}

		return sanitize_text_field( $current_section );
	}

	public static function wlc_prepare_index_types() {
		return apply_filters( 'wlc_index_types', array(
			'string'  => esc_html( 'String' ),
			'float'   => esc_html( 'Float' ),
			'integer' => esc_html( 'Integer' ),
			'array'   => esc_html( 'Array' ),
		) );
	}

	/**
	 * Prepare Selected fields for indexing from CPT settings.
	 *
	 * @param array $cpt_settings Array of CPT Settings.
	 * @param string $flag What to retrieve from CPT Fields.
	 *
	 * @return array|string
	 */
	public static function wlc_prepare_selected_fields( array $cpt_settings, string $flag = '' ): array|string {
		$selected_fields = array();
		
		foreach ( $cpt_settings as $field => $settings ) {
			if ( isset( $settings['index'] ) ) {
				if ( '1' === $settings['index'] ) {
					if ( 'post_type' === $flag ) { //TODO improve custom fields selection by post_type
						$selected_fields = sanitize_key( (string) ( $cpt_settings['selected_post_type'] ?? '' ) );
					} else {
						$selected_fields[ $field ] = $settings;
					}
				}
			}
		}

		return $selected_fields;
	}

	public static function wlc_get_default_index_fields() {
		// Delegate defaults to a dedicated class so CPT "enable indexing" defaults
		// can be maintained in one place.
		return Cpt_Defaults::get_default_index_fields();
	}

	/**
	 * Prepare args to retrieve posts.
	 *
	 * @param string $post_type Post Type
	 *
	 * @return array
	 */
	public static function wlc_prepare_args( string $post_type ): array {
		if ( 'attachment' === $post_type ) {
			return apply_filters( 'wlc_algolia_prepare_args', array(
				'post_type'      => 'attachment',
				'posts_per_page' => - 1,
			) );
		}
		return apply_filters( 'wlc_algolia_prepare_args', array(
			'post_type'      => $post_type,
			'post_status'    => 'publish',
			'posts_per_page' => - 1,
		) );
	}
}
