<?php
/**
 * REST request authorization.
 *
 * @package EntryFoundry
 */

namespace EntryFoundry\Core\Services\Security;

/**
 * Enforces both a WordPress capability and REST nonce.
 */
final class RestPermissionService {

	/**
	 * Required WordPress capability.
	 *
	 * @var string
	 */
	private $capability;

	/**
	 * Constructor.
	 *
	 * @param string $capability Required WordPress capability.
	 */
	public function __construct( string $capability = 'edit_posts' ) {
		$this->capability = $capability;
	}

	/**
	 * Authorize a REST request.
	 *
	 * @param \WP_REST_Request $request    REST request.
	 * @param string|null      $capability Route-specific capability, or the default.
	 * @return true|\WP_Error
	 */
	public function authorize( \WP_REST_Request $request, ?string $capability = null ) {
		$required_capability = $capability ?? $this->capability;

		if ( ! current_user_can( $required_capability ) ) {
			return new \WP_Error(
				'entryfoundry_rest_forbidden',
				__( 'You are not allowed to access EntryFoundry form data.', 'entryfoundry-pdf-builder-for-formidable-forms' ),
				array( 'status' => 403 )
			);
		}

		$nonce = $request->get_header( 'X-WP-Nonce' );

		if ( ! is_string( $nonce ) || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
			return new \WP_Error(
				'entryfoundry_rest_invalid_nonce',
				__( 'The EntryFoundry REST nonce is missing or invalid.', 'entryfoundry-pdf-builder-for-formidable-forms' ),
				array( 'status' => 403 )
			);
		}

		return true;
	}
}
