<?php
namespace Booktics\Admin;

if ( ! defined( 'ABSPATH' ) ) exit;

use Booktics\Contracts\Hookable_Service_Contract;
use WP_REST_Response;

/**
 * RestPermissionMessage class.
 *
 * @package Booktics/Rest_Permission_Message
 */
class Rest_Permission_Message implements Hookable_Service_Contract {
    /**
     * Register hooks
     *
     * @return  void
     */
    public function register() {
        add_filter( 'rest_request_after_callbacks', array( $this, 'modify_rest_permission_message' ), 10, 3 );
    }

    /**
     * Modify permission error message
     *
     * @return  void
     */
    public function modify_rest_permission_message( $response, $handler, $request ) {

        $namespace = $request->get_route();

        if ( strpos( $namespace, '/booktics' ) !== 0 ) {
            return $response;
        }

        if ( is_wp_error( $response ) ) {
            $error_data = $response->get_error_data();
            $status     = isset( $error_data['status'] ) ? $error_data['status'] : 401;

            return new WP_REST_Response(
                array(
					'success' => 0,
					'message' => __( 'Unauthorized user', 'booktics' ),
					'error'   => array(
						'code'    => $response->get_error_code(),
						'type'    => 'permission_error',
						'details' => $response->get_error_message(),
					),
                ), $status
            );
        }

        return $response;
    }
}
