<?php
/**
 * Inject FAQ Schema (Authority Graph) into <head>
 * Dynamic per-site version for SearchShifter™
 */

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

/**
 * ORIGINAL: searchshifter_get_faq_schema_for_post()
 * (Kept exactly as you had it)
 */
if (! function_exists('searchshifter_get_faq_schema_for_post')) {
    function searchshifter_get_faq_schema_for_post($post_id) {

        if (!$post_id) return null;

        $content = apply_filters(
            // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core WordPress hook.
            'the_content',
            get_post_field( 'post_content', $post_id )
        );


        if (empty($content)) return null;

        $entities = [];

        // Match Q:/A: pairs anywhere in content
        if (preg_match_all(
            '/<p[^>]*>\s*<strong>Q:\s*<\/strong>(.*?)<\/p>\s*<p[^>]*>\s*<strong>A:\s*<\/strong>(.*?)<\/p>/si',
            $content,
            $matches,
            PREG_SET_ORDER
        )) {
            foreach ($matches as $m) {
                $entities[] = [
                    "@type" => "Question",
                    "name"  => wp_strip_all_tags($m[1]),
                    "acceptedAnswer" => [
                        "@type" => "Answer",
                        "text" => wp_strip_all_tags($m[2])
                    ]
                ];
            }
        }

        if (empty($entities)) {
            return null;
        }

        return [
            "@type" => "FAQPage",
            "mainEntity" => $entities
        ];
    }
}

/**
 * ORIGINAL: searchshifter_extract_faq_from_html()
 * (Kept exactly as you had it)
 */
if (! function_exists('searchshifter_extract_faq_from_html')) {
    function searchshifter_extract_faq_from_html( $html ) {
        $entities = [];

        libxml_use_internal_errors(true);
        $dom = new DOMDocument();

        // Ensure proper encoding
        $loaded = $dom->loadHTML('<?xml encoding="utf-8" ?>' . $html, LIBXML_NOWARNING | LIBXML_NOERROR);
        if (!$loaded) {
            libxml_clear_errors();
            return [];
        }

        $xpath = new DOMXPath($dom);

        // Look for ss-qa containers
        $nodes = $xpath->query('//*[contains(concat(" ", normalize-space(@class), " "), " ss-qa ")]');

        if ($nodes->length === 0) {

            $p_nodes = $xpath->query('//p');
            $pairs = [];
            $current_q = null;

            foreach ($p_nodes as $p) {
                $txt = trim( preg_replace('/\s+/', ' ', $p->textContent) );
                if ( stripos($txt, 'Q:') === 0 ) {
                    $current_q = trim( preg_replace('/^Q:\s*/i','', $txt) );
                } elseif ( stripos($txt, 'A:') === 0 && $current_q ) {
                    $answer = trim( preg_replace('/^A:\s*/i','', $txt) );
                    $pairs[] = ['q' => $current_q, 'a' => $answer];
                    $current_q = null;
                }
            }

            foreach ($pairs as $pa) {
                if ( empty($pa['q']) || empty($pa['a']) ) continue;
                $entities[] = [
                    "@type" => "Question",
                    "name"  => wp_strip_all_tags( $pa['q'] ),
                    "acceptedAnswer" => [
                        "@type" => "Answer",
                        "text" => wp_strip_all_tags( $pa['a'] )
                    ]
                ];
            }

            libxml_clear_errors();
            return $entities;
        }

        // For each ss-qa container
        foreach ($nodes as $node) {

            $ps = $node->getElementsByTagName('p');
            $q = $a = null;

            for ($i = 0; $i < $ps->length; $i++) {
                $text = trim( preg_replace('/\s+/', ' ', $ps->item($i)->textContent) );
                if ( stripos($text, 'Q:') === 0 ) {
                    $q = trim( preg_replace('/^Q:\s*/i','', $text) );
                } elseif ( stripos($text, 'A:') === 0 ) {
                    $a = trim( preg_replace('/^A:\s*/i','', $text) );
                }

                if ($q && $a) {
                    $entities[] = [
                        "@type" => "Question",
                        "name"  => wp_strip_all_tags( $q ),
                        "acceptedAnswer" => [
                            "@type" => "Answer",
                            "text" => wp_strip_all_tags( $a )
                        ]
                    ];
                    $q = $a = null;
                }
            }

            // fallback
            if (empty($entities)) {
                $inner = $dom->saveHTML($node);
                if (preg_match_all('/Q:\s*(.*?)\s*<\/p>.*?A:\s*(.*?)\s*<\/p>/si', $inner, $m, PREG_SET_ORDER)) {
                    foreach ($m as $mm) {
                        $entities[] = [
                            "@type" => "Question",
                            "name"  => wp_strip_all_tags( $mm[1] ),
                            "acceptedAnswer" => [
                                "@type" => "Answer",
                                "text" => wp_strip_all_tags( $mm[2] )
                            ]
                        ];
                    }
                }
            }
        }

        libxml_clear_errors();
        return $entities;
    }
}

/**
 * MAIN INJECTION BLOCK
 * (Only THIS part was changed — governor toggle added)
 */
add_action('wp_head', function () {

    // NEW: Schema Governor Toggle (required)
    $govern = (bool) get_option( SS_Settings::OPT_SCHEMA_GOVERNOR, true );
    if (!$govern) return;   // STOP ALL FAQ/ARTICLE schema if OFF

    if (!is_singular()) return;

    global $post;
    if (empty($post) || !isset($post->ID)) return;

    $post_id = $post->ID;

    // Extract FAQ from content
    $faq = searchshifter_get_faq_schema_for_post($post_id);

    // Build schema graph
    $schema = [
        "@context" => "https://schema.org",
        "@graph" => []
    ];

    // ARTICLE NODE (kept unchanged)
    $schema["@graph"][] = [
        "@type" => "Article",
        "@id"   => get_permalink($post_id) . "#article",
        "headline"     => get_the_title($post_id),
        "url"          => get_permalink($post_id),
        "author" => [
            "@type" => "Person",
            "name"  => get_the_author_meta('display_name', $post->post_author),
            "url"   => get_author_posts_url($post->post_author)
        ],
        "image"        => get_the_post_thumbnail_url($post_id, 'full') ?: null,
        "datePublished"=> get_the_date('c', $post_id),
        "dateModified" => get_the_modified_date('c', $post_id),
        "inLanguage"   => get_bloginfo('language')
    ];

    // FAQ block if found
    if (!empty($faq)) {
        $faq["@id"] = get_permalink($post_id) . "#faq";
        $schema["@graph"][] = $faq;
    }

    // Output when graph not empty
    if (!empty($schema["@graph"])) {
        echo '<script type="application/ld+json">' .
            wp_json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) .
        '</script>';
    }

}, 99);

