<?php

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

if ( ! is_singular( 'post' ) ) { return; }

$post_id = (int) get_the_ID();
if ( $post_id <= 0 ) { return; }

$rels = AIEO_DMM_Term_Relations::for_post( $post_id, 'post' );
if ( empty( $rels ) ) { return; }

$default_heading = __( 'Σχετικά με', 'ai-eshop-optimizer' );
$heading = isset( $attributes['heading'] ) && trim( (string) $attributes['heading'] ) !== ''
    ? trim( (string) $attributes['heading'] )
    : $default_heading;

$needs = array();
foreach ( $rels as $r ) {
    if ( ( $r['taxonomy'] ?? '' ) !== 'pa_need' ) { continue; }
    $term_id = (int) ( $r['term_id'] ?? 0 );
    if ( $term_id <= 0 ) { continue; }
    $term = get_term( $term_id, 'pa_need' );
    if ( ! $term || is_wp_error( $term ) ) { continue; }

    $link = get_term_link( $term );
    if ( ! $link || is_wp_error( $link ) ) { continue; }

    $needs[] = array(
        'name' => $term->name,
        'url'  => (string) $link,
    );
}

if ( empty( $needs ) ) { return; }

$wrapper_attrs = function_exists( 'get_block_wrapper_attributes' )
    ? get_block_wrapper_attributes( array( 'class' => 'aieo-post-related-needs' ) )
    : 'class="aieo-post-related-needs"';

ob_start();
?>
<div <?php echo $wrapper_attrs; ?>>
    <?php if ( $heading !== '' ) : ?>
        <span class="aieo-post-related-needs__heading"><?php echo esc_html( $heading ); ?></span>
    <?php endif; ?>
    <ul class="aieo-post-related-needs__list" role="list">
        <?php foreach ( $needs as $n ) : ?>
            <li class="aieo-post-related-needs__item">
                <a class="aieo-post-related-needs__chip"
                   href="<?php echo esc_url( $n['url'] ); ?>"
                   aria-label="<?php echo esc_attr( sprintf(
                       
                       __( 'Δείτε προϊόντα για: %s', 'ai-eshop-optimizer' ),
                       $n['name']
                   ) ); ?>">
                    <?php echo esc_html( $n['name'] ); ?>
                </a>
            </li>
        <?php endforeach; ?>
    </ul>
</div>
<?php
echo ob_get_clean(); 
