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

declare( strict_types = 1 );
namespace Nisje\BlockLibrary\WikiCategories;

use function T2\Icons\icon;

/**
 * Renders the `nisje/wiki-categories` block on server
 *
 * @param array $attributes The block attributes.
 *
 * @return string Returns the post content with links added.
 */
function render_block( array $attributes ): string {
	$taxonomies = \get_terms( [
		'taxonomy'   => 'dekode-wiki-category',
		'hide_empty' => true,
		'parent'     => 0,
	] );

	$wrapper_markup = '<ul %1$s>%2$s</ul>';
	$items_markup   = '';
	$slug           = \apply_filters( 'nisje_wiki_slug', 'wiki' );

	if ( ! empty( $taxonomies ) ) {
		foreach ( $taxonomies as $category ) {
			ob_start();
			?>
			<li class="wp-block-nisje-wiki-categories__category">
				<a class="wp-block-nisje-wiki-categories__link" href="/<?php echo esc_attr( $slug ); ?>/category/<?php echo \esc_attr( $category->slug ); ?>/">
					<span class="wp-block-nisje-wiki-categories__link-content">
						<span class="wp-block-nisje-wiki-categories__content">
							<div class="wp-block-nisje-wiki-categories__inner">
								<h2><?php echo \esc_html( $category->name ); ?></h2>
								<p><?php echo \esc_html( $category->description ); ?></p>
							</div>
							<div class="wp-block-nisje-wiki-categories__count"><?php echo \esc_html( $category->count ); ?> <?php echo \esc_html( _n( 'article', 'articles', $category->count, 'nisje' ) ); ?></div>
						</span>
						<span class="wp-block-nisje-wiki-categories__icon">
							<?php icon( \is_rtl() ? 'arrowBack' : 'arrowForward' ); ?>
						</span>
					</span>
				</a>
			</li>
			<?php
			$items_markup .= ob_get_clean();
		}
	}

	$wrapper_attributes = \get_block_wrapper_attributes( [ 'class' => 'wp-block-nisje-wiki-categories__wrapper' ] );

	return sprintf(
		$wrapper_markup,
		$wrapper_attributes,
		$items_markup
	);
}

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