<?php

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

$qo = get_queried_object();
if (!($qo instanceof \WP_Term) || $qo->taxonomy !== 'product_brand') { return ''; }
$brand_id = (int) $qo->term_id;

$show_cats          = !empty($attributes['showCategories']);
$show_articles      = !empty($attributes['showArticles']);
$show_other_brands  = !empty($attributes['showOtherBrands']);
$articles_limit     = isset($attributes['articlesLimit'])  ? max(1, min(8, (int) $attributes['articlesLimit'])) : 3;
$other_brands_limit = isset($attributes['otherBrandsLimit']) ? max(2, min(12, (int) $attributes['otherBrandsLimit'])) : 6;
$layout             = (isset($attributes['layout']) && $attributes['layout'] === 'vertical') ? 'vertical' : 'horizontal';

$cat_chips = array();
if ($show_cats) {
    $rels = AIEO_DMM_Term_Relations::for_term('product_brand', $brand_id, 'term', 'product_cat');
    foreach ($rels as $r) {
        $term = get_term((int) $r['id'], 'product_cat');
        if (!$term || is_wp_error($term)) { continue; }
        $link = get_term_link($term);
        if (is_wp_error($link)) { continue; }
        $cat_chips[] = array(
            'name' => (string) $term->name,
            'url'  => (string) $link,
        );
    }
}

$articles = array();
if ($show_articles) {
    $rels = AIEO_DMM_Term_Relations::for_term('product_brand', $brand_id, 'post', 'post');
    $i = 0;
    foreach ($rels as $r) {
        if ($i >= $articles_limit) { break; }
        $post_id = (int) $r['id'];
        $post    = get_post($post_id);
        if (!$post || $post->post_status !== 'publish') { continue; }
        $articles[] = array(
            'id'        => $post_id,
            'title'     => get_the_title($post_id),
            'permalink' => (string) get_permalink($post_id),
            'thumb'     => (string) get_the_post_thumbnail_url($post_id, 'medium'),
            'excerpt'   => wp_strip_all_tags((string) get_the_excerpt($post_id)),
        );
        $i++;
    }
}

$other_brands = array();
if ($show_other_brands && is_user_logged_in() && class_exists('AIEO_Customer_Intelligence_Query')) {
    $top_ids = AIEO_Customer_Intelligence_Query::get_top_brands(get_current_user_id(), $other_brands_limit + 1);
    $top_ids = array_values(array_filter($top_ids, function ($id) use ($brand_id) { return (int) $id !== $brand_id; }));
    if (!empty($top_ids)) {
        $other_brands = AIEO_Core_Brand_Vitals::instance()->get_by_ids(array_slice($top_ids, 0, $other_brands_limit));
    }
}

if (empty($cat_chips) && empty($articles) && empty($other_brands)) {
    return '';
}

$wrapper_attrs = function_exists('get_block_wrapper_attributes')
    ? get_block_wrapper_attributes(array('class' => 'aieo-brand-related aieo-brand-related--' . $layout))
    : 'class="aieo-brand-related aieo-brand-related--' . $layout . '"';

ob_start();
?>
<section <?php echo $wrapper_attrs; ?>>

    <?php if (!empty($cat_chips)) : ?>
        <div class="aieo-brand-related__row aieo-brand-related__row--cats">
            <h3 class="aieo-brand-related__heading"><?php esc_html_e('Shop by category', 'ai-eshop-optimizer'); ?></h3>
            <ul class="aieo-brand-related__chips" role="list">
                <?php foreach ($cat_chips as $c) : ?>
                    <li class="aieo-brand-related__chip">
                        <a href="<?php echo esc_url($c['url']); ?>"><?php echo esc_html($c['name']); ?></a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if (!empty($articles)) : ?>
        <div class="aieo-brand-related__row aieo-brand-related__row--articles">
            <h3 class="aieo-brand-related__heading"><?php esc_html_e('From the Blog', 'ai-eshop-optimizer'); ?></h3>
            <ul class="aieo-brand-related__articles" role="list">
                <?php foreach ($articles as $a) :
                    $bg_style = !empty($a['thumb'])
                        ? 'background-image:url(' . esc_url($a['thumb']) . ')'
                        : '';
                ?>
                    <li class="aieo-article-card<?php echo empty($a['thumb']) ? ' has-no-thumb' : ''; ?>">
                        <a class="aieo-article-card__link"
                           href="<?php echo esc_url($a['permalink']); ?>"
                           style="<?php echo esc_attr($bg_style); ?>">
                            <span class="aieo-article-card__overlay">
                                <span class="aieo-article-card__title"><?php echo esc_html($a['title']); ?></span>
                                <?php if (!empty($a['excerpt'])) : ?>
                                    <span class="aieo-article-card__excerpt"><?php echo esc_html(wp_trim_words($a['excerpt'], 14)); ?></span>
                                <?php endif; ?>
                            </span>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if (!empty($other_brands)) : ?>
        <div class="aieo-brand-related__row aieo-brand-related__row--other-brands">
            <h3 class="aieo-brand-related__heading"><?php esc_html_e('Other brands you love', 'ai-eshop-optimizer'); ?></h3>
            <ul class="aieo-brand-related__brand-strip" role="list">
                <?php foreach ($other_brands as $b) : ?>
                    <li class="aieo-brand-related__brand-card">
                        <a href="<?php echo esc_url((string) $b['permalink']); ?>">
                            <?php if (!empty($b['logo_url'])) : ?>
                                <span class="aieo-brand-related__brand-logo">
                                    <img loading="lazy" src="<?php echo esc_url((string) $b['logo_url']); ?>" alt="<?php echo esc_attr((string) $b['name']); ?>" />
                                </span>
                            <?php endif; ?>
                            <span class="aieo-brand-related__brand-name"><?php echo esc_html((string) $b['name']); ?></span>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

</section>
<?php
echo ob_get_clean(); 
