<?php
if ( ! defined( 'ABSPATH' ) ) exit;

get_header(); 
?>

<div class="container" style="padding:40px 0; max-width:800px; margin:auto;">

    <h1><?php the_title(); ?></h1>

    <p style="color:#777;">
        Last updated: <?php echo get_the_date(); ?>
    </p>

    <hr>

    <div style="margin-top:20px; font-size:16px; line-height:1.6;">
        <?php

            $answer = get_post_meta(get_the_ID(), '_ss_qa_answer', true);

            // Load glossary terms
            $glossary = get_posts([
                'post_type' => 'ss_glossary',
                'posts_per_page' => -1,
                'post_status' => 'publish'
            ]);

            if ($glossary) {

                foreach ($glossary as $term) {

                    $title = trim($term->post_title);
                    $url   = get_permalink($term->ID);

                    // Skip empty terms
                    if (!$title) {
                        continue;
                    }

                    // Replace ONLY plain text occurrences
                    $pattern = '/(?![^<]*>)(\b' . preg_quote($title, '/') . '\b)(?![^<]*<)/i';

                    $replacement = '<a href="' . esc_url($url) . '">$1</a>';

                    // Replace only first occurrence
                    $answer = preg_replace($pattern, $replacement, $answer, 1);
                }
            }

            echo wp_kses_post(wpautop($answer));

        ?>
    </div>

</div>

<?php get_footer(); ?>