<?php
/**
 * Category Primary Block.
 *
 * @package CategoryLabelsBlock
 */

/**
 * Main class that handles the server-side functionality of category primary block.
 */
class Category_Primary_Core_Block {

	/**
	 * Constructor.
	 *
	 * @return void
	 */
	public function __construct() {
		add_action( 'init', array( $this, 'register' ) );
		add_action( 'init', array( $this, 'register_assets' ) );
	}

	/**
	 * Registers the block on server side.
	 *
	 * @return void
	 */
	public function register() {

		register_block_type_from_metadata(
			CLB_DIR_PATH . 'dist/category-link-primary/block.json',
			array(
				/**
				 * Adding a rendering condition to the link when it's not scoped within the current post.
				 *
				 * @param array     $block_attributes - Attributes.
				 * @param string    $content - Block content.
				 * @param WP_Block  $block_instance - Block instance.
				 *
				 * @return string - Block content.
				 */
				'render_callback' => function( $block_attributes, $content, $block_instance ) {

					$current_term = clb_get_primary_term();
					$fallback = isset( $block_attributes['fallback'] ) ? $block_attributes['fallback'] : false;

					if ( is_null( $current_term ) || is_wp_error( $current_term ) || ! $current_term instanceof \WP_Term ) {
						return '';
					}

					if ( $current_term instanceof \WP_Term && $fallback && 0 !== $current_term->parent )	{
						$parent_term = clb_get_topmost_parent_term( $current_term );
						
						if ( is_null( $parent_term ) || is_wp_error( $parent_term ) ) {
							return '';
						}

						$current_term = $parent_term;
					}

					$content = str_replace( '{{title}}', $current_term->name, $content );
					$content = str_replace( '{{link}}', get_term_link( $current_term ), $content );

					return $content;
				},
			)
		);

	}

	/**
	 * Registers the necessary block assets.
	 *
	 * @return void
	 */
	public function register_assets() {
		wp_register_script(
			'category-link-primary-block-script',
			CLB_PLUGIN_URL . 'dist/category-link-primary.js',
			array(),
			uniqid(),
			true
		);
	}
}

new Category_Primary_Core_Block();
