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

namespace Nisje\BlockLibrary\CardLatest;

/**
 * Renders the `nisje/card-latest` 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-latest 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_card_latest_args', [
		'exclude'  => $nisje_excluded_cards,
		'per_page' => 1,
	], $block );

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

	$content = [];

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

	return \wp_json_encode( $content );
}

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