<?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 () {

    $govern = (bool) get_option(SS_Settings::OPT_SCHEMA_GOVERNOR, true);
    if (!$govern) return;

    $faq_page = get_page_by_path('faq');

    if (!$faq_page || !is_page($faq_page->ID)) {
        return;
    }

    $post_id = $faq_page->ID;

    $faqs = get_posts([
        'post_type' => 'ss_qa',
        'post_status' => 'publish',
        'posts_per_page' => -1
    ]);

    $faq_entities = [];

    foreach ($faqs as $faq) {
        $answer = apply_filters('the_content', $faq->post_content);

        $faq_entities[] = [
            "@type" => "Question",
            "name" => wp_strip_all_tags($faq->post_title),
            "acceptedAnswer" => [
                "@type" => "Answer",
                "text" => wp_strip_all_tags($answer)
            ]
        ];
    }

    if (empty($faq_entities)) return;

    $schema = [
        "@context" => "https://schema.org",
        "@graph" => [
            [
                "@type" => "FAQPage",
                "@id" => get_permalink($post_id) . "#faq",
                "mainEntity" => $faq_entities
            ]
        ]
    ];

    echo '<script type="application/ld+json">' .
        wp_json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) .
    '</script>';

}, 99);

