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

/**
 * FORCE schema injection using output buffer
 */
add_action('template_redirect', function () {

    // Only glossary page
    $glossary_page_id = (int) get_option('ss_glossary_page_id');
    if ($glossary_page_id && !is_page($glossary_page_id)) return;

    ob_start(function ($html) {

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

        if (empty($terms)) return $html;

        $glossary_url = get_permalink(get_option('ss_glossary_page_id')) ?: get_permalink(get_option('ss_glossary_page_id'));

        $defined_terms = [];

        foreach ($terms as $t) {

            $defined_terms[] = [
                "@type" => "DefinedTerm",
                "@id"   => get_permalink($t->ID) . "#definedterm",
                "name"  => wp_strip_all_tags($t->post_title),
                "description" => wp_strip_all_tags(
                    get_post_meta($t->ID, 'ss_definition', true) ?: $t->post_content
                ),
                "url"   => get_permalink($t->ID),
                "inDefinedTermSet" => $glossary_url
            ];
        }

        $schema = [
            "@context" => "https://schema.org",
            "@graph" => array_merge(
                [[
                    "@type" => "DefinedTermSet",
                    "@id"   => $glossary_url,
                    "name"  => "Glossary",
                    "url"   => $glossary_url
                ]],
                $defined_terms
            )
        ];

        $json = wp_json_encode($schema, JSON_UNESCAPED_SLASHES);

        if (!$json) return $html;

        $script = '<script type="application/ld+json">' . $json . '</script>';

        // Inject BEFORE </head>
        if (strpos($html, '</head>') !== false) {
            $html = str_replace('</head>', $script . '</head>', $html);
        } else {
            $html .= $script;
        }

        return $html;
    });
}); 