<?php
// Backlink Analysis API Endpoint

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

// Use the 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', '/backlink-analysis', [
        'methods'  => 'GET',
        'callback' => 'myaio_sac_backlink_analysis',
        'permission_callback' => 'myaio_sac_backlink_analysis_permission',
    ]);
});

/**
 * Permission callback for backlink-analysis
 * Uses the shared myaio_sac_validate_api_key() from includes/sac-utils.php
 */
if ( ! function_exists('myaio_sac_backlink_analysis_permission') ) {
    function myaio_sac_backlink_analysis_permission( WP_REST_Request $request ) {
        if ( function_exists('myaio_sac_validate_api_key') && myaio_sac_validate_api_key($request) ) {
            return true;
        }
        return new WP_Error('unauthorized', 'Invalid or unverified API key', ['status' => 401]);
    }
}


/**
 * Main callback
 */
function myaio_sac_backlink_analysis(WP_REST_Request $request) {
    $urls = myaio_sac_get_all_crawlable_urls();
    $results = [];
    $total_dofollow = 0;
    $total_nofollow = 0;

    foreach ($urls as $url_data) {
        $url = $url_data['url'];
        $type = $url_data['type'];
        $category = $url_data['category'];

        $dofollow = 0;
        $nofollow = 0;
        $dofollow_urls = [];
        $nofollow_urls = [];

        $response = wp_remote_get($url);
        if (is_wp_error($response)) continue;

        $html = wp_remote_retrieve_body($response);
        if (empty($html)) continue;

        libxml_use_internal_errors(true);
        $dom = new DOMDocument();
        @$dom->loadHTML($html);

        foreach ($dom->getElementsByTagName('a') as $link) {
            $href = $link->getAttribute('href');
            if (empty($href) || !filter_var($href, FILTER_VALIDATE_URL)) continue;

            $rel = strtolower($link->getAttribute('rel'));
            if (stripos($rel, 'nofollow') !== false) {
                $nofollow++;
                $nofollow_urls[] = $href;
            } else {
                $dofollow++;
                $dofollow_urls[] = $href;
            }
        }

        $results[] = [
            'url' => $url,
            'type' => $type,
            'category' => $category,
            'dofollow_links' => $dofollow,
            'nofollow_links' => $nofollow,
            'dofollow_urls' => $dofollow_urls,
            'nofollow_urls' => $nofollow_urls,
        ];

        $total_dofollow += $dofollow;
        $total_nofollow += $nofollow;
    }

    return rest_ensure_response([
        'summary' => [
            'total_pages' => count($results),
            'total_dofollow' => $total_dofollow,
            'total_nofollow' => $total_nofollow,
        ],
        'pages' => $results,
    ]);
}

/**
 * Helper function to collect all crawlable URLs
 */
function myaio_sac_get_all_crawlable_urls() {
    $urls = [];

    // Posts
    $posts = get_posts([
        'post_type' => 'post',
        'post_status' => 'publish',
        'fields' => 'ids',
        'posts_per_page' => -1,
    ]);

    foreach ($posts as $post_id) {
        $categories = get_the_category($post_id);
        $category_name = ($categories && !is_wp_error($categories)) ? $categories[0]->name : 'Uncategorized';
        $urls[] = [
            'url' => get_permalink($post_id),
            'type' => 'Post',
            'category' => $category_name,
        ];
    }

    // Pages
    $pages = get_posts([
        'post_type' => 'page',
        'post_status' => 'publish',
        'fields' => 'ids',
        'posts_per_page' => -1,
    ]);

    foreach ($pages as $page_id) {
        $urls[] = [
            'url' => get_permalink($page_id),
            'type' => 'Page',
            'category' => null,
        ];
    }

    // Categories
    $cats = get_categories();
    foreach ($cats as $cat) {
        $urls[] = [
            'url' => get_category_link($cat->term_id),
            'type' => 'Category',
            'category' => $cat->name,
        ];
    }

    return $urls;
}
