<?php
/**
 * Render fonksiyonları
 * 
 * @package Kanews
 * @developer Kan Themes
 * @version 7.0
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * İlgili yazılar bloğunu render et
 * 
 * @param array $attributes Blok özellikleri
 * @return string HTML çıktısı
 */
function kanews_render_related_posts($attributes) {
    if (empty($attributes['selectedPosts']) || !is_array($attributes['selectedPosts'])) {
        return '';
    }

    $post_ids = $attributes['selectedPosts'];
    $posts = get_posts([
        'post__in' => $post_ids,
        'post_type' => 'post',
        'orderby' => 'post__in',
        'posts_per_page' => 1
    ]);

    if (empty($posts)) {
        return '';
    }

    $heading_tag = !empty($attributes['headingTag']) ? $attributes['headingTag'] : 'h4';
    $title = !empty($attributes['title']) ? $attributes['title'] : __('İlgili Yazılar', 'kanews');
    $show_title = isset($attributes['showTitle']) ? $attributes['showTitle'] : true;
    $thumbnail = 'kanews-post-1';
    $detail_text = !empty($attributes['detailText']) ? $attributes['detailText'] : __('Haberi görüntüle', 'kanews');
    $show_detail_text = isset($attributes['showDetailText']) ? $attributes['showDetailText'] : true;
    
    // Görünürlük sınıflarını ekle
    $visibility_classes = '';
    if (!empty($attributes['visibility'])) {
        if ($attributes['visibility']['desktop'] === true) {
            $visibility_classes .= ' hidden-desktop';
        }
        if ($attributes['visibility']['tablet'] === true) {
            $visibility_classes .= ' hidden-tablet';
        }
        if ($attributes['visibility']['mobile'] === true) {
            $visibility_classes .= ' hidden-mobile';
        }
    }
    
    $background_color = !empty($attributes['backgroundColor']) ? $attributes['backgroundColor'] : '';
    $background_typography = !empty($attributes['backgroundColorTypography']) ? $attributes['backgroundColorTypography'] : [];
    $background_style = $background_color ? ' style="background-color: ' . esc_attr($background_color) . ';' . kanews_get_typography_styles($background_typography) . '"' : '';
    
    // Tipografi stilleri
    $title_typography = !empty($attributes['titleTypography']) ? $attributes['titleTypography'] : [];    
    $title_style = kanews_get_typography_styles($title_typography, true);
    
    ob_start();
    ?>
    <div class="wp-block-kanews-related-posts<?php echo esc_attr($visibility_classes); ?>">
        <div class="kanews-post-shortcode">
            <?php if ($show_title) : ?>
                <div class="kanews-post-shortcode-title">
                    <i class="icon-bolt"></i>
                    <span><?php echo esc_html($title); ?></span>
                </div>
            <?php endif; ?>
            <?php foreach ($posts as $post) : 
                setup_postdata($post);
                $default = kanews_get_option('default-thumbnail') ? kanews_get_option('default-thumbnail') : '';
                if (has_post_thumbnail() ) {
                  $image_id = get_post_thumbnail_id($post->ID);  
                  $image_url = wp_get_attachment_image_src($image_id, $thumbnail);  
                  $image_url = isset($image_url[0]) ? $image_url[0] : ''; 
                } elseif($default != '') {
                  $image_url = wp_get_attachment_image_src($default['id'], $thumbnail);  
                  $image_url = isset($image_url[0]) ? $image_url[0] : '';  
                }
                echo '<div class="mt-1 kanews-post-item d-flex flex-wrap"'.$background_style.'>';
                  echo '<a href="' . esc_url(get_permalink($post->ID)) . '" class="kanews-post-href" aria-label="'.get_the_title($post->ID).'"></a>';
                  if( $image_url != '' ) {
                    echo '<div class="kanews-post-thumb">';
                      echo '<img alt="thumbnail" loading="lazy" height="90" width="215" src="'.esc_url($image_url).'" />';
                    echo '</div>';
                  }
                  echo '<div class="kanews-post-content">';
                    echo '<'.$heading_tag.' class="kanews-post-headline truncate truncate-2" style="'.esc_attr($title_style).'">' . get_the_title($post->ID) . '</'.$heading_tag.'>';
                    if ($show_detail_text) {
                        echo '<span>'.esc_html($detail_text).' <i class="icon-arrow-long icon-180deg"></i> </span>';
                    }
                  echo '</div>';
                echo '</div>'; ?>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
    wp_reset_postdata();
    return ob_get_clean();
}

/**
 * Calculator bloğunu render et
 * 
 * @param array $attributes Blok özellikleri
 * @return string HTML çıktısı
 */
function kanews_render_calculator($attributes) {
    // Kısa kod parametreleriyle uyumlu olması için parametre isimlerini kontrol et
    $type = !empty($attributes['type']) ? $attributes['type'] : (!empty($attributes['tur']) ? $attributes['tur'] : 'doviz');
    $show_tabs = isset($attributes['showTabs']) ? $attributes['showTabs'] : (isset($attributes['show_tabs']) ? ($attributes['show_tabs'] === 'true' || $attributes['show_tabs'] === '1') : true);
    
    // Hariç tutulacak tipleri kontrol et
    $excluded_types = [];
    if (!empty($attributes['excludedTypes'])) {
        $excluded_types = $attributes['excludedTypes'];
    } elseif (!empty($attributes['exclude_types'])) {
        $excluded_types = explode(',', $attributes['exclude_types']);
        $excluded_types = array_map('trim', $excluded_types);
    }
    
    // Görünürlük sınıflarını ekle
    $visibility_classes = '';
    if (!empty($attributes['visibility'])) {
        if ($attributes['visibility']['desktop'] === true) {
            $visibility_classes .= ' hidden-desktop';
        }
        if ($attributes['visibility']['tablet'] === true) {
            $visibility_classes .= ' hidden-tablet';
        }
        if ($attributes['visibility']['mobile'] === true) {
            $visibility_classes .= ' hidden-mobile';
        }
    }

    ob_start();
    ?>
    <div class="wp-block-kanews-calculator<?php echo esc_attr($visibility_classes); ?>">
        <div class="kanews-calculator-wrapper">

            <div class="kanews-calculator-content">
                <?php echo do_shortcode('[kanews-calculator tur="'.$type.'" show_tabs="'.$show_tabs.'" exclude_types="'.implode(',', $excluded_types).'"]');
                ?>
            </div>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * DOMDocument sınıfına getElementsByClassName metodu ekle
 */
if (!function_exists('dom_get_elements_by_class_name')) {
    function dom_get_elements_by_class_name($dom, $class_name) {
        $elements = [];
        
        // Eğer $dom bir DOMElement ise, ownerDocument'ı al
        if ($dom instanceof DOMElement) {
            $dom = $dom->ownerDocument;
        }
        
        // Eğer hala DOMDocument değilse, işlemi sonlandır
        if (!($dom instanceof DOMDocument)) {
            return $elements;
        }
        
        $xpath = new DOMXPath($dom);
        $nodes = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class_name ')]");
        
        foreach ($nodes as $node) {
            $elements[] = $node;
        }
        
        return $elements;
    }
}

/**
 * SSS bloğunu render et
 * 
 * @param array $attributes Blok özellikleri
 * @param string $content Blok içeriği
 * @return string HTML çıktısı
 */
function kanews_render_faq($attributes, $content) {
    // Görünürlük sınıflarını ekle
    $visibility_classes = '';
    if (!empty($attributes['visibility'])) {
        if ($attributes['visibility']['desktop'] === true) {
            $visibility_classes .= ' hidden-desktop';
        }
        if ($attributes['visibility']['tablet'] === true) {
            $visibility_classes .= ' hidden-tablet';
        }
        if ($attributes['visibility']['mobile'] === true) {
            $visibility_classes .= ' hidden-mobile';
        }
    }
    
    // Schema desteği
    $enable_schema = isset($attributes['enableSchema']) ? $attributes['enableSchema'] : true;
    
    // Schema markup için soru-cevap çiftlerini topla
    $schema_items = [];
    if ($enable_schema) {
        // Regex kullanarak soru ve cevapları çıkar
        preg_match_all('/<h3[^>]*class="[^"]*collapse-item-header-title[^"]*"[^>]*>(.*?)<\/h3>/s', $content, $questions);
        preg_match_all('/<div[^>]*class="[^"]*collapse-item-body-content[^"]*"[^>]*>(.*?)<\/div>/s', $content, $answers);
        
        // Soru ve cevapları eşleştir
        $count = min(count($questions[1]), count($answers[1]));
        for ($i = 0; $i < $count; $i++) {
            $question = strip_tags($questions[1][$i]);
            $answer = strip_tags($answers[1][$i]);
            
            if (!empty($question) && !empty($answer)) {
                $schema_items[] = [
                    '@type' => 'Question',
                    'name' => $question,
                    'acceptedAnswer' => [
                        '@type' => 'Answer',
                        'text' => $answer
                    ]
                ];
            }
        }
    }
    
    // Schema markup oluştur
    $schema_markup = '';
    if ($enable_schema && !empty($schema_items)) {
        $schema_data = [
            '@context' => 'https://schema.org',
            '@type' => 'FAQPage',
            'mainEntity' => $schema_items
        ];
        
        $schema_markup = '<script type="application/ld+json">' . json_encode($schema_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . '</script>';
    }
    
    // Çıktıyı oluştur
    $output = '<div class="wp-block-kanews-faq' . esc_attr($visibility_classes) . '">';
    $output .= $content;
    if ($enable_schema) {
        $output .= $schema_markup;
    }
    $output .= '</div>';
    
    return $output;
}

function kanews_render_table_of_contents($attributes, $content) {
    // Extract attributes with safe defaults
    $title = isset($attributes['title']) ? $attributes['title'] : __('İçindekiler', 'kanews');
    $showTitle = isset($attributes['showTitle']) ? (bool)$attributes['showTitle'] : true;
    $showNumbers = isset($attributes['showNumbers']) ? (bool)$attributes['showNumbers'] : true;
    $isAccordion = isset($attributes['isAccordion']) ? (bool)$attributes['isAccordion'] : false;
    $headingLevels = isset($attributes['headingLevels']) && is_array($attributes['headingLevels']) ? $attributes['headingLevels'] : ['h2', 'h3', 'h4'];
    $maxDepth = isset($attributes['maxDepth']) ? (int)$attributes['maxDepth'] : 3;
    
    // Style attributes
    $backgroundColor = isset($attributes['backgroundColor']) ? $attributes['backgroundColor'] : '';
    $titleColor = isset($attributes['titleColor']) ? $attributes['titleColor'] : '';
    $linkColor = isset($attributes['linkColor']) ? $attributes['linkColor'] : '';
    $linkHoverColor = isset($attributes['linkHoverColor']) ? $attributes['linkHoverColor'] : '';
    
    // Margin and Padding
    $margin = isset($attributes['margin']) ? $attributes['margin'] : [];
    $padding = isset($attributes['padding']) ? $attributes['padding'] : [];
    
    // Border
    $border = isset($attributes['border']) ? $attributes['border'] : [];
    
    // Typography attributes
    $titleTypography = isset($attributes['titleTypography']) ? $attributes['titleTypography'] : [
        'fontSize' => '',
        'lineHeight' => '',
        'fontWeight' => '',
        'fontFamily' => '',
        'textTransform' => '',
        'letterSpacing' => ''
    ];
    
    $linkTypography = isset($attributes['linkTypography']) ? $attributes['linkTypography'] : [
        'fontSize' => '',
        'lineHeight' => '',
        'fontWeight' => '',
        'fontFamily' => '',
        'textTransform' => '',
        'letterSpacing' => ''
    ];
    
    // Get post content
    global $post;
    $content = $post->post_content;
    
    // Initialize variables
    $headings = [];
    $depthMap = [];
    
    // Store heading IDs for later use
    global $kanews_heading_ids;
    $kanews_heading_ids = [];

    // Extract headings from raw content using regex
    $pattern = '/<h([1-6])[^>]*>(.*?)<\/h\1>/i';
    preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);
    
    foreach ($matches as $index => $match) {
        $level = (int)$match[1];
        $text = strip_tags($match[2]);
        
        // Skip empty headings
        if (empty(trim($text))) {
            continue;
        }
        
        // Generate ID
        $id = 'heading-' . ($index + 1);
        
        // Check if heading already has an ID
        $fullMatch = $match[0];
        if (preg_match('/id=["\']([^"\']+)["\']/', $fullMatch, $idMatch)) {
            $id = $idMatch[1];
        }
        
        // Store the heading ID for later use
        $kanews_heading_ids[] = [
            'match' => $fullMatch,
            'id' => $id
        ];
        
        // Store heading
        $headings[] = [
            'level' => $level,
            'text' => $text,
            'id' => $id
        ];
        
        // Update maps
        $depthMap[$id] = 0;
    }

    // Filter headings based on selected levels and max depth
    $filteredHeadings = array_filter($headings, function($heading) use ($headingLevels, $maxDepth) {
        return in_array('h' . $heading['level'], $headingLevels) && $heading['level'] <= $maxDepth;
    });

    // Generate TOC HTML
    $tocHtml = '';
    if (!empty($filteredHeadings)) {
        // Sort headings by their position in the content
        usort($filteredHeadings, function($a, $b) use ($content) {
            $posA = strpos($content, $a['text']);
            $posB = strpos($content, $b['text']);
            return $posA - $posB;
        });
        
        // Group headings by their level
        $groupedHeadings = [];
        $currentGroup = null;
        $currentLevel = null;
        
        foreach ($filteredHeadings as $heading) {
            $level = $heading['level'];
            
            if ($currentLevel === null || $level <= $currentLevel) {
                // Start a new group
                $currentGroup = $heading['id'];
                $currentLevel = $level;
                $groupedHeadings[$currentGroup] = [
                    'main' => $heading,
                    'subheadings' => []
                ];
            } else {
                // Add to current group's subheadings
                $groupedHeadings[$currentGroup]['subheadings'][] = $heading;
            }
        }
        
        // Generate TOC HTML
        $tocHtml .= '<ul class="toc-list">';
        foreach ($groupedHeadings as $groupId => $group) {
            $mainHeading = $group['main'];
            $subheadings = $group['subheadings'];
            
            // Only show numbers for non-H1 headings
            $number = $showNumbers ? '<span class="toc-number"></span>' : '';
            $tocHtml .= sprintf(
                '<li class="toc-item toc-level-%d">
                    <a href="#%s" class="toc-link toc-main-link">%s%s</a>',
                $mainHeading['level'],
                $mainHeading['id'],
                $number,
                $mainHeading['text']
            );
            
            // Add subheadings if any
            if (!empty($subheadings)) {
                $tocHtml .= '<ul class="toc-subheadings">';
                foreach ($subheadings as $subheading) {
                    $subNumber = $showNumbers ? '<span class="toc-number"></span>' : '';
                    $indent = str_repeat(' ', $subheading['level'] - $mainHeading['level']);
                    $tocHtml .= sprintf(
                        '<li class="toc-item toc-level-%d"><a href="#%s" class="toc-link">%s%s%s</a></li>',
                        $subheading['level'],
                        $subheading['id'],
                        $indent,
                        $subNumber,
                        $subheading['text']
                    );
                }
                $tocHtml .= '</ul>';
            }
            
            $tocHtml .= '</li>';
        }
        $tocHtml .= '</ul>';
    } else {
        $tocHtml = '<div class="toc-empty">' . __('İçindekiler tablosu için başlık bulunamadı.', 'kanews') . '</div>';
    }

    // Build wrapper classes
    $wrapperClasses = ['wp-block-kanews-table-of-contents', 'kanews-toc-wrapper'];
    
    // Add is-number class if showNumbers is true
    if ($showNumbers) {
        $wrapperClasses[] = 'is-number';
    }
    
    // Add visibility classes
    if (!empty($attributes['visibility'])) {
        if ($attributes['visibility']['desktop'] === true) {
            $wrapperClasses[]= ' hidden-desktop';
        }
        if ($attributes['visibility']['tablet'] === true) {
            $wrapperClasses[]= ' hidden-tablet';
        }
        if ($attributes['visibility']['mobile'] === true) {
            $wrapperClasses[]= ' hidden-mobile';
        }
    }
    
    // Generate unique ID
    $uniqueId = 'toc-' . uniqid();
    $wrapperClasses[] = $uniqueId;

    // Add a filter to modify the content when it's displayed
    add_filter('the_content', 'kanews_add_heading_ids', 20);
    
    // Generate inline styles
    $titleStyles = kanews_get_typography_styles($titleTypography);
    $linkStyles = kanews_get_typography_styles($linkTypography, true);
    
    // Build inline styles with conditional properties
    $inlineStyles = ".{$uniqueId} {";
    
    if ($backgroundColor !== '') {
        $inlineStyles .= "--kan-placeholder-bg: {$backgroundColor};";
    }
    
    // Add margin styles
    if (!empty($margin['desktop'])) {
        $m = $margin['desktop'];
        $inlineStyles .= "margin: {$m['top']}px {$m['right']}px {$m['bottom']}px {$m['left']}px;";
    }
    
    // Add padding styles
    if (!empty($padding['desktop'])) {
        $p = $padding['desktop'];
        $inlineStyles .= "padding: {$p['top']}px {$p['right']}px {$p['bottom']}px {$p['left']}px;";
    }
    
    // Add border styles
    if (!empty($border['desktop'])) {
        $b = $border['desktop'];
        if (isset($b['style']) && $b['style'] !== 'none') {
            $inlineStyles .= "border-style: {$b['style']};";
            if (!empty($b['width'])) {
                $w = $b['width'];
                $inlineStyles .= "border-width: {$w['top']}px {$w['right']}px {$w['bottom']}px {$w['left']}px;";
            }
            if (!empty($b['color'])) {
                $inlineStyles .= "border-color: {$b['color']};";
            }
            if (!empty($b['radius'])) {
                $r = $b['radius'];
                $inlineStyles .= "border-radius: {$r['topLeft']}px {$r['topRight']}px {$r['bottomRight']}px {$r['bottomLeft']}px;";
            }
        }
    }
    
    $inlineStyles .= "}";
    
    // Add responsive styles
    if (!empty($margin['tablet']) || !empty($padding['tablet']) || !empty($border['tablet'])) {
        $inlineStyles .= "@media (max-width: 1024px) {";
        $inlineStyles .= ".{$uniqueId} {";
        
        if (!empty($margin['tablet'])) {
            $m = $margin['tablet'];
            $inlineStyles .= "margin: {$m['top']}px {$m['right']}px {$m['bottom']}px {$m['left']}px;";
        }
        
        if (!empty($padding['tablet'])) {
            $p = $padding['tablet'];
            $inlineStyles .= "padding: {$p['top']}px {$p['right']}px {$p['bottom']}px {$p['left']}px;";
        }
        
        if (!empty($border['tablet'])) {
            $b = $border['tablet'];
            if (isset($b['style']) && $b['style'] !== 'none') {
                $inlineStyles .= "border-style: {$b['style']};";
                if (!empty($b['width'])) {
                    $w = $b['width'];
                    $inlineStyles .= "border-width: {$w['top']}px {$w['right']}px {$w['bottom']}px {$w['left']}px;";
                }
                if (!empty($b['color'])) {
                    $inlineStyles .= "border-color: {$b['color']};";
                }
                if (!empty($b['radius'])) {
                    $r = $b['radius'];
                    $inlineStyles .= "border-radius: {$r['topLeft']}px {$r['topRight']}px {$r['bottomRight']}px {$r['bottomLeft']}px;";
                }
            }
        }
        
        $inlineStyles .= "}";
        $inlineStyles .= "}";
    }
    
    if (!empty($margin['mobile']) || !empty($padding['mobile']) || !empty($border['mobile'])) {
        $inlineStyles .= "@media (max-width: 767px) {";
        $inlineStyles .= ".{$uniqueId} {";
        
        if (!empty($margin['mobile'])) {
            $m = $margin['mobile'];
            $inlineStyles .= "margin: {$m['top']}px {$m['right']}px {$m['bottom']}px {$m['left']}px;";
        }
        
        if (!empty($padding['mobile'])) {
            $p = $padding['mobile'];
            $inlineStyles .= "padding: {$p['top']}px {$p['right']}px {$p['bottom']}px {$p['left']}px;";
        }
        
        if (!empty($border['mobile'])) {
            $b = $border['mobile'];
            if (isset($b['style']) && $b['style'] !== 'none') {
                $inlineStyles .= "border-style: {$b['style']};";
                if (!empty($b['width'])) {
                    $w = $b['width'];
                    $inlineStyles .= "border-width: {$w['top']}px {$w['right']}px {$w['bottom']}px {$w['left']}px;";
                }
                if (!empty($b['color'])) {
                    $inlineStyles .= "border-color: {$b['color']};";
                }
                if (!empty($b['radius'])) {
                    $r = $b['radius'];
                    $inlineStyles .= "border-radius: {$r['topLeft']}px {$r['topRight']}px {$r['bottomRight']}px {$r['bottomLeft']}px;";
                }
            }
        }
        
        $inlineStyles .= "}";
        $inlineStyles .= "}";
    }
    
    // Add title styles if not empty
    if ($titleColor !== '' || $titleStyles !== '') {
        $inlineStyles .= ".{$uniqueId} .toc-title {";
        if ($titleColor !== '') {
            $inlineStyles .= "color: {$titleColor};";
        }
        if ($titleStyles !== '') {
            $inlineStyles .= $titleStyles;
        }
        $inlineStyles .= "}";
    }
    
    // Add link styles if not empty
    if ($linkColor !== '' || $linkStyles !== '') {
        $inlineStyles .= ".{$uniqueId} .toc-link {";
        if ($linkColor !== '') {
            $inlineStyles .= "color: {$linkColor};";
        }
        if ($linkStyles !== '') {
            $inlineStyles .= $linkStyles;
        }
        $inlineStyles .= "}";
    }
    
    // Add link hover styles if not empty
    if ($linkHoverColor !== '') {
        $inlineStyles .= ".{$uniqueId} {--kan-theme-color: {$linkHoverColor};}";
    }
    
    // Add accordion styles if not empty
    if ($titleColor !== '' || $titleStyles !== '') {
        $inlineStyles .= ".{$uniqueId} .toc-title {";
        if ($titleColor !== '') {
            $inlineStyles .= "color: {$titleColor};";
        }
        if ($titleStyles !== '') {
            $inlineStyles .= $titleStyles;
        }
        $inlineStyles .= "}";
    }
    
    if ($linkColor !== '' || $linkStyles !== '') {
        $inlineStyles .= ".{$uniqueId} .toc-link {";
        if ($linkColor !== '') {
            $inlineStyles .= "color: {$linkColor};";
        }
        if ($linkStyles !== '') {
            $inlineStyles .= $linkStyles;
        }
        $inlineStyles .= "}";
    }
    
    if ($linkHoverColor !== '') {
        $inlineStyles .= ".{$uniqueId} .toc-link:hover {color: {$linkHoverColor};}";
    }
    
    // Return HTML
    if ($isAccordion) {
        return sprintf(
            '<div class="%s">
                <style>%s</style>
                <div class="kanews-toc-container">
                    <div class="toc-accordion">
                        <div class="toc-accordion-item">
                            <input type="checkbox" id="toc-title-check" class="toc-checkbox">
                            <label for="toc-title-check" class="toc-accordion-label">
                                <span class="toc-accordion-text">%s</span>
                                <span class="toc-accordion-icon"></span>
                            </label>
                            <div class="toc-accordion-content">
                                <div class="toc-container">
                                    %s
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>',
            esc_attr(implode(' ', $wrapperClasses)),
            $inlineStyles,
            $showTitle ? esc_html($title) : '',
            $tocHtml
        );
    } else {
        return sprintf(
            '<div class="%s">
                <style>%s</style>
                <div class="kanews-toc-container">
                    %s
                    <div class="toc-container">
                        %s
                    </div>
                </div>
            </div>',
            esc_attr(implode(' ', $wrapperClasses)),
            $inlineStyles,
            $showTitle ? sprintf('<h2 class="toc-title">%s</h2>', esc_html($title)) : '',
            $tocHtml
        );
    }
}

/**
 * Add IDs to headings in the post content
 * 
 * @param string $content The post content
 * @return string Modified content with heading IDs
 */
function kanews_add_heading_ids($content) {
    // Only process the content once
    static $processed = false;
    if ($processed) {
        return $content;
    }
    $processed = true;
    
    // Get the heading IDs from the global variable
    global $kanews_heading_ids;
    
    if (!empty($kanews_heading_ids)) {
        // Replace each heading with its ID version
        foreach ($kanews_heading_ids as $heading) {
            $fullMatch = $heading['match'];
            $id = $heading['id'];
            
            // Skip if heading already has an ID
            if (preg_match('/id=["\']([^"\']+)["\']/', $fullMatch)) {
                continue;
            }
            
            // Add ID to the heading
            $newHeading = preg_replace('/<h([1-6])([^>]*)>/', '<h$1$2 id="' . $id . '">', $fullMatch);
            $content = str_replace($fullMatch, $newHeading, $content);
        }
    } else {
        // Fallback if no heading IDs were stored
        $pattern = '/<h([1-6])[^>]*>(.*?)<\/h\1>/i';
        preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);
        
        $index = 1;
        foreach ($matches as $match) {
            $fullMatch = $match[0];
            
            // Skip if heading already has an ID
            if (preg_match('/id=["\']([^"\']+)["\']/', $fullMatch)) {
                continue;
            }
            
            // Add ID to the heading
            $id = 'heading-' . $index;
            $newHeading = preg_replace('/<h([1-6])([^>]*)>/', '<h$1$2 id="' . $id . '">', $fullMatch);
            $content = str_replace($fullMatch, $newHeading, $content);
            
            $index++;
        }
    }
    
    return $content;
}
