<?php

// @link https://searchwp.com/documentation/knowledge-base/append-document-content-to-parent-post-content/
// Retrieve child PDF content and add as 'extra' data to a SearchWP Entry.
add_filter( 'searchwp\entry\data', function( $data, \SearchWP\Entry $entry ) {
	// Convert the SearchWP Entry into it's native object type.
	$entry = $entry->native();

	// We only want to consider WP_Post objects.
	if ( ! $entry instanceof \WP_Post ) {
		return $data;
	}

	// Retrieve PDFs that have been uploaded to this Entry.
	$pdfs = get_posts( [
		'post_type'      => 'attachment',
		'post_mime_type' => 'application/pdf',
		'post_status'    => 'inherit',
		'nopaging'       => true,
		'post_parent'    => $entry->ID,
	] );

	if ( empty( $pdfs ) ) {
		return $data;
	}

	// Retrieve PDF content for PDFs and store as extra data.
	$data['meta'][ 'searchwp_child_pdf_content' ] = array_map( function( $pdf ) {
		return \SearchWP\Document::get_content( $pdf );
	}, $pdfs );

	return $data;
}, 20, 2 );

// Add "Attached PDF Content" as available option to SearchWP Source Attributes.
add_filter( 'searchwp\source\attribute\options', function( $keys, $args ) {
	if ( $args['attribute'] !== 'meta' ) {
		return $keys;
	}

	// This key is the same as the one used in the searchwp\entry\data hook above, they must be the same.
	$pdf_content_key = 'searchwp_child_pdf_content';

	// Add "Attached PDF Content" Option if it does not exist already.
	if ( ! in_array(
		$pdf_content_key,
		array_map( function( $option ) { return $option->get_value(); }, $keys )
	) ) {
		$keys[] = new \SearchWP\Option( $pdf_content_key, 'Attached PDF Content' );
	}

	return $keys;
}, 20, 2 );