<?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' ),
				'permission_callback' => array( $this, 'require_manage_options' ),
			)
		);
	}

	public function require_manage_options() {
		return current_user_can( 'manage_options' );
	}

	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 );
	}
}
