<?php

namespace SerpIQ\Api\Controllers;

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

/**
 * REST: resolve WordPress edit links for given URLs (used by admin reports).
 */
final class Page_Links_Controller {
	private static ?Page_Links_Controller $instance = null;

	public static function instance(): Page_Links_Controller {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public function register_routes(): void {
		register_rest_route(
			'serpiq/v1',
			'/page-edit-links',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'resolve_edit_links' ),
				'permission_callback' => array( \SerpIQ\Api\Rest_Permission::class, 'admin_rest_request' ),
				'args'                => array(
					'urls' => array(
						'required' => true,
						'type'     => 'array',
						'items'    => array( 'type' => 'string' ),
					),
				),
			)
		);
	}

	public function resolve_edit_links( \WP_REST_Request $request ): \WP_REST_Response {
		$body = $request->get_json_params();
		$urls = isset( $body['urls'] ) && is_array( $body['urls'] ) ? $body['urls'] : array();
		$result = array();
		$home   = trailingslashit( home_url() );
		foreach ( $urls as $url ) {
			$url_in = is_string( $url ) ? trim( $url ) : '';
			$url_sanitized = '' !== $url_in ? esc_url_raw( $url_in ) : '';
			if ( '' === $url_sanitized ) {
				continue;
			}
			$normalized = trailingslashit( $url_sanitized );
			if ( function_exists( 'url_to_postid' ) ) {
				$post_id = url_to_postid( $normalized );
				if ( $post_id > 0 && current_user_can( 'edit_post', $post_id ) ) {
					$edit_link = get_edit_post_link( $post_id, 'raw' );
					if ( $edit_link ) {
						$result[ $url_sanitized ] = $edit_link;
						continue;
					}
				}
			}
			$result[ $url_sanitized ] = null;
		}
		return new \WP_REST_Response( $result, 200 );
	}
}
