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

namespace Nisje\BlockLibrary\CardLatestNews;

/**
 * Renders the `nisje/card-latest-news` 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-latest-news',
		'isDark'   => $attributes['isDark'],
		'items'    => [],
		'title'    => __( 'Latest news', 'nisje' ),
		'moreLink' => '/news/',
	];

	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,featured_media',
	];

	if ( isset( $attributes['categoryId'] ) && 0 !== $attributes['categoryId'] ) {
		$category = get_term( $attributes['categoryId'], 'dekode-news-category' );
		if ( $category && ! is_wp_error( $category ) ) {
			$args['dekode-news-categories'] = $attributes['categoryId'];
			$content['title']               = $category->name;
			$content['moreLink']            = '/news/category/' . $attributes['categoryId'] . '/';
		}
	}

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

	if ( ! empty( $posts ) ) {
		foreach ( $posts as $item ) {
			$content['items'][] = apply_filters( 'nisje_news_card_latest_news_content_item', [
				'id'            => $item['id'],
				'title'         => $item['title']['rendered'],
				'featuredImage' => wp_get_attachment_image_url( $item['featured_media'], 'thumbnail', false ),
			] );
		}
	}

	$content = \apply_filters( 'nisje_news_card_latest_news_content', $content );

	return \wp_json_encode( $content );
}

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