<?php
/**
 * Add to Wishlist block — server-side registration and render callback.
 *
 * Renders the wishlist button for the product currently in context
 * (product query loop, product template, etc.).
 *
 * @package JWP_STK
 */

namespace JWP_STK\Blocks\AddToWishlist;

defined( 'ABSPATH' ) || exit;

/**
 * Block class.
 */
class Block {

	/**
	 * Register this block type with WordPress.
	 *
	 * @param string $asset_dir Absolute path to the compiled block directory.
	 * @return void
	 */
	public function register( string $asset_dir ) {
		register_block_type(
			$asset_dir,
			array(
				'render_callback' => array( $this, 'render' ),
			)
		);
	}

	/**
	 * Render the button on the frontend.
	 *
	 * Resolves the product ID from the block context (query loops / product
	 * templates) and delegates to the wishlist button shortcode.
	 *
	 * @param array<string, mixed> $attributes Block attributes.
	 * @param string               $content    Inner content (unused).
	 * @param \WP_Block            $block      Block instance carrying context.
	 * @return string HTML output.
	 */
	public function render( array $attributes, string $content, $block ) {
		$product_id = 0;

		// Prefer context postId (query loops, product templates).
		if ( ! empty( $block->context['postId'] ) ) {
			$product_id = (int) $block->context['postId'];
		}

		// Fall back to global $product (classic product hooks).
		if ( ! $product_id ) {
			global $product;
			if ( $product instanceof \WC_Product ) {
				$product_id = $product->get_id();
			}
		}

		if ( ! $product_id ) {
			return '';
		}

		if ( ! shortcode_exists( 'storetoolkit_add_to_wishlist' ) ) {
			return '';
		}

		return do_shortcode(
			'[storetoolkit_add_to_wishlist product_id="' . esc_attr( $product_id ) . '" context="block"]'
		);
	}
}
