<?php
namespace TotalTheme\Integration;

defined( 'ABSPATH' ) || exit;

/**
 * Relevanssi Integration.
 *
 * @package TotalTheme
 * @subpackage Integration
 * @version 5.4.5
 */
final class Relevanssi {

	/**
	 * Instance.
	 */
	private static $instance;

	/**
	 * Create or retrieve the instance of Revslider.
	 */
	public static function instance() {
		if ( is_null( static::$instance ) ) {
			static::$instance = new self();
		}
		return static::$instance;
	}

	/**
	 * Hook into actions and filters.
	 */
	public function __construct() {
		if ( ! has_action( 'init', 'relevanssi_init' ) ) {
			return;
		}

		add_filter( 'wpex_excerpt_output', __CLASS__ . '::parse_excerpts' );
		add_filter( 'the_title', __CLASS__ . '::parse_title', 10, 2 );
		add_filter( 'wpex_card_title', __CLASS__ . '::parse_card_title', 10, 3 );
	}

	/**
	 * Check if doing a search query.
	 */
	private static function is_search_query() {
		return ( is_search() && wpex_is_request( 'frontend' ) && is_main_query() ) ? true : false;
	}

	/**
	 * Parses post excerpts.
	 */
	public static function parse_excerpts( $excerpt ) {
		if ( self::is_search_query() && function_exists( 'relevanssi_highlight_terms' ) ) {
			$excerpt = relevanssi_highlight_terms( $excerpt, get_search_query(), true );
		}
		return $excerpt;
	}

	/**
	 * Parses the wpex_title.
	 */
	public static function parse_title( $title, $id ) {
		if ( self::is_search_query() ) {
			$post = relevanssi_get_post( $id );
			if ( $post && ! empty( $post->post_highlighted_title ) ) {
				return $post->post_highlighted_title;
			}
		}
		return $title;
	}

	/**
	 * Parses card titles.
	 */
	public static function parse_card_title( $title, $card_obj, $args ) {
		if ( self::is_search_query() && empty( $card_obj->args['title'] ) && empty( $args['content'] ) ) {
			$post = relevanssi_get_post( $card_obj->post_id ?? 0 );
			if ( $post && ! empty( $post->post_highlighted_title ) ) {
				return $post->post_highlighted_title;
			}
		}
		return $title;
	}

}