<?php
/**
 * Badge count REST routes.
 *
 * @package MenuVerse
 */

namespace WPXero\MenuVerse\Rest;

use WPXero\MenuVerse\Compat\Yith_Wishlist;

defined( 'ABSPATH' ) || exit;

/**
 * Serves the wishlist badge its number.
 *
 * WooCommerce needs no equivalent here: its Store API already publishes a cart
 * route, so the badge reads that directly. YITH publishes nothing, hence this.
 */
final class Counts_Controller extends Rest_Controller {

	/**
	 * Registers routes.
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			self::REST_NAMESPACE,
			'/counts/wishlist',
			array(
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_wishlist_count' ),
					'permission_callback' => array( $this, 'can_read_own_count' ),
				),
			)
		);
	}

	/**
	 * Checks permission for reading one's own wishlist count.
	 *
	 * This is a visitor facing number rather than an administrative one, so the
	 * settings capability would be wrong. It is still a real check: the count
	 * belongs to the requesting account, so an account is required. Signed out
	 * visitors keep the number the page was rendered with, which is the right
	 * trade for never publishing an unauthenticated route.
	 *
	 * @return true|\WP_Error
	 */
	public function can_read_own_count() {
		if ( is_user_logged_in() ) {
			return true;
		}

		return new \WP_Error(
			'menuverse_forbidden',
			__( 'You must be signed in to read this count.', 'menuverse' ),
			array( 'status' => 401 )
		);
	}

	/**
	 * Returns the wishlist item count for the current user.
	 *
	 * @return \WP_REST_Response
	 */
	public function get_wishlist_count() {
		nocache_headers();

		return rest_ensure_response(
			array( 'count' => Yith_Wishlist::count() )
		);
	}
}
