    <?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'])) {
                self::run_full_scan();
                echo '<div class="updated"><p>Reinforcement scan completed.</p></div>';
            }

            echo '<form method="post" style="margin-bottom:20px;">';
            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'] ? '🟢 Reinforced' : '🔴 Missing').'</td>
                        <td>'.implode(', ', $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>'.get_the_title($pid).'</td>
                        <td>'.($row['ok'] ? '🟢 Reinforced' : '🔴 No glossary terms found').'</td>
                        <td>'.implode(', ', $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(strip_tags(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')
            ]);
        }
    }
