<?php
// File: modules/title-slug-checker.php

if (!defined('ABSPATH')) exit;

require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/title-slug-mismatch', [
        'methods'             => WP_REST_Server::READABLE, // GET
        'callback'            => 'myaio_sac_check_title_slug_match',
        'permission_callback' => 'myaio_sac_rest_require_api_key_title_slug',
    ]);
});

function myaio_sac_rest_require_api_key_title_slug(WP_REST_Request $request) {
    if (function_exists('myaio_sac_validate_api_key') && myaio_sac_validate_api_key($request)) {
        return true;
    }
    return new WP_Error('rest_forbidden', 'Unauthorized', ['status' => 401]);
}

function myaio_sac_check_title_slug_match(WP_REST_Request $request) {
    $posts = get_posts([
        'post_type'   => ['post', 'page'],
        'post_status' => 'publish',
        'numberposts' => -1
    ]);

    $stop_words = ['and', 'or', 'of', 'the', 'a', 'an', 'in', 'on'];
    $results = [];

    foreach ($posts as $post) {
        $title_slug = sanitize_title($post->post_title);
        $slug       = sanitize_title($post->post_name);

        $title_words = array_values(array_filter(explode('-', $title_slug)));
        $slug_words  = array_values(array_filter(explode('-', $slug)));

        $matched_words = array_values(array_intersect($title_words, $slug_words));

        $title_count = count($title_words);
        $match_score = $title_count > 0
            ? (count($matched_words) . '/' . $title_count)
            : '0/0';

        $stop_used = array_values(array_intersect($slug_words, $stop_words));
        $has_underscore = (strpos($post->post_name, '_') !== false);

        $aligned = ($title_count === 0)
            ? true
            : (count($matched_words) >= max(0, $title_count - 1));

        $results[] = [
            'title' => $post->post_title,
            'slug'  => $post->post_name,
            'match_score' => $match_score,
            'stop_words_in_slug' => $stop_used,
            'uses_underscore' => $has_underscore,
            'url'  => get_permalink($post),
            'status' => [
                'title_slug_aligned' => $aligned,
                'no_stop_words'      => empty($stop_used),
                'uses_hyphens_only'  => !$has_underscore
            ]
        ];
    }

    return rest_ensure_response(['results' => $results]);
}
