<?php

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

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

$show_history     = !empty($attributes['showHistory']);
$show_ambassadors = !empty($attributes['showAmbassadors']);
$show_website     = !empty($attributes['showWebsite']);
$show_footer      = !empty($attributes['showFooter']);

$extras = AIEO_DMM_Brand_Extras_Data::get('product_brand', (int) $qo->term_id);

$sections = array();
if ($show_history     && !empty($extras['history_text']))     { $sections[] = array('label' => __('About the Brand', 'ai-eshop-optimizer'), 'html' => (string) $extras['history_text']); }
if ($show_ambassadors && !empty($extras['ambassadors_text'])) { $sections[] = array('label' => __('Ambassadors', 'ai-eshop-optimizer'), 'html' => (string) $extras['ambassadors_text']); }

$website_url = $show_website ? trim((string) ($extras['website_url'] ?? '')) : '';
if ($website_url !== '' && filter_var($website_url, FILTER_VALIDATE_URL) === false) {
    
    if (!preg_match('#^https?://#i', $website_url)) {
        $website_url = 'https://' . ltrim($website_url, '/');
    }
}

$has_website = $show_website && $website_url !== '';
$has_footer  = $show_footer  && !empty($extras['footer_text']);

if (empty($sections) && !$has_website && !$has_footer) {
    return '';
}

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

ob_start();
?>
<section <?php echo $wrapper_attrs; ?>>
    <?php foreach ($sections as $section) : ?>
        <div class="aieo-brand-story__section">
            <h2 class="aieo-brand-story__heading"><?php echo esc_html($section['label']); ?></h2>
            <div class="aieo-brand-story__body">
                <?php
                
                echo wp_kses_post($section['html']);
                ?>
            </div>
        </div>
    <?php endforeach; ?>

    <?php if ($has_website) : ?>
        <div class="aieo-brand-story__section aieo-brand-story__website">
            <a class="aieo-brand-story__website-link"
               href="<?php echo esc_url($website_url); ?>"
               target="_blank"
               rel="noopener noreferrer">
                <?php
                printf(
                    
                    esc_html__('Visit %s ↗', 'ai-eshop-optimizer'),
                    esc_html((string) wp_parse_url($website_url, PHP_URL_HOST))
                );
                ?>
            </a>
        </div>
    <?php endif; ?>

    <?php if ($has_footer) : ?>
        <div class="aieo-brand-story__footer">
            <?php echo wp_kses_post((string) $extras['footer_text']); ?>
        </div>
    <?php endif; ?>
</section>
<?php
echo ob_get_clean(); 
