<?php
/**
 * Wishlist Block
 */

/**
 * Register the Wishlist block.
 *
 * @since 2.2.26
 *
 * @return void
 */
function rwe_register_wishlist_block() {
	if ( ! function_exists( 'register_block_type' ) ) {
		return;
	}

	register_block_type( 'rwe-blocks/wishlist-block', [
		'editor_script' => 'wishlist-block-editor',
		'attributes'    => [
			'className' => [ 'type' => 'string' ]
		]
	] );
}
add_action( 'init', 'rwe_register_wishlist_block' );

/**
 * Enqueue wishlist block editor assets
 *
 * @since 2.2.26
 *
 * @return void
 */
function rwe_enqueue_wishlist_block_editor_assets() {
	wp_enqueue_script( 'rwe-wishlist-block-editor' );

	wp_enqueue_style( 'rwe-gallery' );

	wp_add_inline_style( 'rwe-gallery', rwe_generate_inline_styles() );
}
add_action( 'enqueue_block_editor_assets', 'rwe_enqueue_wishlist_block_editor_assets' );

/**
 * Create an endpoint to deliver the wishlist shortcode content.
 *
 * @since 2.2.26
 *
 * @return void
 */
function rwe_wishlist_shortcode_rest_endpoint() {
	register_rest_route( 'rw-elephant/v1', '/wishlist-shortcode', [
		'methods'  => 'GET',
		'callback' => function( WP_REST_Request $request ) {
			$cls_raw  = $request->get_param( 'class' ) ?: '';
			$pieces   = array_filter( preg_split( '/\s+/', $cls_raw ) );
			$classes  = array_map( 'sanitize_html_class', $pieces );
			$attr     = $classes ? ' class="' . esc_attr( implode( ' ', $classes ) ) . '"' : '';
			return rest_ensure_response( do_shortcode( '[rw-elephant-wishlist' . $attr . ']' ) );
		}
	] );
}
add_action( 'rest_api_init', 'rwe_wishlist_shortcode_rest_endpoint' );

/**
 * Retrieve the wishlist shortcode content from the REST API.
 *
 * @since 2.2.26
 *
 * @param $request
 *
 * @return mixed
 */
function rwe_get_wishlist_shortcode( $request ) {
	// Retrieve and return the shortcode content
	$shortcode_content = do_shortcode( '[rw-elephant-wishlist]' );
	return rest_ensure_response( $shortcode_content );
}
