<?php

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

/**
 * Block that is shown when editing individual entries. Note, this block does not automatically include the actual form.
 *
 * Uses <InnerBlocks />. Uses dynamic rendering to prevent outputting content if not editing an entry.
 *
 * @since 1.0
 */
class Edit_Entry extends Block {
	public function render( $attributes, $content, $block ) {
		$queryer = GF_Queryer::attach( $block->context );

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

		if ( ! $queryer->entry ) {
			return __( 'Oops! We can\'t locate that entry.', 'gp-entry-blocks' );
		}

		if ( ! gp_entry_blocks()->permissions->can_current_user_edit_entry( $queryer->entry ) ) {
			return __( 'Oops! You don\'t have permission to edit this entry.', 'gp-entry-blocks' );
		}

		$form_id = $block->context['gp-entry-blocks/formId'];

		$content = replace_merge_tags( $content, GFAPI::get_form( $form_id ), $queryer->entry );
		$content = $this->unescape_merge_tags( $content ); // Unescape inner blocks (for Edit Form block).

		return $content;
	}
}
