<?php
/**
 * SearchShifter – Single Glossary Term Template (FIXED + CLEAN)
 */

if (!defined('ABSPATH')) exit;

// Start output buffer early
add_action('template_redirect', function () {
    if (is_singular('ss_glossary')) {
        ob_start('ss_clean_single_glossary_schema');
    }
});

function ss_clean_single_glossary_schema($html)
{
    // REMOVE YOAST ARTICLE SCHEMA
    $html = preg_replace(
        '/<script type="application\/ld\+json">.*?"@type"\s*:\s*"Article".*?<\/script>/s',
        '',
        $html
    );

    // REMOVE DUPLICATE DEFINEDTERMSET SCHEMA
    $html = preg_replace(
        '/<script type="application\/ld\+json">.*?"@type"\s*:\s*"DefinedTermSet".*?<\/script>/s',
        '',
        $html
    );

    return $html;
}

// Detect license plan
$license = class_exists('SS_Licensing') ? SS_Licensing::get_cached_status() : [];
$plan = strtolower($license['plan'] ?? 'free'); // free | pro | authority

get_header();
?>

<div class="ss-glossary-wrapper">

    <!-- Term Name -->
    <h1 class="ss-term-title"><?php echo esc_html(get_the_title()); ?></h1>

  
    <!-- Definition -->
    <?php
    $post_id = get_the_ID();
    $def = get_post_meta($post_id, 'ss_definition', true);

    if (empty($def)) {
        $raw = get_post_field('post_content', $post_id);
        $def = apply_filters('the_content', $raw);
    }

    if (!empty(trim($def))) :
    ?>
        <h2 class="ss-section-title">Definition</h2>
        <div class="ss-section-text"><?php echo $def; ?></div>
    <?php endif; ?>

    <!-- Why It Matters -->
    <h2 class="ss-section-title">Why It Matters</h2>
    <?php $why = get_post_meta($post_id, 'ss_why_matters', true); ?>

    <?php if ($plan === 'free') : ?>
        <div class="ss-locked" data-required-plan="pro">
            <div class="ss-locked-box">
                <span>Locked feature – available on Pro plan.</span>
                <a class="ss-upgrade-btn" href="https://searchshifter.ai/pricing/" target="_blank">Upgrade to Pro</a>
            </div>
        </div>
    <?php else : ?>
        <p class="ss-section-text"><?php echo nl2br(esc_html($why)); ?></p>
    <?php endif; ?>

    <!-- Simple Example -->
    <h2 class="ss-section-title">Simple Example</h2>
    <?php $example = get_post_meta($post_id, 'ss_simple_example', true); ?>

    <?php if ($plan === 'free') : ?>
        <div class="ss-locked" data-required-plan="pro">
            <div class="ss-locked-box">
                <span>Locked feature – available on Pro plan.</span>
                <a class="ss-upgrade-btn" href="https://searchshifter.ai/pricing/" target="_blank">Upgrade to Pro</a>
            </div>
        </div>
    <?php else : ?>
        <p class="ss-section-text"><?php echo nl2br(esc_html($example)); ?></p>
    <?php endif; ?>

    <!-- Video Explanation (Authority Only) -->
    <h2 class="ss-section-title">Watch the Deeper Explanation</h2>
    <?php $yt = get_post_meta($post_id, 'ss_video_url', true); ?>

    <?php if ($plan !== 'authority') : ?>
        <div class="ss-locked" data-required-plan="authority">
            <div class="ss-locked-box">
                <span>Unlocked in the Authority Plan.</span>
                <a class="ss-upgrade-btn" href="https://searchshifter.ai/pricing/" target="_blank">Upgrade to Authority</a>
            </div>
        </div>
    <?php elseif (!empty($yt)) : ?>
        <div class="ss-video-wrapper">
            <iframe width="100%" height="360" src="<?php echo esc_url($yt); ?>" frameborder="0" allowfullscreen></iframe>
        </div>
    <?php else : ?>
        <p class="ss-section-text">No video added.</p>
    <?php endif; ?>

    <!-- Related Terms -->
    <h2 class="ss-section-title">Related Terms</h2>
    <?php
    $related = get_post_meta($post_id, 'ss_related_terms', true);
    $related = is_array($related) ? $related : [];
    ?>

    <?php if ($plan === 'free') : ?>
        <div class="ss-locked" data-required-plan="pro">
            <div class="ss-locked-box">
                <span>This feature requires Pro plan.</span>
                <a class="ss-upgrade-btn" href="https://searchshifter.ai/pricing/" target="_blank">Upgrade</a>
            </div>
        </div>
    <?php else : ?>
        <?php if (empty($related)) : ?>
            <p class="ss-section-text">No related terms added.</p>
        <?php else : ?>
            <ul class="ss-related-list">
                <?php foreach ($related as $id) :
                    if ($id == $post_id) continue;
                    if (!get_post_status($id)) continue;
                ?>
                    <li>
                        <a href="<?php echo get_permalink($id); ?>">
                            <?php echo esc_html(get_the_title($id)); ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
    <?php endif; ?>

    <!-- ⭐ Where This Term Appears -->
    <h2 class="ss-section-title">Where This Term Appears</h2>

    <?php if ($plan !== 'authority') : ?>
        <div class="ss-locked" data-required-plan="authority">
            <div class="ss-locked-box">
                <span>Unlocked in the Authority Plan.</span>
                <a class="ss-upgrade-btn" href="https://searchshifter.ai/pricing/" target="_blank">Upgrade to Authority</a>
            </div>
        </div>
    <?php else :
        $term = strtolower(get_the_title());
        $needle = preg_quote($term, '/');

        $pages = get_posts([
            'post_type' => ['post', 'page'],
            'post_status' => 'publish',
            'posts_per_page' => -1
        ]);

        $matches = [];

        foreach ($pages as $p) {
            $content = strtolower(strip_tags($p->post_content));
            if (preg_match("/\b{$needle}\b/", $content)) {
                $matches[] = [
                    'id' => $p->ID,
                    'title' => $p->post_title,
                    'url' => get_permalink($p->ID)
                ];
            }
        }
    ?>

        <?php if (empty($matches)) : ?>
            <p class="ss-section-text">This term does not appear in any indexed content.</p>
        <?php else : ?>
            <ul class="ss-appears-list">
                <?php foreach ($matches as $m) : ?>
                    <li>
                        <a href="<?php echo esc_url($m['url']); ?>">
                            <?php echo esc_html($m['title']); ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
    <?php endif; ?>

 <!-- External Validation -->
<?php
$ext = get_post_meta($post_id, 'ss_external_validation', true);
$public_toggle = get_option('ss_external_validation_public', 'off'); // on | off

if (!empty($ext)) {

    // CASE 1: Toggle OFF → Only Authority plan users can see
    if ($public_toggle !== 'on' && $plan !== 'authority') {

        echo '<div class="ss-locked" data-required-plan="authority">
                <div class="ss-locked-box">
                    <span>External Validation is locked. Available only on Authority Plan.</span>
                    <a class="ss-upgrade-btn" href="https://searchshifter.ai/pricing/" target="_blank">Upgrade</a>
                </div>
              </div>';

    } else {

        // CASE 2: Toggle ON → Everyone can see the entry
        echo "<h2 class='ss-section-title'>External Validation</h2>";

        if (!empty($ext['label']) && !empty($ext['url'])) {
            echo "<p><strong>Source:</strong> 
                    <a href='".esc_url($ext['url'])."' target='_blank'>
                        ".esc_html($ext['label'])."
                    </a>
                </p>";
        }

        if (!empty($ext['notes'])) {
            echo "<p>".esc_html($ext['notes'])."</p>";
        }
    }
}
?>

<?php
// ------------------------------------------
// REINFORCEMENT-SCANNER STYLE CALCULATION
// ------------------------------------------

$term = strtolower(get_the_title());

// Match EXACTLY like scanner
$pages = get_posts([
    'post_type'      => ['post', 'page'],
    'post_status'    => 'publish',
    'posts_per_page' => -1
]);

$density = 0;
$linked  = 0;
$has_qa  = 0;

foreach ($pages as $p) {

    $content_raw  = apply_filters('the_content', $p->post_content);
    $content_text = strtolower(strip_tags($content_raw));

    // ---- EXACT SAME MATCH AS REINFORCEMENT SCANNER ----
    if (strpos($content_text, $term) !== false) {

        // Count where term appears
        $density++;

        // Count internal glossary links
        if (strpos($content_raw, 'ss-glossary-term') !== false) {
            $linked++;
        }

        // Detect FAQ/Q&A in same page
        if (
            stripos($content_raw, 'ss-qa') !== false ||
            stripos($content_raw, 'faq') !== false ||
            stripos($content_raw, 'Frequently Asked Questions') !== false
        ) {
            $has_qa = 1;
        }
    }
}

// Schema flag
$schema_flag = get_post_meta($post_id, '_ss_flag_add_schema', true) ? 1 : 0;

// ---- REINFORCEMENT SCORE ----
$reinforcement = min(
    100,
    ($density * 10) +    // content presence
    ($linked * 10)  +    // hyperlink presence
    ($has_qa ? 20 : 0) +
    ($schema_flag ? 10 : 0)
);
?>


    <!-- Glossary Intelligence Summary -->
  <h2 class="ss-section-title">Glossary Intelligence Summary</h2>

<div class="ss-glossary-metrics">

    <p><strong>Glossary Density:</strong> 
        <?php echo $density; ?> pages where this term appears.
    </p>

    <p><strong>Internal Linking Coverage:</strong> 
        <?php echo $linked; ?> internal references detected.
    </p>

    <p><strong>Q&A Presence:</strong> 
        <?php echo $has_qa ? 'Yes — appears in FAQ/Q&A content' : 'No'; ?>
    </p>

    <p><strong>Schema Eligible:</strong> 
        <?php echo $schema_flag ? 'Yes — Included in structured data output' : 'No'; ?>
    </p>

    <?php if ($plan === 'authority') : ?>
        <p><strong>Reinforcement Score (AI Reinforcement Rating):</strong>
            <span style="font-size:18px;font-weight:bold;">
                <?php echo $reinforcement; ?> / 100
            </span>
        </p>
    <?php else : ?>
        <div class="ss-locked" data-required-plan="authority">
            <div class="ss-locked-box" style="max-width:440px;">
                <span>Reinforcement scoring is an Authority-level feature.</span>
                <a class="ss-upgrade-btn" href="https://searchshifter.ai/pricing/" target="_blank">Upgrade to Authority</a>
            </div>
        </div>
    <?php endif; ?>

</div>


    <!-- Back Link -->
    <a class="ss-back-link" href="<?php echo site_url('/glossary'); ?>">← Back to Glossary</a>

<?php
$flag = get_post_meta(get_the_ID(), 'ss_plan_flag', true);

if ($flag === 'authority') {
    echo '<span class="ss-authority-badge">Authority Term</span>';
} elseif ($flag === 'pro') {
    echo '<span class="ss-pro-badge">Pro Term</span>';
}
?>


    <!-- Structured Data (Authority Only) -->
<?php if ($plan === 'authority') :

    $ext = get_post_meta($post_id, 'ss_external_validation', true);

    $schema_extra = [
        "@context" => "https://schema.org",
        "@type"    => "DefinedTerm",
        "name"     => get_the_title(),
        "url"      => get_permalink(),
        "authoritySignals" => [
            "reinforcementScore" => intval(get_post_meta($post_id, '_ss_reinforcement_score', true)),
            "linkedPages"        => intval(get_post_meta($post_id, '_ss_internal_link_coverage', true)),
            "glossaryDensity"    => intval(get_post_meta($post_id, '_ss_glossary_density', true)),
            "hasFAQ"             => boolval(get_post_meta($post_id, '_ss_has_qa', true)),
        ],
        "brandingReinforced" => true,
        "multimodalSignals"  => true,
        "externalValidation" => $ext ? [
            "label" => $ext['label'] ?? '',
            "url"   => $ext['url'] ?? '',
            "notes" => $ext['notes'] ?? ''
        ] : null
    ];

    echo '<script type="application/ld+json">' . json_encode($schema_extra) . '</script>';

endif; ?>


</div>

<?php get_footer(); ?>
