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

namespace Nisje\BlockLibrary\CardNews;

/**
 * Renders the `nisje/card-news` 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 = [];
	$fields  = 'date_gmt,excerpt,featuredImage,title,group_id,group_name';

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

		if ( isset( $attributes['categoryId'] ) && 0 !== $attributes['categoryId'] ) {
			$args['dekode-news-categories'] = $attributes['categoryId'];
		}

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

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

	if ( ! empty( $content ) ) {
		$content['className'] = '';

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

		$content['type']       = 'dekode-news';
		$content['className'] .= " has-{$attributes['columns']}-columns has-{$attributes['rows']}-rows";

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

	return \wp_json_encode( $content );
}

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