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

namespace Nisje\BlockLibrary\CardEvent;

/**
 * Renders the `nisje/card-event` block on server
 *
 * @param array $attributes The block attributes.
 *
 * @return string Returns the post content.
 */
function render_block( array $attributes ): string {
	global $nisje_excluded_cards;

	if ( ! isset( $nisje_excluded_cards ) ) {
		$nisje_excluded_cards = [];
	}

	$content = [];

	if ( isset( $attributes['postId'] ) && 0 !== $attributes['postId'] ) {
		$content                = \nisje_get_api_data( '/wp/v2/dekode-event/' . $attributes['postId'] );
		$nisje_excluded_cards[] = $attributes['postId'];
	} else {
		$args = [
			'exclude'  => $nisje_excluded_cards,
			'per_page' => 1,
		];

		$posts = \nisje_get_api_data( '/wp/v2/dekode-event', $args );

		if ( ! empty( $posts ) ) {
			$content                = $posts[0];
			$nisje_excluded_cards[] = $posts[0]['id'];
		}
	}

	if ( ! empty( $posts ) ) {
		$content          = $posts[0];
		$content['type']  = 'dekode-event';
		$excluded_cards[] = $posts[0]['id'];
		unset( $content['_links'] );
	}

	return \wp_json_encode( $content );
}

/**
 * Registers the `nisje/card-event` block on server.
 */
if ( function_exists( 'nisje_register_block' ) ) {
	\nisje_register_block( __DIR__, [
		'render_callback' => __NAMESPACE__ . '\\render_block',
	] );
}
