<?php
/**
 * Block and style registration functions.
 *
 * @package Nisje
 */

declare( strict_types=1 );
namespace NisjeFrontend\Blocks;

/**
 * Register blocks.
 */
function register_block_types() {
	// Blocks directory may not exist if working from a fresh clone.
	$blocks_dir = dirname( __FILE__ ) . '/../build/block-library/blocks/';
	if ( ! file_exists( $blocks_dir ) ) {
		return;
	}

	$block_folders = [
		'files',
	];

	foreach ( $block_folders as $folder_name ) {
		$block_json_file = $blocks_dir . $folder_name . '/block.json';
		if ( ! file_exists( $block_json_file ) ) {
			return;
		}

		$metadata = json_decode( file_get_contents( $block_json_file ), true ); // phpcs:ignore
		if ( ! is_array( $metadata ) || ! $metadata['name'] ) {
			return false;
		}

		register_block_type(
			$metadata['name'],
			$metadata
		);
	}
}
add_action( 'init', __NAMESPACE__ . '\\register_block_types' );

/**
 * Allow passing through the block comment to the API.
 *
 * @param null  $retval Default null.
 * @param array $block  A single parsed block object.
 *
 * @return null|string
 */
function passthrough_block_comments( $retval, $block ) { // phpcs:ignore
	$nisje_blocks = [
		'nisje/files',
	];

	foreach ( $nisje_blocks as $nisje_block ) {
		if ( $nisje_block === $block['blockName'] ) {
			$json = ! empty( $block['attrs'] ) ? wp_json_encode( $block['attrs'] ) : '{}';
			return '<!-- wp:' . $block['blockName'] . ' ' . $json . ' /-->';
		}
	}

	return $retval;
}
add_filter( 'pre_render_block', __NAMESPACE__ . '\\passthrough_block_comments', 10, 2 );
