<?php
/**
 * Server-side rendering of the `nisje/iframe` block.
 *
 * @package Nisje
 */

namespace Nisje\BlockLibrary\IFrame;

/**
 * Renders the `nisje/iframe` block on server
 *
 * @param array $attributes The block attributes.
 *
 * @return string Returns the post content with links added.
 */
function render_block( $attributes ) {
	$args = wp_parse_args( $attributes, [
		'url'    => '',
		'height' => 300,
	] );

	if ( empty( $args['height'] ) || empty( $args['url'] ) ) {
		return '';
	}

	$classes = 'wp-block-embed nisje-block-iframe';

	if ( isset( $attributes['align'] ) && ! empty( $attributes['align'] ) ) {
		$classes .= " align{$attributes['align']}";
	}

	return sprintf( '<div class="%s"><div class="wp-block-embed__wrapper"><iframe src="%s" height="%s" frameborder="0" allowfullscreen="allowfullscreen"></iframe></div></div>',
		esc_attr( $classes ),
		esc_attr( $args['url'] ),
		esc_attr( $args['height'] )
	);
}

/**
 * Registers the `nisje/iframe` block on server.
 */
function register_block() {
	\register_block_type_from_metadata( __DIR__, [
		'render_callback' => __NAMESPACE__ . '\\render_block',
	] );
}
\add_action( 'init', __NAMESPACE__ . '\\register_block' );
