<?php
defined( 'ABSPATH' ) || exit;

/**
 * REST routes (admin-only).
 *
 * - /wp-json/bw-lead-ai/v1/links : list recent posts/pages for the UTM builder autocomplete
 */
class BW_Lead_AI_REST {

	const NAMESPACE_V1 = 'bw-lead-ai/v1';

	private static $instance = null;

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

	public function register() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	public function register_routes() {
		register_rest_route(
			self::NAMESPACE_V1,
			'/links',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_links' ),
				// This lists the site's published permalinks for the UTM builder's
				// autocomplete. The data is public, but the only thing that asks
				// for it is a manage-only screen — so the route is gated where its
				// caller is rather than one notch looser for no one's benefit.
				'permission_callback' => array( $this, 'require_manage' ),
			)
		);
	}

	/**
	 * Reads need the view capability; anything that writes needs manage.
	 *
	 * Both exist so the contract is stated once for whatever route comes next,
	 * rather than each one deciding for itself and drifting.
	 */
	public function require_view() {
		return BW_Lead_AI_Caps::can_view();
	}

	public function require_manage() {
		return BW_Lead_AI_Caps::can_manage();
	}

	/**
	 * Kept because it was public. Nothing in the plugin calls it any more; a site
	 * that registered its own route against it keeps working, at the tighter of
	 * the two capabilities.
	 *
	 * @deprecated 1.10.0 Use require_view() or require_manage().
	 */
	public function require_manage_options() {
		return $this->require_manage();
	}

	public function get_links( $request ) {
		$args  = array(
			'post_type'      => 'any',
			'orderby'        => 'title',
			'order'          => 'ASC',
			'posts_per_page' => 200,
			'post_status'    => 'publish',
		);
		$links = array();
		$query = new WP_Query( $args );
		while ( $query->have_posts() ) {
			$query->the_post();
			$links[] = esc_url_raw( get_the_permalink() );
		}
		wp_reset_postdata();
		return rest_ensure_response( $links );
	}
}
