<?php
/**
 * Shared block helpers.
 *
 * @package WPDudeProducts
 */

declare(strict_types=1);

namespace WPDude\Products\Blocks;

/**
 * Common block registration helpers.
 */
trait Block_Helpers {

	/**
	 * Whether this render is for the block editor preview.
	 */
	protected function is_editor_preview(): bool {
		return ( defined( 'REST_REQUEST' ) && REST_REQUEST && current_user_can( 'edit_posts' ) )
			|| ( is_admin() && current_user_can( 'edit_posts' ) );
	}

	/**
	 * Register a dynamic block from assets/blocks/{dir}.
	 *
	 * @param array{dir: string, handle: string, title: string, description: string, callback: callable} $args Args.
	 */
	protected function register_dynamic_block( array $args ): void {
		$dir    = (string) $args['dir'];
		$handle = (string) $args['handle'];
		$path   = WPDUDE_DC_PATH . 'assets/blocks/' . $dir;

		wp_register_script(
			$handle,
			WPDUDE_DC_URL . 'assets/blocks/' . $dir . '/index.js',
			array(
				'wp-blocks',
				'wp-element',
				'wp-block-editor',
				'wp-components',
				'wp-data',
				'wp-server-side-render',
				'wp-i18n',
			),
			WPDUDE_DC_VERSION,
			true
		);

		wp_register_style(
			$handle . '-editor',
			WPDUDE_DC_URL . 'assets/css/frontend.css',
			array(),
			WPDUDE_DC_VERSION
		);

		register_block_type(
			$path,
			array(
				'title'           => (string) $args['title'],
				'description'     => (string) $args['description'],
				'editor_script'   => $handle,
				'editor_style'    => $handle . '-editor',
				'render_callback' => $args['callback'],
			)
		);
	}
}
