<?php
// File: modules/internal-link-opportunities.php
if ( ! defined('ABSPATH') ) { exit; }

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

// Internal Linking Opportunities API
add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/internal-link-opportunities', [
        'methods'  => WP_REST_Server::READABLE, // GET
        'callback' => 'myaio_sac_internal_link_opportunities',
        // keep output unchanged (Unauthorized handled in callback)
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ]);
});

function myaio_sac_internal_link_opportunities(WP_REST_Request $request) {

    // ✅ Consistent auth across all modules (same output)
    $auth = function_exists('myaio_sac_require_api_key_or_401') ? myaio_sac_require_api_key_or_401($request) : null;
    if ($auth !== true) {
        return $auth instanceof WP_REST_Response ? $auth : new WP_REST_Response(['error' => 'Unauthorized'], 401);
    }

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

    $all_titles = [];
    foreach ($posts as $post) {
        $all_titles[$post->ID] = [
            'title' => strtolower(trim($post->post_title)),
            'url'   => get_permalink($post),
        ];
    }

    $results = [];

    foreach ($posts as $post) {
        $content = strtolower(trim(wp_strip_all_tags($post->post_content)));
        $opportunities = [];

        foreach ($all_titles as $target_id => $target) {
            if ($target_id === $post->ID) continue;

            $target_title = $target['title'];

            // Skip if already linked
            if (strpos($post->post_content, $target['url']) !== false) continue;

            // Search for the title keyword match
            if ($target_title !== '' && strpos($content, $target_title) !== false) {
                $opportunities[] = [
                    'suggested_anchor' => $target_title,
                    'link_to'          => $target['url']
                ];
            }
        }

        if (!empty($opportunities)) {
            $results[] = [
                'page_url'        => get_permalink($post),
                'page_title'      => get_the_title($post),
                'link_suggestions'=> $opportunities
            ];
        }
    }

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