<?php
/**
 * Icon library REST route.
 *
 * @package MenuVerse
 */

namespace WPXero\MenuVerse\Rest;

use WPXero\MenuVerse\Frontend\Icon_Library;

defined( 'ABSPATH' ) || exit;

/**
 * Serves the bundled icon library to the dashboard picker.
 */
final class Icons_Controller extends Rest_Controller {

	/**
	 * Registers routes.
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			self::REST_NAMESPACE,
			'/icons',
			array(
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_icons' ),
					'permission_callback' => array( $this, 'can_read_icons' ),
					'args'                => array(
						'include_ui' => array(
							'type'    => 'boolean',
							'default' => false,
						),
					),
				),
			)
		);
	}

	/**
	 * Checks permission for reading the icon library.
	 *
	 * The block editor offers icons on menu item blocks, so anyone who may
	 * write content needs this list. Icon names carry nothing sensitive.
	 *
	 * @return true|\WP_Error
	 */
	public function can_read_icons() {
		if ( current_user_can( 'edit_posts' ) ) {
			return true;
		}

		return $this->permission_check();
	}

	/**
	 * Returns the icon library.
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return \WP_REST_Response
	 */
	public function get_icons( \WP_REST_Request $request ) {
		$icons = $request->get_param( 'include_ui' )
			? Icon_Library::all()
			: Icon_Library::selectable();

		$list = array();

		foreach ( $icons as $slug => $icon ) {
			$list[] = array(
				'slug'     => (string) $slug,
				'label'    => isset( $icon['label'] ) ? (string) $icon['label'] : (string) $slug,
				'keywords' => isset( $icon['keywords'] ) ? array_map( 'strval', (array) $icon['keywords'] ) : array(),
				'shapes'   => isset( $icon['shapes'] ) ? (array) $icon['shapes'] : array(),
			);
		}

		return rest_ensure_response(
			array(
				'viewBox' => '0 0 24 24',
				'icons'   => $list,
			)
		);
	}
}
