<?php

namespace GP_Entry_Blocks\Blocks;

use GFAPI;
use GP_Entry_Blocks\GF_Queryer;
use function GP_Entry_Blocks\replace_merge_tags;

/**
 * Block to display a single entry. Will be displayed instead of multi-entry blocks such as Entries Loop or Entries Table
 * if a single entry is being requested.
 *
 * Uses <InnerBlocks />. Parses content for GF merge tags.
 *
 * @since 1.0
 */
class View_Entry extends Block {
	public function __construct( $path ) {
		parent::__construct( $path );

		add_filter( 'gpeb_view_entry_content', array( $this, 'replace_view_item_template_merge_tags' ), 5, 3 );

		if ( isset( $GLOBALS['wp_embed'] ) ) {
			add_filter( 'gpeb_view_entry_content', array( $GLOBALS['wp_embed'], 'autoembed' ), 8 );
		}
	}

	public function replace_view_item_template_merge_tags( $content, $entry_form, $entry ) {
		return replace_merge_tags( $content, $entry_form, $entry );
	}

	/**
	 * @todo i18n.
	 */
	public function render( $attributes, $content, $block ) {
		$queryer = GF_Queryer::attach( $block->context );

		if ( ! $queryer->is_view_entry() ) {
			return '';
		}

		$form_id = $block->context['gp-entry-blocks/formId'];
		$form    = GFAPI::get_form( $form_id );

		if ( ! $form ) {
			return '';
		}

		/** This filter is documented in /includes/blocks/class-entries-loop.php */
		$entry = apply_filters( 'gpeb_entry', $queryer->entry, $form, $block );
		/** This filter is documented in /includes/blocks/class-entries-loop.php */
		$entry_form = apply_filters( 'gpeb_entry_form', $form, $entry, $block );

		if ( ! $entry || (int) rgar( $entry, 'form_id' ) !== (int) $form_id ) {
			return __( 'Entry not found.', 'gp-entry-blocks' );
		} else {
			/**
			 * Filter an entry being displayed in a View Entry block.
			 *
			 * @param string $content    A string containing the inner blocks for an individual entry in a View Entry block.
			 * @param array  $entry_form The form for the current entry.
			 * @param array  $entry      The current entry being rendered in the View Entry block.
			 *
			 * @since 1.0-alpha-2.17
			 */
			$content = apply_filters( 'gpeb_view_entry_content', $content, $entry_form, $entry );
		}

		return $content;
	}
}
