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

class SS_Orphan_Engine {

    public static function scan() {

        $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' => [],
            ];
        }

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

        $post_results = [];
        $link_issues = [];

        foreach ($posts as $p) {

            $content = strtolower(
                wp_strip_all_tags(
                    apply_filters('the_content', $p->post_content)
                )
            );

            $matched = [];

            foreach ($terms as $gid => $entry) {

                $term = $entry['term'];
                $url  = get_permalink($gid);

                $raw_content = apply_filters('the_content', $p->post_content);

                $content = strtolower(
                    wp_strip_all_tags($raw_content)
                );

                $found  = strpos($content, $term) !== false;
                $linked = strpos($raw_content, $url) !== false;

                if ($found) {

                    $matched[] = $term;

                    $terms[$gid]['locations'][] = $p->post_title;

                    if (!$linked) {
                        $link_issues[] = [
                            'post_id' => $p->ID,
                            'post_title' => $p->post_title,
                            'term' => $term
                        ];
                    }
                }
            }

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

        // Orphans
        $orphans = [];

        foreach ($terms as $entry) {
            if (empty($entry['locations'])) {
                $orphans[] = $entry['term'];
            }
        }

        return [
            'terms' => $terms,
            'posts' => $post_results,
            'orphans' => $orphans,
            'link_issues' => $link_issues
        ];
    }
}