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

namespace Nisje\BlockLibrary\CardUserContent;

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

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

	$args = \apply_filters( 'nisje_block_library_user_content_card_args', [
		'exclude'    => $nisje_excluded_cards,
		'per_page'   => 1,
		'post_types' => [ 'nisje-user-content' ],
	], $block );

	$posts = \nisje_get_api_data( '/dekode-intranet/v1/feed', $args );

	$content = [];

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

	return \wp_json_encode( $content );
}

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