<?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('searchshifter_clean_single_glossary_schema');
    }
});

function searchshifter_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;
}


$searchshifter_license = class_exists( 'SS_Licensing' )
    ? SS_Licensing::get_cached_status()
    : array();

$searchshifter_plan = strtolower(
    $searchshifter_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();
    $searchshifter_definition = get_post_meta( $post_id, 'ss_definition', true );

    if (empty($searchshifter_definition)) {
        $searchshifter_raw_content = get_post_field( 'post_content', $post_id );
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core WordPress hook.
        $searchshifter_definition = apply_filters( 'the_content', $searchshifter_raw_content );
    }

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

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

    <?php if ($searchshifter_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($searchshifter_why_matters)); ?></p>
    <?php endif; ?>

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

    <?php if ($searchshifter_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($searchshifter_simple_example)); ?></p>
    <?php endif; ?>

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

    <?php if ($searchshifter_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($searchshifter_video_url)) : ?>
        <div class="ss-video-wrapper">
           <?php
                $video = get_post_meta($post_id, 'ss_video_url', true);

                if (!empty($video)) {

                    // Convert YouTube watch URL to embed
                    if (strpos($video, 'watch?v=') !== false) {
                        $video = str_replace('watch?v=', 'embed/', $video);
                    }

                    // Handle youtu.be short links
                    if (strpos($video, 'youtu.be/') !== false) {
                        $video_id = basename($video);
                        $video = 'https://www.youtube.com/embed/' . $video_id;
                    }
                ?>
                    <div class="ss-video-wrapper">
                        <iframe width="100%" height="360"
                            src="<?php echo esc_url($video); ?>"
                            frameborder="0"
                            allowfullscreen>
                        </iframe>
                    </div>
            <?php } ?>
        </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
    $searchshifter_related_terms = get_post_meta($post_id, 'ss_related_terms', true);
    $searchshifter_related_terms = is_array($searchshifter_related_terms) ? $searchshifter_related_terms : [];
    ?>

    <?php if ($searchshifter_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($searchshifter_related_terms)) : ?>
            <p class="ss-section-text">No related terms added.</p>
        <?php else : ?>
            <ul class="ss-related-list">
                <?php foreach ($searchshifter_related_terms as $id) :
                    if ($id == $post_id) continue;
                    if (!get_post_status($id)) continue;
                ?>
                    <li>
                            <a href="<?php echo esc_url( 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 ($searchshifter_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());
        $searchshifter_needle = preg_quote($term, '/');

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

        $searchshifter_matches = [];

        foreach ($searchshifter_pages as $searchshifter_page) {

            $searchshifter_content = strtolower(
                wp_strip_all_tags($searchshifter_page->post_content)
            );

            if (preg_match("/\b{$searchshifter_needle}\b/", $searchshifter_content)) {

                $searchshifter_matches[] = [
                    'id'    => $searchshifter_page->ID,
                    'title' => $searchshifter_page->post_title,
                    'url'   => get_permalink($searchshifter_page->ID)
                ];
            }
        }
    ?>

        <?php if (empty($searchshifter_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 ($searchshifter_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
$searchshifter_external_validation = get_post_meta(
    $post_id,
    'ss_external_validation',
    true
);

$searchshifter_external_validation_public = get_option(
    'ss_external_validation_public',
    'off'
); // on | off

if (!empty($searchshifter_external_validation)) {

    // CASE 1: Toggle OFF → Only Authority plan users can see
    if ($searchshifter_external_validation_public !== 'on' && $searchshifter_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($searchshifter_external_validation['label']) && !empty($searchshifter_external_validation['url'])) {
            echo "<p><strong>Source:</strong> 
                    <a href='".esc_url($searchshifter_external_validation['url'])."' target='_blank'>
                        ".esc_html($searchshifter_external_validation['label'])."
                    </a>
                </p>";
        }

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

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

$term = strtolower(get_the_title());

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

$searchshifter_density = 0;
$searchshifter_linked  = 0;
$searchshifter_has_qa  = 0;


foreach ($searchshifter_pages as $searchshifter_page ) {
    $searchshifter_content_raw = apply_filters(
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core WordPress hook.
        'the_content',
        $searchshifter_page->post_content
    );
    $searchshifter_content_text = strtolower(
        wp_strip_all_tags( $searchshifter_content_raw )
    );

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

        // Count where term appears
        $searchshifter_density++;

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

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

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

// ---- REINFORCEMENT SCORE ----
$searchshifter_reinforcement = min(
    100,
    ($searchshifter_density * 10) +    // content presence
    ($searchshifter_linked * 10)  +    // hyperlink presence
    ($searchshifter_has_qa ? 20 : 0) +
    ($searchshifter_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 esc_html( $searchshifter_density ); ?> pages where this term appears.
    </p>

    <p><strong>Internal Linking Coverage:</strong> 
       <?php echo esc_html( $searchshifter_linked ); ?> internal references detected.
    </p>

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

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

    <?php if ($searchshifter_plan === 'authority') : ?>
        <p><strong>Reinforcement Score (AI Reinforcement Rating):</strong>
            <span style="font-size:18px;font-weight:bold;">
                <?php echo esc_html( $searchshifter_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 esc_url( site_url('/glossary') ); ?>">
        ← Back to Glossary
    </a>


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

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


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

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

    $searchshifter_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" => $searchshifter_external_validation ? [
            "label" => $searchshifter_external_validation['label'] ?? '',
            "url"   => $searchshifter_external_validation['url'] ?? '',
            "notes" => $searchshifter_external_validation['notes'] ?? ''
        ] : null
    ];

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

endif; ?>


</div>

<?php get_footer(); ?>
