<?php
/**
 * Product price block.
 *
 * @package WPDudeProducts
 */

declare(strict_types=1);

namespace WPDude\Products\Blocks;

use WPDude\Products\Frontend\Assets;
use WPDude\Products\Frontend\Shortcodes;

/**
 * dude-commerce/price
 */
final class Price_Block {

	use Block_Helpers;

	public const BLOCK_NAME = 'dude-commerce/price';

	/**
	 * Register hooks.
	 */
	public function register(): void {
		add_action( 'init', array( $this, 'register_block' ) );
	}

	/**
	 * Register block.
	 */
	public function register_block(): void {
		$this->register_dynamic_block(
			array(
				'dir'         => 'price',
				'handle'      => 'wpdude-dc-price-block',
				'title'       => __( 'Dude Commerce Price', 'dude-commerce' ),
				'description' => __( 'Display the product price (updates with options).', 'dude-commerce' ),
				'callback'    => array( $this, 'render' ),
			)
		);
	}

	/**
	 * @param array<string, mixed> $attributes Attributes.
	 */
	public function render( array $attributes ): string {
		$product_id = absint( $attributes['productId'] ?? 0 );
		if ( $product_id <= 0 ) {
			return $this->is_editor_preview()
				? '<p class="wpdude-dc-block-placeholder">' . esc_html__( 'Select a product in the block settings.', 'dude-commerce' ) . '</p>'
				: '';
		}

		Assets::mark_needed();
		$html = ( new Shortcodes() )->render_price( array( 'id' => (string) $product_id ) );

		if ( '' === $html && $this->is_editor_preview() ) {
			return '<p class="wpdude-dc-block-placeholder">' . esc_html__( 'This product is unavailable or not published.', 'dude-commerce' ) . '</p>';
		}

		return $html;
	}
}
