    <?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>Content Optimization Scanner</h1>';

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

    // Run scan
    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>Scan completed successfully.</p></div>';
    }

    // Run button
    echo '<form method="post" style="margin-bottom:20px;">';
    wp_nonce_field('searchshifter_run_reinforcement', 'searchshifter_reinforcement_nonce');
    submit_button('Run 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;
    }

    // =========================
    // 🎨 STYLES
    // =========================
    echo '<style>
    .ss-card {
        background:#fff;
        border:1px solid #ddd;
        border-radius:8px;
        padding:16px;
        margin-bottom:20px;
    }
    .ss-title {
        font-size:18px;
        font-weight:600;
        margin-bottom:10px;
    }
    .ss-badge {
        display:inline-block;
        padding:5px 10px;
        border-radius:6px;
        font-size:12px;
        font-weight:600;
    }
    .ss-red { background:#ffe5e5; color:#d63638; }
    .ss-green { background:#e6f4ea; color:#1a7f37; }
    .ss-yellow { background:#fff8e1; color:#b26a00; }
    .ss-list li { margin-bottom:6px; }
    .ss-small { color:#666; font-size:13px; }
    </style>';

    // =========================
    // 📊 SUMMARY
    // =========================
 $problem_posts = array_filter( $results['posts'], function ( $p ) {
    return ! $p['ok'];
} );

$summary = [
    'problems' => count( $problem_posts ),
    'orphans'  => count( $results['orphans'] ?? [] ),
    'links'    => count( $results['link_issues'] ?? [] ),
];

// Sanitize values for output.
$problems = absint( $summary['problems'] );
$links    = absint( $summary['links'] );
$orphans  = absint( $summary['orphans'] );

echo '<div class="ss-card">
    <div class="ss-title">Overview</div>

    <div style="display:flex;gap:15px;flex-wrap:wrap;">';

echo '<div class="ss-badge ss-red">🔴 ' . esc_html( absint( $summary['problems'] ) ) . ' Pages need fixes</div>';
echo '<div class="ss-badge ss-yellow">🟡 ' . esc_html( absint( $summary['links'] ) ) . ' Linking gaps</div>';
echo '<div class="ss-badge ss-red">🔴 ' . esc_html( absint( $summary['orphans'] ) ) . ' Unused terms</div>';

echo '</div>

    <p class="ss-small" style="margin-top:10px;">
        These issues affect how well your content is structured and understood by AI systems.
    </p>
</div>';

    // =========================
    // 🔴 PROBLEM PAGES
    // =========================
    echo '<div class="ss-card">';
    echo '<div class="ss-title">Pages That Need Attention</div>';

    echo '<table class="widefat fixed">
        <thead><tr><th>Page</th><th>Status</th><th>Action</th></tr></thead><tbody>';

    $limit = absint( 10 );
    $count = 0;

    foreach ($problem_posts as $pid => $row) {

        if ($count >= $limit) break;
        $count++;

        echo '<tr>
                <td>' . esc_html(get_the_title($pid)) . '</td>
                <td><span class="ss-badge ss-red">Missing glossary terms</span></td>
                <td>
                    <a href="' . esc_url(get_edit_post_link($pid)) . '" 
                    class="button button-small" target="_blank">
                    Fix Page
                    </a>
                </td>
            </tr>';
    }

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

    if (count($problem_posts) > $limit) {
       echo '<p class="ss-small">Showing first ' . esc_html( ( $limit ) ) . ' issues</p>';
    }

    echo '<p class="ss-small">Add relevant glossary terms to improve clarity and AI understanding.</p>';

    echo '</div>';

    // =========================
    // 🔴 ORPHANS
    // =========================
    echo '<div class="ss-card">';
    echo '<div class="ss-title">Unused Glossary Terms</div>';

    if (!empty($results['orphans'])) {
        echo '<ul class="ss-list">';
        foreach ($results['orphans'] as $term) {
            echo '<li>❌ <strong>' . esc_html($term) . '</strong> is not used anywhere</li>';
        }
        echo '</ul>';
    } else {
        echo '<p class="ss-green">All glossary terms are currently used across your site. No action needed.</p>';
    }

    echo '<p class="ss-small">Consider adding these terms into relevant pages.</p>';

    echo '</div>';
// =========================
// ⚠ WEAK CONTENT (IMPROVED)
// =========================
echo '<div class="ss-card">';
echo '<div class="ss-title">Weak Content Issues</div>';

if (!empty($results['weak_issues'])) {

    // 🔹 GROUP BY TERM
    $grouped = [];

    foreach ($results['weak_issues'] as $item) {
        $grouped[$item['title']][] = $item;
    }

    $limit = 10;
    $count = 0;

    foreach ($grouped as $term => $items) {

        if ($count >= $limit) break;
        $count++;

        // 🔹 Merge all reasons
        $all_reasons = [];

        foreach ($items as $i) {
            if (!empty($i['reasons'])) {
                $all_reasons = array_merge($all_reasons, $i['reasons']);
            }
        }

        $all_reasons = array_unique($all_reasons);

        // 🔴 Severity
        $severity = in_array('Missing definition', $all_reasons)
            ? 'ss-red'
            : 'ss-yellow';

        echo '<div style="margin-bottom:15px;padding:12px;border:1px solid #eee;background:#fafafa;">';

        // 🔹 Title + Badge
        echo '<strong>⚠ ' . esc_html($term) . '</strong> ';
        echo '<span class="ss-badge ' . esc_attr($severity) . '" style="margin-left:8px;">';
        echo ($severity === 'ss-red') ? 'Critical' : 'Needs Improvement';
        echo '</span>';

        // 🔹 Issues
        echo '<p style="margin:8px 0 5px 0;"><strong>Issues:</strong></p>';
        echo '<ul class="ss-list">';

        foreach ($all_reasons as $reason) {

            // Better readable labels
            $label = match ($reason) {
                'Missing definition' => 'Definition is missing',
                'Too short' => 'Definition is too short',
                'Contains vague wording' => 'Contains vague wording',
                'Incomplete sentence' => 'Sentence is incomplete',
                default => $reason
            };

            echo '<li>• ' . esc_html($label) . '</li>';
        }

        echo '</ul>';

        // 🔹 Tip
        echo '<p class="ss-small" style="margin-top:6px;">
            Tip: Write a clear 20–40 word explanation in one complete sentence.
        </p>';

        // 🔹 Action (use first item link)
        $edit_id = $items[0]['id'];

        echo '<a href="' . esc_url(get_edit_post_link($edit_id)) . '" 
                class="button button-primary" 
                target="_blank">
                Improve
              </a>';

        echo '</div>';
    }

} else {
    echo '<p class="ss-green">All glossary content meets quality standards. No improvements needed.</p>';
}

echo '<p class="ss-small">
Improving weak definitions helps AI better understand and prioritize your content.
</p>';

echo '</div>';
    // =========================
    // 🟡 LINKING ISSUES
    // =========================
    echo '<div class="ss-card">';
    echo '<div class="ss-title">Linking Opportunities</div>';

    if (!empty($results['link_issues'])) {
        $limit = 10;
        $count = 0;

        foreach ($results['link_issues'] as $issue) {

            if ($count >= $limit) break;
            $count++;
            echo '<li>
                ⚠ <strong>' . esc_html($issue['term']) . '</strong> appears in 
                <strong>' . esc_html($issue['post_title']) . '</strong> but is not linked
            </li>';
        }
        echo '</ul>';
    } else {
        echo '<p class="ss-green">All glossary terms are properly linked.</p>';
    }

    echo '<p class="ss-small">Linking helps AI understand relationships between concepts.</p>';

    echo '</div>';

    // =========================
    // 📊 FULL REPORT
    // =========================
    echo '<div class="ss-card">';
    echo '<div class="ss-title" style="cursor:pointer;" onclick="
        var el = document.getElementById(\'ss-full-data\');
        el.style.display = (el.style.display === \'none\' ? \'block\' : \'none\');
    ">📊 Full Report (Advanced)</div>';

    echo '<div id="ss-full-data" style="display:none;">';

    // Terms table
    echo '<h3>Glossary Terms</h3>';
    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']
                ? '<span class="ss-badge ss-green">Connected</span>'
                : '<span class="ss-badge ss-red">Missing</span>') . '</td>
            <td>' . esc_html(implode(', ', $row['locations'])) . '</td>
        </tr>';
    }

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

    // Pages table
    echo '<h3 style="margin-top:30px;">All Pages</h3>';
    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']
                ? '<span class="ss-badge ss-green">Connected</span>'
                : '<span class="ss-badge ss-red">Missing</span>') . '</td>
            <td>' . esc_html(implode(', ', $row['terms'])) . '</td>
        </tr>';
    }

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

    

    echo '</div></div>'; // full report

    echo '</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_source = $p->post_content;

                // FAQ support
                if ($p->post_type === 'ss_qa') {

                    $faq_answer = get_post_meta($p->ID, '_ss_qa_answer', true);

                    if (!empty($faq_answer)) {
                        $content_source = $faq_answer;
                    }
                }

                $content = strtolower(
                    wp_strip_all_tags(
                        apply_filters('the_content', $content_source)
                    )
                );

                $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'])
                ];
            }
            // =========================
            // ⚠ WEAK CONTENT SCAN
            // =========================
            $weak_issues = [];

            foreach ($glossary as $g) {

                $definition = get_post_meta($g->ID, 'ss_definition', true);

                if (!is_string($definition) || trim($definition) === '') {
                    $definition = $g->post_content;
                }

                $text = strtolower(trim(wp_strip_all_tags($definition)));

                $reasons = [];

                // Empty
                if (empty($text)) {
                    $reasons[] = 'Missing definition';
                }

                // Too short
                if (str_word_count($text) < 20) {
                    $reasons[] = 'Too short';
                }

                // Vague words
                $vague_words = ['something','thing','etc','stuff','things'];

                foreach ($vague_words as $word) {
                    if (strpos($text, $word) !== false) {
                        $reasons[] = 'Contains vague wording';
                        break;
                    }
                }

                // Incomplete sentence
                if ($text && substr($text, -1) !== '.') {
                    $reasons[] = 'Incomplete sentence';
                }

                if (!empty($reasons)) {
                    $weak_issues[] = [
                        'id' => $g->ID,
                        'title' => $g->post_title,
                        'definition' => $text,
                        'reasons' => $reasons
                    ];
                }
            }
            update_option(self::OPTION_RESULTS, [
                'terms' => $term_results,
                'posts' => $post_results,
                'weak_issues' => $weak_issues,
                'last_run' => current_time('mysql')
            ]);
        }
    }
