<?php
/**
 * Snippet block for Gutenberg editor
 *
 * @package Woody_Code_Snippets
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * WINP_Gutenberg_Snippet Class
 */
class WINP_Gutenberg_Snippet {

	/**
	 * Shortcode data.
	 *
	 * @var array<int, array<string, mixed>>
	 */
	protected $shortcode_data;

	/**
	 * WINP_Gutenberg_Snippet constructor.
	 */
	public function __construct() {
		$this->register_hooks();
	}

	/**
	 * Register WordPress hooks.
	 *
	 * @return void
	 */
	private function register_hooks() {
		add_action( 'init', [ $this, 'init' ] );
	}

	/**
	 * Initialize the Gutenberg block.
	 *
	 * @return void
	 */
	public function init() {
		$this->shortcode_data = WINP_Helper::get_shortcode_data();

		if ( empty( $this->shortcode_data ) ) {
			return;
		}

		// Register the block type and get the WP_Block_Type instance.
		$block_type = register_block_type( WINP_PLUGIN_DIR . '/admin/assets/gutenberg/build/block.json' );

		/**
		 * Register snippets object, so it can be accessible within Gutenberg.
		 * The script handle is automatically generated by WordPress from the block name.
		 */
		if ( $block_type && ! empty( $block_type->editor_script_handles ) ) {
			wp_localize_script(
				$block_type->editor_script_handles[0],
				'winp_snippets',
				[
					'data' => $this->prepared_snippets_data(),
				]
			);
		}
	}

	/**
	 * Prepare snippets data for the block editor.
	 *
	 * @return array<int, array<string, mixed>>
	 */
	public function prepared_snippets_data() {
		return self::get_prepared_snippets_data();
	}

	/**
	 * Get prepared snippets data statically for use in render.php.
	 *
	 * @return array<int, array<string, mixed>>
	 */
	public static function get_prepared_snippets_data() {
		$shortcode_data  = WINP_Helper::get_shortcode_data();
		$prepared_object = [];

		foreach ( (array) $shortcode_data as $item ) {

			if ( ! isset( $item['id'] ) ) {
				continue;
			}

			$tags = isset( $item['snippet_tags'] ) ? $item['snippet_tags'] : [];
			$tags = array_values(
				array_filter(
					$tags,
					function ( $tag ) {
						return 'id' !== $tag;
					} 
				) 
			);

			$prepared_object[ $item['id'] ] = [
				'id'    => $item['id'],
				'title' => $item['title'],
				'type'  => isset( $item['type'] ) ? $item['type'] : '',
				'tags'  => $tags,
			];
		}

		return $prepared_object;
	}
}
