<?php
/**
 * Saved layout block render and register.
 *
 * @package visual-portfolio
 */

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

/**
 * Class Visual_Portfolio_Gutenberg_Saved_Block
 */
class Visual_Portfolio_Gutenberg_Saved_Block {
	/**
	 * Registered controls, that will be used in Gutenberg block.
	 *
	 * @var array
	 */
	public $registered_controls = array();

	/**
	 * Visual_Portfolio_Gutenberg_Saved_Block constructor.
	 */
	public function __construct() {
		add_action( 'init', array( $this, 'register_block' ), 11 );
		add_action( 'admin_init', array( $this, 'register_block_layouts_editor' ), 11 );
	}

	/**
	 * Register Block.
	 */
	public function register_block() {
		$saved_block = register_block_type_from_metadata(
			visual_portfolio()->plugin_path . 'gutenberg/block-saved',
			array(
				'render_callback' => array( $this, 'block_render' ),
			)
		);

		if ( ! $saved_block ) {
			return;
		}

		// Legacy alias used only to migrate old content to the current block name.
		register_block_type(
			'nk/visual-portfolio',
			array(
				'api_version'     => $saved_block->api_version,
				'render_callback' => array( $this, 'block_render' ),
				'attributes'      => array(
					'id' => array(
						'type' => 'string',
					),
					'align' => array(
						'type' => 'string',
					),
					'className' => array(
						'type' => 'string',
					),
					'anchor' => array(
						'type' => 'string',
					),
				),
				'supports'        => array_merge(
					(array) $saved_block->supports,
					array(
						'inserter' => false,
					)
				),
			)
		);
	}

	/**
	 * Register Block for Layouts Editor.
	 */
	public function register_block_layouts_editor() {
		global $pagenow;

		if (
			'post.php' === $pagenow && isset( $_GET['post'] ) && 'vp_lists' === get_post_type( $_GET['post'] ) ||
			'post-new.php' === $pagenow && isset( $_GET['post_type'] ) && 'vp_lists' === $_GET['post_type']
		) {
			register_block_type_from_metadata(
				visual_portfolio()->plugin_path . 'gutenberg/layouts-editor/block'
			);
		}
	}

	/**
	 * Block output
	 *
	 * @param array $attributes - block attributes.
	 *
	 * @return string
	 */
	public function block_render( $attributes ) {
		$attributes = array_merge(
			array(
				'id'        => '',
				'align'     => '',
				'className' => '',
			),
			$attributes
		);

		if ( ! $attributes['id'] ) {
			return '';
		}

		// WPML support.
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		$attributes['id'] = apply_filters( 'wpml_object_id', $attributes['id'], 'vp_lists', true );

		$class_name = 'wp-block-visual-portfolio';

		$wrapper_attributes = get_block_wrapper_attributes(
			array(
				'class' => $class_name,
			)
		);

		return sprintf( '<div %1$s>%2$s</div>', $wrapper_attributes, Visual_Portfolio_Get::get( array( 'id' => $attributes['id'] ) ) );
	}
}
new Visual_Portfolio_Gutenberg_Saved_Block();
