<?php
/**
 * Advanced Hooks - REST controller.
 *
 * @package Astra Addon
 * @since 4.13.12
 */

if ( ! class_exists( 'Astra_Ext_Advanced_Hooks_REST_Controller' ) && class_exists( 'WP_REST_Posts_Controller' ) ) {

	/**
	 * REST controller for the Custom Layout post type.
	 *
	 * The post type is public so layouts can render on the front end, which lets the default
	 * posts controller hand every published layout (content and targeting meta) to any visitor.
	 * Reading layouts over REST is limited to users who can manage them.
	 *
	 * @since 4.13.12
	 */
	// @codingStandardsIgnoreStart
	class Astra_Ext_Advanced_Hooks_REST_Controller extends WP_REST_Posts_Controller {
		// @codingStandardsIgnoreEnd

		/**
		 * Checks if a given request has access to read layouts.
		 *
		 * @since 4.13.12
		 * @param WP_REST_Request $request Full details about the request.
		 * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
		 */
		public function get_items_permissions_check( $request ) {
			if ( ! Astra_Ext_Advanced_Hooks_Loader::user_can_manage_layouts() ) {
				return $this->get_read_forbidden_error();
			}

			return parent::get_items_permissions_check( $request );
		}

		/**
		 * Checks if a given request has access to read a layout.
		 *
		 * @since 4.13.12
		 * @param WP_REST_Request $request Full details about the request.
		 * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise.
		 */
		public function get_item_permissions_check( $request ) {
			if ( ! Astra_Ext_Advanced_Hooks_Loader::user_can_manage_layouts() ) {
				return $this->get_read_forbidden_error();
			}

			return parent::get_item_permissions_check( $request );
		}

		/**
		 * Error returned when the current user may not read layouts.
		 *
		 * @since 4.13.12
		 * @return WP_Error
		 */
		private function get_read_forbidden_error() {
			return new WP_Error(
				'rest_forbidden',
				__( 'Sorry, you are not allowed to view layouts.', 'astra-addon' ),
				array( 'status' => rest_authorization_required_code() )
			);
		}
	}
}
