<?php
/**
 * Block context tracker.
 * Prevents badges from being injected inside blocked Gutenberg blocks.
 */

defined( 'ABSPATH' ) || exit;

/**
 * List of block names that should never receive product badges.
 *
 * Example — add more blocks to block:
 *
 *   add_filter( 'cpbw_blocked_blocks', function( $blocks ) {
 *       $blocks[] = 'my-plugin/product-slider';
 *       return $blocks;
 *   } );
 *
 * @return array
 */
function cpbw_get_blocked_blocks() {
    return (array) apply_filters( 'cpbw_blocked_blocks', [
        'cusrev/reviews-grid',
        'cusrev/reviews-slider',
    ] );
}

/**
 * List of blocks that are explicitly allowed to show badges.
 * Overrides cpbw_blocked_blocks for specific block names.
 * By default, empty — nothing is allowed unless opted-in.
 *
 * Example — allow badges in a specific block:
 *
 *   add_filter( 'cpbw_allowed_badge_blocks', function( $blocks ) {
 *       $blocks[] = 'customer-reviews-woocommerce/reviews-block';
 *       return $blocks;
 *   } );
 *
 * @return array
 */
function cpbw_get_allowed_badge_blocks() {
    return (array) apply_filters( 'cpbw_allowed_badge_blocks', [] );
}

/**
 * Simple on/off flag to track if we're inside a blocked block.
 *
 * @param bool|null $set  true to enter, false to exit, null to read
 * @return bool
 */
function cpbw_block_context( $set = null ) {
    static $inside = false;
    if ( $set !== null ) {
        $inside = $set;
    }
    return $inside;
}

/**
 * Check if badges are allowed inside a specific block.
 *
 * @param string $block_name Block name being rendered (e.g. 'my-plugin/slider')
 * @return bool
 */
function cpbw_is_badge_allowed_in_block( $block_name ) {
    return in_array( $block_name, cpbw_get_allowed_badge_blocks(), true );
}

/**
 * Wrap block rendering to toggle the block context flag.
 * Uses pre_render_block to set the flag BEFORE the block's render callback fires
 * (so woocommerce_product_get_image is suppressed during render), then resets
 * the flag in render_block after the output is produced.
 */
add_filter( 'pre_render_block', function( $pre_render, $block ) {
    $block_name = $block['blockName'] ?? '';

    if (
        in_array( $block_name, cpbw_get_blocked_blocks(), true ) &&
        ! cpbw_is_badge_allowed_in_block( $block_name )
    ) {
        cpbw_block_context( true );
    }

    return $pre_render; // null — let the block render normally.
}, 9, 2 ); // Priority 9 — runs before the block's render_callback.

add_filter( 'render_block', function( $block_content, $block ) {
    $block_name = $block['blockName'] ?? '';

    if ( in_array( $block_name, cpbw_get_blocked_blocks(), true ) ) {
        cpbw_block_context( false );
    }

    return $block_content;
}, 11, 2 ); // Priority 11 — runs after block has rendered.
