<?php
/**
 * Shared REST helpers.
 *
 * @package JOCBM
 */

namespace JOCBM\Rest;

use WP_Error;
use WP_REST_Request;

defined( 'ABSPATH' ) || exit;

/**
 * Trait RestPermissions
 */
trait RestPermissions {

	/**
	 * Capability check for editors.
	 *
	 * @return bool|WP_Error
	 */
	public function can_manage() {
		if ( ! current_user_can( 'edit_posts' ) ) {
			return new WP_Error(
				'jocbm_forbidden',
				__( 'You do not have permission to manage Blockora Morph.', 'joc-blockora-morph' ),
				array( 'status' => 403 )
			);
		}

		return true;
	}

	/**
	 * Capability check for destructive system actions.
	 *
	 * @return bool|WP_Error
	 */
	public function can_manage_options() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new WP_Error(
				'jocbm_forbidden',
				__( 'You do not have permission to reset Blockora Morph data.', 'joc-blockora-morph' ),
				array( 'status' => 403 )
			);
		}

		return true;
	}

	/**
	 * Decode JSON body field.
	 *
	 * @param WP_REST_Request $request Request.
	 * @param string          $key     Param key.
	 * @param mixed           $default Default.
	 * @return mixed
	 */
	protected function json_param( WP_REST_Request $request, string $key, $default = null ) {
		$value = $request->get_param( $key );

		if ( is_string( $value ) ) {
			$decoded = json_decode( $value, true );
			return null !== $decoded ? $decoded : $default;
		}

		return null !== $value ? $value : $default;
	}
}
