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

namespace Nisje\BlockLibrary\Feed;

/**
 * Renders the `nisje/feed` block on server.
 *
 * @param array     $attributes The block attributes.
 * @param string    $content    The block content.
 * @param \WP_Block $block      The block.
 *
 * @return string Returns the post content with feed added.
 */
function render_block( array $attributes, string $content, \WP_Block $block ): string {
	global $nisje_excluded_cards;

	if ( ! isset( $nisje_excluded_cards ) ) {
		$nisje_excluded_cards = [];
	}

	$cards = array_filter( explode( "\n", $content ) );
	$items = [];

	foreach ( $cards as $key => $card ) {
		$card_data = json_decode( $card );

		if ( ! empty( $card_data ) ) {
			$items[] = \wp_parse_args( $card_data, [
				'id' => uniqid(),
			] );
		}
	}

	$posts = [
		'infinite' => false,
	];

	if ( isset( $attributes['infiniteScroll'] ) && $attributes['infiniteScroll'] ) {
		// Calculate spaced used.
		$cols = 0;
		foreach ( $block->inner_blocks as $inner_block ) {
			$block_cols  = $inner_block->parsed_block['attrs']['columns'] ?? 2;
			$block_rows  = $inner_block->parsed_block['attrs']['rows'] ?? 1;
			$block_space = $block_cols * $block_rows;
			$cols        = $cols + $block_space;
		}

		if ( $cols < 24 ) {
			$args = \apply_filters( 'nisje_block_library_feed_infinite_args', [
				'exclude'  => $nisje_excluded_cards,
				'per_page' => 24 - ( $cols / 2 ),
			], $block );

			$infinite_posts = \nisje_get_api_data( '/dekode-intranet/v1/feed', $args );

			foreach ( $infinite_posts as $infinite_post ) {
				$infinite_post['type']  = $infinite_post['post_type'];
				$items[]                = $infinite_post;
				$nisje_excluded_cards[] = $infinite_post['id'];
			}
		}

		$posts['exclude']  = $nisje_excluded_cards;
		$posts['infinite'] = true;

		if ( isset( $block->context['postType'] ) && isset( $block->context['postId'] ) && 'nisje-feed-group' === $block->context['postType'] ) {
			$group = \get_post_meta( $block->context['postId'], 'group_id', true );

			if ( $group ) {
				$posts['query'] = [
					'group_id' => $group,
				];
			}
		}
	}

	$posts['items'] = $items;

	$json = ! empty( $posts ) ? \wp_json_encode( $posts ) : '[]';

	return '<!-- nisje:feed ' . $json . ' /-->';
}

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