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

namespace Nisje\BlockLibrary\CardWiki;

/**
 * Renders the `nisje/card-wiki` 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-wiki/' . $attributes['postId'] );
		$nisje_excluded_cards[] = $attributes['postId'];
	} else {
		$posts = \nisje_get_api_data( '/wp/v2/dekode-wiki', [
			'exclude'  => $nisje_excluded_cards,
			'per_page' => 1,
		] );

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

	if ( ! empty( $content ) ) {
		$content['type']      = 'dekode-wiki';
		$content['className'] = "has-{$attributes['columns']}-columns has-{$attributes['rows']}-rows";
		$content['isDark']    = $attributes['isDark'];

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

		unset( $content['_links'] );
	}

	return \wp_json_encode( $content );
}

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