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

    class SS_Reinforcement_Scanner {

        const OPTION_RESULTS = 'ss_reinforcement_results';

        public static function init() {

            // Only load for Authority plan
            if (self::plan() !== 'authority') return;

            // Add admin menu
            add_action('admin_menu', [__CLASS__, 'add_menu']);

            // Allow external trigger
            add_action('ss_run_reinforcement_scan', [__CLASS__, 'run_full_scan']);
        }

        private static function plan() {
            if (!class_exists('SS_Licensing')) return 'free';
            $data = SS_Licensing::get_cached_status();
            return strtolower($data['plan'] ?? 'free');
        }

        public static function add_menu() {
            add_submenu_page(
                'searchshifter',
                'Reinforcement Scanner',
                'Reinforcement Scanner',
                'manage_options',
                'ss-reinforcement',
                [__CLASS__, 'render_page']
            );
        }

        public static function render_page() {

            echo '<div class="wrap"><h1>Cross-Page Reinforcement Scanner</h1>';

            if (self::plan() !== 'authority') {
                echo '<div class="notice notice-error"><p>This feature requires the <strong>Authority</strong> plan.</p></div></div>';
                return;
            }

            // Run Scanner When Button Clicked
            if (
                isset( $_POST['run_scan'], $_POST['searchshifter_reinforcement_nonce'] ) &&
                wp_verify_nonce(
                    sanitize_text_field( wp_unslash( $_POST['searchshifter_reinforcement_nonce'] ) ),
                    'searchshifter_run_reinforcement'
                )
            ) {
                self::run_full_scan();

                echo '<div class="notice notice-success">
                    <p>' . esc_html__( 'Reinforcement scan completed.', 'searchshifter' ) . '</p>
                </div>';
            }

            echo '<form method="post" style="margin-bottom:20px;">';
            wp_nonce_field( 'searchshifter_run_reinforcement', 'searchshifter_reinforcement_nonce' );
            submit_button( 'Run Reinforcement Scan', 'primary', 'run_scan' );
            echo '</form>';


            $results = get_option(self::OPTION_RESULTS, []);

            if (!$results) {
                echo '<p>No scan results found. Run scan to generate results.</p></div>';
                return;
            }

            echo '<h2>Glossary Terms</h2>';
            echo '<table class="widefat fixed">
                    <thead><tr><th>Term</th><th>Status</th><th>Found In</th></tr></thead><tbody>';

            foreach ($results['terms'] as $term => $row) {
                echo '<tr>
                    <td>' . esc_html($term) . '</td>
                    <td>' . ($row['ok'] ? esc_html__('🟢 Reinforced', 'searchshifter') : esc_html__('🔴 Missing', 'searchshifter')) . '</td>
                    <td>' . esc_html(implode(', ', array_map('esc_html', $row['locations']))) . '</td>
                </tr>';
            }

            echo '</tbody></table>';

            echo '<h2 style="margin-top:40px;">Pages</h2>';
            echo '<table class="widefat fixed">
                    <thead><tr><th>Page</th><th>Status</th><th>Matched Terms</th></tr></thead><tbody>';

            foreach ($results['posts'] as $pid => $row) {
                echo '<tr>
                    <td>' . esc_html(get_the_title($pid)) . '</td>
                    <td>' . ($row['ok']
                        ? esc_html__('🟢 Reinforced', 'searchshifter')
                        : esc_html__('🔴 No glossary terms found', 'searchshifter')
                    ) . '</td>
                    <td>' . esc_html(implode(', ', array_map('esc_html', $row['terms']))) . '</td>
                </tr>';
            }

            echo '</tbody></table></div>';
        }

        public static function run_full_scan() {

            // Load glossary terms
            $glossary = get_posts([
                'post_type' => 'ss_glossary',
                'numberposts' => -1,
                'post_status' => 'publish'
            ]);

            $terms = [];

            foreach ($glossary as $t) {
                $terms[$t->ID] = [
                    'term' => strtolower($t->post_title),
                    'locations' => [],
                ];
            }

            // Scan Pages, FAQs, Posts, Q&A
            $posts = get_posts([
                'post_type' => ['post', 'page', 'ss_qa'],
                'posts_per_page' => -1,
                'post_status' => 'publish'
            ]);

            $post_results = [];

            foreach ($posts as $p) {

             $content = strtolower(
                wp_strip_all_tags(
                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core WordPress hook
                    apply_filters( 'the_content', $p->post_content )
                )
            );

                $matched = [];

                foreach ($terms as $gid => $entry) {
                    if (strpos($content, $entry['term']) !== false) {
                        $matched[] = $entry['term'];
                        $terms[$gid]['locations'][] = $p->post_title;
                    }
                }

                $post_results[$p->ID] = [
                    'terms' => $matched,
                    'ok' => !empty($matched)
                ];
            }

            // Build term results
            $term_results = [];

            foreach ($terms as $tid => $entry) {
                $term_results[$entry['term']] = [
                    'locations' => $entry['locations'],
                    'ok' => !empty($entry['locations'])
                ];
            }

            update_option(self::OPTION_RESULTS, [
                'terms' => $term_results,
                'posts' => $post_results,
                'last_run' => current_time('mysql')
            ]);
        }
    }
