<?php
// File: modules/external-links-api.php

defined('ABSPATH') || exit;

// Shared key validation used across ALL modules
require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/external-links', [
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'myaio_sac_get_external_links',
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ]);
});

/**
 * Extract external links from all posts/pages
 * Output MUST remain same.
 */
if (!function_exists('myaio_sac_get_external_links')) {
    function myaio_sac_get_external_links(WP_REST_Request $request) {
        $site_host = wp_parse_url(home_url(), PHP_URL_HOST);
        $external_links = [];

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

        foreach ($posts as $post) {
            // Keep same approach (the_content filters), but ensure string
            $content = (string) apply_filters('myaio_the_content', $post->post_content);

            libxml_use_internal_errors(true);
            $dom = new DOMDocument();
            @$dom->loadHTML($content);
            $anchors = $dom->getElementsByTagName('a');

            foreach ($anchors as $anchor) {
                $href = (string) $anchor->getAttribute('href');
                $text = trim((string) $anchor->nodeValue);

                // Same skip rules as original
                if (empty($href) || strpos($href, '#') === 0 || strpos($href, 'mailto:') === 0) {
                    continue;
                }

                $link_host = wp_parse_url($href, PHP_URL_HOST);

                // Same external rule (different host)
                if ($link_host && $site_host && $link_host !== $site_host) {
                    $external_links[] = [
                        'source_page'  => get_permalink($post),
                        'external_url' => $href,
                        'anchor_text'  => $text,
                    ];
                }
            }
        }

        return rest_ensure_response([
            'total_external_links' => count($external_links),
            'links'                => $external_links
        ]);
    }
}
