<?php
/**
 * Builder Plugin Compatibility Code
 *
 * @package    Themify_Builder Pro
 */
/**
 * @link https://wordpress.org/plugins/relevanssi/
 */
class Themify_Builder_Plugin_Compat_relevanssi {

	static function init() {
		add_filter( 'tbp_archive_posts_query', array( __CLASS__, 'tbp_archive_posts_query' ), 10, 2 );
		add_filter( 'tbp_archive_products_query', array( __CLASS__, 'tbp_archive_posts_query' ), 10, 2 );
	}

    static function tbp_archive_posts_query( $query_args, $fields_args ) {
        if ( ! empty( $query_args['s'] ) && is_search() ) {
            $args = array(
                's'              => $query_args['s'],
                'fields'         => 'ids',
                'posts_per_page' => -1,
                'relevanssi'     => true,
            );

            $relevanssi_query = new WP_Query( $args );

            $results = ! empty( $relevanssi_query->posts )
                ? $relevanssi_query->posts
                : array( 0 );

            $query_args = [
                'post__in' => $results,
                'post_type' => $query_args['product'],
                'post_status' => 'any',
                'orderby' => 'post__in',
                'order' => 'DESC',
                's' => false
            ];
        }

        return $query_args;
    }
}