<?php
/**
 * REST controller for mega panels.
 *
 * @package MenuVerse
 */

namespace WPXero\MenuVerse\Module\Mega_Menu;

use WPXero\MenuVerse\Capabilities;

defined( 'ABSPATH' ) || exit;

/**
 * Restricts the panel endpoints to users who may manage MenuVerse.
 *
 * The default posts controller lets anyone read a published post type that
 * opts into REST. Panels are an editing surface, not public content, so every
 * method here requires the management capability.
 */
final class Panel_Rest_Controller extends \WP_REST_Posts_Controller {

	/**
	 * Returns the error used for every denied request.
	 *
	 * @return \WP_Error
	 */
	private function forbidden() {
		return new \WP_Error(
			'menuverse_forbidden',
			__( 'You are not allowed to work with mega panels.', 'menuverse' ),
			array( 'status' => is_user_logged_in() ? 403 : 401 )
		);
	}

	/**
	 * Checks permission for reading a collection.
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return true|\WP_Error
	 */
	public function get_items_permissions_check( $request ) {
		return Capabilities::current_user_can_manage()
			? parent::get_items_permissions_check( $request )
			: $this->forbidden();
	}

	/**
	 * Checks permission for reading one panel.
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return true|\WP_Error
	 */
	public function get_item_permissions_check( $request ) {
		return Capabilities::current_user_can_manage()
			? parent::get_item_permissions_check( $request )
			: $this->forbidden();
	}
}
