<?php
/**
 * Buy Now block.
 *
 * @package WPDudeProducts
 */

declare(strict_types=1);

namespace WPDude\Products\Blocks;

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

/**
 * dude-commerce/buy
 */
final class Buy_Block {

	use Block_Helpers;

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

	/**
	 * 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'         => 'buy',
				'handle'      => 'wpdude-dc-buy-block',
				'title'       => __( 'Dude Commerce Buy Now', 'dude-commerce' ),
				'description' => __( 'Buy Now button with options and quantity.', '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_buy(
			array(
				'id'     => (string) $product_id,
				'button' => sanitize_text_field( (string) ( $attributes['buttonText'] ?? '' ) ),
			)
		);

		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;
	}
}
