<?php
/**
 * Functions to register client-side assets (scripts and stylesheets) for the
 * Gutenberg block.
 *
 * @package {{namespace}}
 */

/**
 * Registers all block assets so that they can be enqueued through Gutenberg in
 * the corresponding context.
 *
 * @see https://wordpress.org/gutenberg/handbook/blocks/writing-your-first-block-type/#enqueuing-block-scripts
 */
function {{machine_name}}_block_init() {
	// Skip block registration if Gutenberg is not enabled/merged.
	if ( ! function_exists( 'register_block_type' ) ) {
		return;
	}
	{{#plugin}}
	$dir = dirname( __FILE__ );
	{{/plugin}}
	{{#theme}}
	$dir = get_template_directory() . '/blocks';
	{{/theme}}

	$index_js = '{{slug}}/index.js';
	wp_register_script(
		'{{slug}}-block-editor',
		{{#plugin}}
		plugins_url( $index_js, __FILE__ ),
		{{/plugin}}
		{{#theme}}
		get_template_directory_uri() . "/blocks/$index_js,
		{{/theme}}
		array(
			'wp-blocks',
			'wp-i18n',
			'wp-element',
		),
		filemtime( "$dir/$index_js" )
	);

	$editor_css = '{{slug}}/editor.css';
	wp_register_style(
		'{{slug}}-block-editor',
		{{#plugin}}
		plugins_url( $editor_css, __FILE__ ),
		{{/plugin}}
		{{#theme}}
		get_template_directory_uri() . "/blocks/$editor_css",
		{{/theme}}
		array(),
		filemtime( "$dir/$editor_css" )
	);

	$style_css = '{{slug}}/style.css';
	wp_register_style(
		'{{slug}}-block',
		{{#plugin}}
		plugins_url( $style_css, __FILE__ ),
		{{/plugin}}
		{{#theme}}
		get_template_directory_uri() . "/blocks/$style_css",
		{{/theme}}
		array(),
		filemtime( "$dir/$style_css" )
	);

	register_block_type( '{{namespace}}/{{slug}}', array(
		'editor_script' => '{{slug}}-block-editor',
		'editor_style'  => '{{slug}}-block-editor',
		'style'         => '{{slug}}-block',
	) );
}
add_action( 'init', '{{machine_name}}_block_init' );
