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

namespace Nisje\Retriever\CardRetriever;

/**
 * Renders the `nisje/card-retriever` block on server
 *
 * @param array $attributes The block attributes.
 * @return string Returns the post content with links added.
 */
function render_block( $attributes ) {
	$content = [
		'type'   => 'nisje-retriever',
		'isDark' => $attributes['isDark'],
		'items'  => [],
		'title'  => \apply_filters( 'nisje_retriever_title', 'Retriever', 'nisje-theme' ),
	];

	if ( isset( $attributes['backgroundColor'] ) ) {
		$content['className'] = "has-{$attributes['backgroundColor']}-background-color";
	} elseif ( isset( $attributes['customBackgroundColor'] ) ) {
		$content['bg'] = $attributes['customBackgroundColor'];
	}

	$args = [
		'per_page' => 5,
		'_fields'  => 'id,title,link',
	];

	$posts = \nisje_get_api_data( '/wp/v2/nisje-retriever', $args );

	if ( ! empty( $posts ) ) {
		foreach ( $posts as $item ) {
			$content['items'][] = [
				'id'    => $item['id'],
				'title' => $item['title']['rendered'],
				'link'  => $item['link'],
			];
		}
	}

	return \wp_json_encode( $content );
}

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