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

class SS_Entity_Conflict {


    public static function render_page() {
        echo '<div class="wrap"><h1>Entity Conflict Detector</h1>';

        $conflicts = self::scan();

        if (empty($conflicts)) {
            echo '<div class="notice notice-success">
                <p>✅ No conflicts found. All terms are consistent.</p>
            </div></div>';
            return;
        }

        echo '<div class="notice notice-warning">
                <p>⚠ Duplicate or conflicting glossary terms detected. Review below.</p>
            </div>';
        echo '<div class="notice notice-info" style="margin-top:10px;">
            <p><strong>How to fix:</strong></p>
            <ul style="margin-left:15px;">
                <li><strong>Duplicate (Same meaning):</strong> Keep one term and delete the duplicate.</li>
                <li><strong>Conflict (Different meanings):</strong> Update definitions so they match, or rename terms to make them unique.</li>
            </ul>
        </div>';
        foreach ($conflicts as $term => $conflict) {

            $entries = $conflict['entries'];
            $type    = $conflict['type'];

            echo '<div style="background:#fff;padding:15px;margin-bottom:20px;border:1px solid #ddd;">';

            if ($type === 'meaning_conflict') {
                echo '<h2 style="color:red;">🔴 ' . esc_html($term) . ' (Conflict: Different meanings)</h2>';
            } else {
                echo '<h2 style="color:#dba617;">⚠ ' . esc_html($term) . ' (Duplicate: Same meaning)</h2>';
            }

            foreach ($entries as $entry) {

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

                $display = wp_trim_words(wp_strip_all_tags($entry['raw']), 20);

                if (empty(trim($display))) {
                    $display = 'No definition found';
                }

                echo '<p><strong>From:</strong> ' . esc_html($entry['title']) . '<br><br>';
                echo '<strong>Definition:</strong><br>' . esc_html($display) . '</p>';

                echo '<a href="' . esc_url( get_edit_post_link( $entry['id'] ) ) . '" class="button button-small">Edit</a>';

                echo '</div>';
            }

            echo '</div>';
        }

        echo '</div>';
    }

    public static function scan() {

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

        $terms_map = [];
        $conflicts = [];

        foreach ($glossary as $g) {

            $term = strtolower(trim($g->post_title));

            if (!isset($terms_map[$term])) {
                $terms_map[$term] = [];
            }

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

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


            $terms_map[$term][] = [
                'id'   => $g->ID,
                'raw'  => $definition,
                'title'=> $g->post_title
            ];
        }

        // 🔥 Detect duplicates + meaning conflicts
        foreach ($terms_map as $term => $entries) {

            if (count($entries) > 1) {

                $definitions = array_map(function($e){

                    $text = wp_strip_all_tags($e['raw']);

                    // Normalize spaces + lowercase
                    $text = strtolower(trim(preg_replace('/\s+/', ' ', $text)));

                    return $text;

                }, $entries);
                // 🔍 Smart similarity check instead of exact match
                $is_same = true;

                $base = $definitions[0];

                foreach ($definitions as $def) {

                    similar_text($base, $def, $percent);

                    // If similarity is low → treat as conflict
                    if ($percent < 80) {
                        $is_same = false;
                        break;
                    }
                }

                // ✅ classify type
                $type = $is_same 
                    ? 'duplicate_only' 
                    : 'meaning_conflict';

                $conflicts[$term] = [
                    'type' => $type,
                    'entries' => $entries
                ];
            }
        }

        return $conflicts;
    }
}