<?php

if ( ! defined( 'ABSPATH' ) ) { return; }

if ( ! function_exists( 'is_singular' ) || ! is_singular( 'product' ) ) {
    return;
}
if ( ! class_exists( 'AIEO_DMM' ) ) {
    return;
}

$module_id     = isset( $attributes['moduleId'] ) ? sanitize_key( (string) $attributes['moduleId'] ) : '';
$render_method = isset( $attributes['renderMethod'] ) && is_string( $attributes['renderMethod'] )
    ? preg_replace( '/[^a-zA-Z0-9_]/', '', $attributes['renderMethod'] )
    : 'output';
if ( $module_id === '' || $render_method === '' ) { return; }

$dmm    = AIEO_DMM::instance();
$module = $dmm->get_module( $module_id );

if ( ! is_object( $module ) ) {
    $alt = strpos( $module_id, '-' ) !== false ? str_replace( '-', '_', $module_id ) : str_replace( '_', '-', $module_id );
    $module = $dmm->get_module( $alt );
    if ( is_object( $module ) ) { $module_id = $alt; }
}
if ( ! is_object( $module ) || ! method_exists( $module, $render_method ) ) {
    return;
}

$bridge_zone = isset( $attributes['zone'] ) ? sanitize_key( (string) $attributes['zone'] ) : '';
if ( $bridge_zone === 'info' || $bridge_zone === 'under' ) {
    $cluster_id = ( isset( $attributes['clusterId'] ) && $attributes['clusterId'] !== '' )
        ? sanitize_key( (string) $attributes['clusterId'] )
        : $module_id;
    $zones    = get_option( 'aieo_dmm_product_display_zones', array() );
    $assigned = ( is_array( $zones ) && isset( $zones[ $cluster_id ] ) && $zones[ $cluster_id ] === 'under' ) ? 'under' : 'info';
    if ( $bridge_zone !== $assigned ) { return; }
}

if ( method_exists( $module, 'is_active' ) && ! $module->is_active() ) {
    return;
}

ob_start();
$module->{$render_method}();
$inner = (string) ob_get_clean();
if ( $inner === '' ) { return; }

$wrapper_attrs = function_exists( 'get_block_wrapper_attributes' )
    ? get_block_wrapper_attributes( array(
        'class'          => 'aieo-dmm-bridge aieo-dmm-bridge--' . sanitize_html_class( $module_id ),
        'data-module-id' => $module_id,
    ) )
    : 'class="aieo-dmm-bridge aieo-dmm-bridge--' . esc_attr( sanitize_html_class( $module_id ) ) . '" data-module-id="' . esc_attr( $module_id ) . '"';

ob_start();
?>
<div <?php echo $wrapper_attrs; ?>>
    <?php echo $inner; ?>
</div>
<?php
echo ob_get_clean(); 
