<?php

if ( ! defined( 'ABSPATH' ) ) { return; }
if ( ! function_exists( 'is_singular' ) || ! is_singular( 'product' ) ) { return; }
if ( ! function_exists( 'wc_get_product' ) ) { return; }

$product_id = (int) get_the_ID();
$product    = wc_get_product( $product_id );
if ( ! $product instanceof WC_Product ) { return; }

$is_on_sale     = $product->is_on_sale();
$show_non_sale  = ! empty( $attributes['showOnNonSale'] );
if ( ! $is_on_sale && ! $show_non_sale ) { return; }

$tier = 'anonymous';
if ( is_user_logged_in() ) {
    $tier = 'logged_in';
    if ( class_exists( 'AIEO_DMM_Role_Pricing' ) && class_exists( 'AIEO_DMM' ) ) {
        
        
        
        $tier = (string) apply_filters(
            'aieo_sale_eligibility_tier',
            $tier,
            $product,
            get_current_user_id()
        );
    }
}

$message_key = 'messageAnonymous';
if ( $tier === 'logged_in' )    { $message_key = 'messageLoggedIn'; }
if ( $tier === 'pro' )          { $message_key = 'messageProMember'; }

$template = isset( $attributes[ $message_key ] ) ? (string) $attributes[ $message_key ] : '';
if ( $template === '' ) { return; }

$regular_raw = (float) $product->get_regular_price();
$sale_raw    = (float) $product->get_sale_price();
$savings_raw = max( 0, $regular_raw - $sale_raw );
$pct         = $regular_raw > 0 ? round( 100 * $savings_raw / $regular_raw ) : 0;

$tokens = array(
    '{regular_price}'  => function_exists( 'wc_price' ) ? wc_price( $regular_raw ) : (string) $regular_raw,
    '{sale_price}'     => function_exists( 'wc_price' ) ? wc_price( $sale_raw )    : (string) $sale_raw,
    '{savings_amount}' => function_exists( 'wc_price' ) ? wc_price( $savings_raw ) : (string) $savings_raw,
    '{savings_pct}'    => $pct . '%',
    '{role}'           => esc_html( $tier ),
);
$message = str_replace( array_keys( $tokens ), array_values( $tokens ), $template );

$wrapper_attrs = function_exists( 'get_block_wrapper_attributes' )
    ? get_block_wrapper_attributes( array(
        'class'        => 'aieo-sale-eligibility aieo-sale-eligibility--' . sanitize_html_class( $tier ),
        'data-tier'    => $tier,
        'data-on-sale' => $is_on_sale ? '1' : '0',
    ) )
    : 'class="aieo-sale-eligibility aieo-sale-eligibility--' . esc_attr( sanitize_html_class( $tier ) ) . '"';

echo '<div ' . $wrapper_attrs . '>' . wp_kses_post( $message ) . '</div>'; 
