<?php

/**
 * Link Analysis REST Endpoint
 * 
 * Provides link analysis data
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\RestApi;

use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;

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


// Register the endpoint


add_action('rest_api_init', function() {
    register_rest_route('prorank-seo/v1', '/linking/analysis', [
        [
            'methods' => WP_REST_Server::READABLE,
            'callback' => __NAMESPACE__ . '\get_link_analysis',
            'permission_callback' => function() {
                return current_user_can('edit_posts');
            },
        ]
    ]);
});

/**
 * Get link analysis data
 */
function get_link_analysis(WP_REST_Request $request): WP_REST_Response {
    global $wpdb;
    
    // Get all posts
    $posts = get_posts([
        'post_type' => ['post', 'page'],
        'post_status' => 'publish',
        'numberposts' => -1,
    ]);
    
    $total_posts = count($posts);
    $posts_with_links = 0;
    $orphaned_posts = [];
    $broken_links = [];
    $total_internal_links = 0;
    
    foreach ($posts as $post) {
        $content = $post->post_content;
        
        // Check for internal links
        preg_match_all('/<a[^>]+href=["\']([^"\']+)["\'][^>]*>/i', $content, $matches);
        
        if (!empty($matches[1])) {
            $posts_with_links++;
            
            foreach ($matches[1] as $url) {
                // Check if internal
                if (strpos($url, get_site_url()) !== false || strpos($url, '/') === 0) {
                    $total_internal_links++;
                    
                    // Check if link is broken
                    $target_id = url_to_postid($url);
                    if ($target_id === 0 && strpos($url, get_site_url()) !== false) {
                        $broken_links[] = [
                            'source' => $post->post_title,
                            'url' => $url,
                            'status' => 404,
                        ];
                    }
                }
            }
        }
        
        // Check if orphaned (no incoming links)
        $has_incoming = false;
        $permalink = get_permalink($post->ID);
        
        foreach ($posts as $other_post) {
            if ($other_post->ID !== $post->ID && strpos($other_post->post_content, $permalink) !== false) {
                $has_incoming = true;
                break;
            }
        }
        
        if (!$has_incoming) {
            $orphaned_posts[] = [
                'id' => $post->ID,
                'title' => $post->post_title,
                'url' => $permalink,
            ];
        }
    }
    
    return rest_ensure_response([
        'success' => true,
        'data' => [
            'total_posts' => $total_posts,
            'posts_with_links' => $posts_with_links,
            'orphaned_posts' => $orphaned_posts,
            'broken_links' => array_slice($broken_links, 0, 20),
            'total_internal_links' => $total_internal_links,
            'link_coverage' => $total_posts > 0 ? round(($posts_with_links / $total_posts) * 100, 2) : 0,
        ],
    ]);
}

/**
 * Get linkmap visualization data
 */
function get_linkmap_data(WP_REST_Request $request): WP_REST_Response {
    $post_types = $request->get_param('post_types');
    $max_nodes = min((int) $request->get_param('max_nodes'), 500);

    // Handle comma-separated post_types from frontend
    if (is_string($post_types)) {
        $post_types = array_filter(array_map('trim', explode(',', $post_types)));
    }
    if (empty($post_types)) {
        $post_types = ['post', 'page'];
    }

    // Get posts
    $posts = get_posts([
        'post_type' => $post_types,
        'post_status' => 'publish',
        'numberposts' => $max_nodes,
    ]);

    $nodes = [];
    $links = [];
    $post_ids = wp_list_pluck($posts, 'ID');

    // First pass: count links
    $inbound_counts = [];
    $outbound_counts = [];

    foreach ($posts as $post) {
        $outbound_counts[$post->ID] = 0;
        if (!isset($inbound_counts[$post->ID])) {
            $inbound_counts[$post->ID] = 0;
        }

        // Find outbound links
        preg_match_all('/<a[^>]+href=["\']([^"\']+)["\'][^>]*>/i', $post->post_content, $matches);

        if (!empty($matches[1])) {
            foreach ($matches[1] as $url) {
                $target_id = url_to_postid($url);
                if ($target_id && $target_id !== $post->ID && in_array($target_id, $post_ids)) {
                    $outbound_counts[$post->ID]++;
                    if (!isset($inbound_counts[$target_id])) {
                        $inbound_counts[$target_id] = 0;
                    }
                    $inbound_counts[$target_id]++;

                    $links[] = [
                        'source' => $post->ID,
                        'target' => $target_id,
                        'value' => 1,
                    ];
                }
            }
        }
    }

    // Second pass: create nodes with counts
    foreach ($posts as $post) {
        $inbound = $inbound_counts[$post->ID] ?? 0;
        $outbound = $outbound_counts[$post->ID] ?? 0;
        $is_orphan = ($inbound === 0);

        $nodes[] = [
            'id' => $post->ID,
            'title' => $post->post_title,
            'name' => $post->post_title,
            'url' => get_permalink($post->ID),
            'post_type' => $post->post_type,
            'inbound_links' => $inbound,
            'outbound_links' => $outbound,
            'is_orphan' => $is_orphan,
            'is_pillar' => (bool) get_post_meta($post->ID, '_prorank_is_pillar_content', true),
            'group' => $post->post_type === 'page' ? 1 : 2,
        ];
    }

    // Calculate metrics
    $total_links = count($links);
    $orphan_count = count(array_filter($nodes, function($n) { return $n['is_orphan']; }));
    $link_density = count($nodes) > 0 ? round($total_links / count($nodes), 2) : 0;

    return rest_ensure_response([
        'success' => true,
        'data' => [
            'nodes' => $nodes,
            'links' => $links,
            'metrics' => [
                'total_nodes' => count($nodes),
                'total_links' => $total_links,
                'orphan_count' => $orphan_count,
                'link_density' => $link_density,
            ],
        ],
    ]);
}
