<?php

namespace Brandy\BlocksOverride\WooCommerce;

use Brandy\Traits\SingletonTrait;

/**
 * Override WooCommerce product review form block
 */
class WooCommerceReviewForm {
	use SingletonTrait;

	protected function __construct() {
		add_filter( 'block_type_metadata_settings', array( $this, 'override_meta_data' ), 10, 3 );
	}

	/**
	 * Override block callback
	 */
	public function override_meta_data( $settings, $metadata ) {
		if ( 'woocommerce/product-review-form' === $metadata['name'] ) {
			$settings['render_callback'] = array( $this, 'render_callback' );
		}
		return $settings;
	}

	public function render_callback( $attributes, $content, $block ) {

		if ( ! isset( $block->context['postId'] ) ) {
			return '';
		}

		if ( post_password_required( $block->context['postId'] ) ) {
			return;
		}

		$product = \wc_get_product( $block->context['postId'] );

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

		ob_start();
		brandy_get_template_part( 'woocommerce/single-product-review-form', null, array( 'product' => $product ) );
		$rating_html = ob_get_clean();
		return $rating_html;
	}

}
