<?php
class SS_Authority_Visibility {

    // public static function init() {
    //     add_submenu_page(
    //         'searchshifter',
    //         __('Authority Visibility Checks', 'searchshifter'),
    //         __('Authority Checks', 'searchshifter'),
    //         'manage_options',
    //         'searchshifter-authority-visibility',
    //         [__CLASS__, 'render_page']
    //     );
    // }

    public static function render_page() {

        // -------------------------
        // Pull signals for report
        // -------------------------

        // Brand Entity Presence
        $brand_ok = self::has_brand_entity();
        $brand_status = $brand_ok ? '✔ Strong' : '❌ Weak';
        $brand_desc = $brand_ok
            ? 'Brand entity properly referenced across key trust pages.'
            : 'Brand name missing on About or Contact page.';

        // Domain Authority Signals
        $da_count = self::domain_authority_score();
        $da_status = ($da_count >= 2) ? '✔ Strong' : '❌ Weak';
        $da_desc = "Authority indicators detected: {$da_count} of 3.";

        // Entity Linking Gaps
        $glossary_terms = self::glossary_terms_count();
        $linked_pages = self::linked_page_count();
        $entity_status = ($linked_pages > 0) ? '✔ OK' : '❌ Missing Links';
        $entity_desc = "Glossary terms: {$glossary_terms}, linked pages: {$linked_pages}.";

        // Citation Readiness
        $policy_exists = self::policy_exists();
        $citation_status = $policy_exists ? '✔ Ready' : '❌ Not Ready';
        $citation_desc = $policy_exists
            ? 'AI Visibility Policy page exists.'
            : 'AI Visibility Policy page does not exist.';

        // Trust Signal Depth
        $trust_ok = self::has_trust_pages();
        $trust_status = $trust_ok ? '✔ Good' : '❌ Weak';
        $trust_desc = $trust_ok
            ? 'All major trust pages found.'
            : 'Missing About, Contact, or identity proof pages.';

        // -------------------------
        // Display
        // -------------------------
        ?>
        <div class="wrap">
            <h1>Authority Visibility Checks</h1>

            <table class="widefat fixed" style="margin-top:20px;">
                <thead>
                    <tr>
                        <th width="28%">Check</th>
                        <th width="12%">Status</th>
                        <th>Description</th>
                    </tr>
                </thead>
                <tbody>

                    <tr>
                        <td><strong>Brand Entity Presence</strong></td>
                        <td><?php echo esc_html( $brand_status ); ?></td>
                        <td><?php echo esc_html( $brand_desc ); ?></td>
                    </tr>

                    <tr>
                        <td><strong>Domain Authority Signals</strong></td>
                        <td><?php echo esc_html( $da_status ); ?></td>
                        <td><?php echo esc_html( $da_desc ); ?></td>
                    </tr>

                    <tr>
                        <td><strong>Entity Linking Gaps</strong></td>
                        <td><?php echo esc_html( $entity_status ); ?></td>
                        <td><?php echo esc_html( $entity_desc ); ?></td>
                    </tr>

                    <tr>
                        <td><strong>Citation Readiness</strong></td>
                        <td><?php echo esc_html( $citation_status ); ?></td>
                        <td><?php echo esc_html( $citation_desc ); ?></td>
                    </tr>

                    <tr>
                        <td><strong>Trust Signal Depth</strong></td>
                        <td><?php echo esc_html( $trust_status ); ?></td>
                        <td><?php echo esc_html( $trust_desc ); ?></td>
                    </tr>

                </tbody>
            </table>
        </div>
        <?php
    }

    // ---------------------------------------------------
    // Helper functions – simple logic matching client scope
    // ---------------------------------------------------

    private static function has_brand_entity() {
        return self::page_contains('about') || self::page_contains('contact');
    }

    private static function domain_authority_score() {
        // 0-3 simple placeholder scoring
        $score = 0;
        if (get_option('blog_public') == 1) $score++;
        if (has_site_icon()) $score++;
        if (get_option('blogdescription') != '') $score++;
        return $score;
    }

    private static function glossary_terms_count() {

        // Fetch all published glossary CPT entries
        $terms = get_posts([
            'post_type'      => 'ss_glossary',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'fields'         => 'ids'
        ]);

        return is_array($terms) ? count($terms) : 0;
    }

    private static function linked_page_count() {

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

        if (empty($glossary)) return 0;

        // Collect lowercase titles
        $terms = array_map(function($t){
            return strtolower($t->post_title);
        }, $glossary);

        // Scan pages & posts
        $posts = get_posts([
            'post_type'      => ['post', 'page'],
            'post_status'    => 'publish',
            'posts_per_page' => -1
        ]);

        $linked_pages = 0;

        foreach ($posts as $p) {

            // Use the same reinforcement scanner logic
           $content = strtolower(
                wp_strip_all_tags(
                    apply_filters(
                        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core WordPress hook.
                        'the_content',
                        $p->post_content
                    ),
                    true
                )
            );

            foreach ($terms as $term) {
                if (strpos($content, $term) !== false) {
                    $linked_pages++;
                    break; // no need to check more terms for this page
                }
            }
        }

        return $linked_pages;
    }


    private static function policy_exists() {
        $id = get_option('ss_ai_policy_page_id');
        return $id && get_post_status($id) === 'publish';
    }

    private static function has_trust_pages() {
        return (
            self::page_exists('about') &&
            self::page_exists('contact')
        );
    }

    private static function page_exists($slug) {
        return get_page_by_path($slug) !== null;
    }

    private static function page_contains($slug) {
        $page = get_page_by_path($slug);
        if (!$page) return false;
        $content = strtolower(
            wp_strip_all_tags(
                get_post_field( 'post_content', $page->ID ),
                true
            )
        );
        return strpos($content, strtolower(get_bloginfo('name'))) !== false;
    }
}
