<?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_label = __( 'Σχετικές Κατηγορίες Προϊόντων', 'ai-eshop-optimizer' );
$label = isset( $attributes['label'] ) && trim( (string) $attributes['label'] ) !== ''
    ? trim( (string) $attributes['label'] )
    : $default_label;

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

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

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

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

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

ob_start();
?>
<div <?php echo $wrapper_attrs; ?>>
    <form class="aieo-post-related-categories__form"
          method="get"
          onchange="if(this.aieoCat.value){window.location.href=this.aieoCat.value;}">
        <select name="aieoCat"
                class="aieo-post-related-categories__select"
                aria-label="<?php echo esc_attr( $label ); ?>">
            <option value="" selected="selected"><?php echo esc_html( $label ); ?></option>
            <?php foreach ( $options as $opt ) : ?>
                <option value="<?php echo esc_url( $opt['url'] ); ?>">
                    <?php echo esc_html( $opt['name'] ); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </form>
</div>
<?php
echo ob_get_clean(); 
