<?php
/**
 * Lantern Span People Directory directory block.
 *
 * @package LanternSpanPeopleDirectory
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Registers the block-editor directory block.
 */
class LSPD_Block {

	/**
	 * Directory renderer.
	 *
	 * @var LSPD_Directory
	 */
	private $directory;

	/**
	 * Sets up the block.
	 *
	 * @param LSPD_Directory $directory Directory renderer.
	 */
	public function __construct( $directory ) {
		$this->directory = $directory;
		add_action( 'init', array( $this, 'register_block' ), 20 );
	}

	/**
	 * Registers scripts and the dynamic block.
	 *
	 * @return void
	 */
	public function register_block() {
		$script_path    = LSPD_PATH . 'assets/js/block.js';
		$script_version = file_exists( $script_path ) ? (string) filemtime( $script_path ) : LSPD_VERSION;

		wp_register_script(
			'lspd-directory-block',
			LSPD_URL . 'assets/js/block.js',
			array( 'wp-blocks', 'wp-element', 'wp-components', 'wp-block-editor', 'wp-i18n' ),
			$script_version,
			true
		);

		wp_set_script_translations(
			'lspd-directory-block',
			'lantern-span-people-directory',
			LSPD_PATH . 'languages'
		);

		register_block_type(
			LSPD_PATH . 'blocks/directory',
			array(
				'editor_script'   => 'lspd-directory-block',
				'style'           => 'lspd-directory',
				'render_callback' => array( $this, 'render_block' ),
			)
		);
	}

	/**
	 * Renders the dynamic directory block.
	 *
	 * @param array<string, mixed> $attributes Block attributes.
	 * @return string
	 */
	public function render_block( $attributes = array() ) {
		return $this->directory->render_shortcode( is_array( $attributes ) ? $attributes : array() );
	}
}
