<?php
/**
 * Full product block.
 *
 * @package WPDudeProducts
 */

declare(strict_types=1);

namespace WPDude\Products\Blocks;

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

/**
 * dude-commerce/product
 */
final class Product_Block {

	use Block_Helpers;

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

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

	/**
	 * Editor preview styles.
	 */
	public function enqueue_editor_assets(): void {
		wp_enqueue_style(
			'wpdude-dc-frontend',
			WPDUDE_DC_URL . 'assets/css/frontend.css',
			array(),
			WPDUDE_DC_VERSION
		);
	}

	/**
	 * Register block.
	 */
	public function register_block(): void {
		$this->register_dynamic_block(
			array(
				'dir'         => 'product',
				'handle'      => 'wpdude-dc-product-block',
				'title'       => __( 'Dude Commerce Product', 'dude-commerce' ),
				'description' => __( 'Display a product with images, price, and Buy Now.', '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();

		// Default on; false must survive ServerSideRender (use POST in editor).
		$show_title = true;
		if ( array_key_exists( 'showTitle', $attributes ) ) {
			$show_title = filter_var( $attributes['showTitle'], FILTER_VALIDATE_BOOLEAN );
		}
		$button = sanitize_text_field( (string) ( $attributes['buttonText'] ?? '' ) );

		$html = ( new Shortcodes() )->render_product(
			array(
				'id'         => (string) $product_id,
				'show_title' => $show_title ? 'yes' : 'no',
				'button'     => $button,
			)
		);

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