<?php
/**
 * Search template modifications
 *
 * @package WebEquipe\PDFSearch
 * @since 1.0.0
 */

namespace WebEquipe\PDFSearch;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Search Template class for modifying search result display
 */
class Search_Template {

	/**
	 * Initialize hooks
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_filter( 'get_search_query', array( $this, 'preserve_search_query' ) );
		add_action( 'loop_start', array( $this, 'wrap_pdf_results' ) );
	}

	/**
	 * Preserve search query
	 *
	 * @since 1.0.0
	 * @param string $query Search query (unused but required by filter signature).
	 * @return string Search query
	 */
	public function preserve_search_query( $query ) {
		// Parameter $query is required by filter signature but unused.
		$query = null;
		unset( $query );
		return sanitize_text_field( get_query_var( 's' ) );
	}

	/**
	 * Wrap PDF results with special class
	 *
	 * @since 1.0.0
	 * @param \WP_Query $query WordPress query object.
	 * @return void
	 */
	public function wrap_pdf_results( $query ) {
		if ( ! $query->is_main_query() || ! $query->is_search() ) {
			return;
		}

		add_filter( 'post_class', array( $this, 'add_pdf_result_class' ), 10, 3 );
	}

	/**
	 * Add PDF result class to post
	 *
	 * @since 1.0.0
	 * @param array $classes Post classes.
	 * @param array $additional_class Additional classes (unused but required by filter signature).
	 * @param int   $post_id Post ID (unused but required by filter signature).
	 * @return array Modified classes
	 */
	public function add_pdf_result_class( $classes, $additional_class, $post_id ) {
		// Parameters required by filter signature but unused.
		$additional_class = null;
		$post_id          = null;
		unset( $additional_class, $post_id );
		global $post;

		if ( isset( $post->is_pdf_result ) && $post->is_pdf_result ) {
			$classes[] = 'webequipe-pdf-result';
			$classes[] = 'type-pdf';
		}

		return $classes;
	}
}
