<?php

namespace WPUF\UserDirectory\Api;

use WP_Error;
use WP_REST_Controller;

class WPUF_Pro_REST_Controller extends WP_REST_Controller {

    /**
     * The namespace of this controller's route.
     *
     * @since 4.2.0
     *
     * @var string
     */
    protected $namespace = 'wpuf/v1';

    /**
     * Get the item schema for the endpoint.
     *
     * @since 4.2.0
     *
     * @return WP_Error|bool
     */
    public function permissions_check( $request ) {
        // Nonce check
        if ( ! wp_verify_nonce( $request->get_header( 'x-wp-nonce' ), 'wp_rest' ) ) {
            return new WP_Error( 'rest_forbidden', __( 'Invalid nonce.', 'wpuf-pro' ), [ 'status' => 403 ] );
        }

        // Check if the user has permission to create items
        // Use a fallback if wpuf_admin_role() is not defined
        $admin_role = function_exists( 'wpuf_admin_role' ) ? wpuf_admin_role() : 'manage_options';
        if ( ! current_user_can( $admin_role ) ) {
            return new WP_Error( 'rest_forbidden', __( 'You do not have permission to create items.', 'wpuf-pro' ), [ 'status' => 403 ] );
        }

        return true;
    }
}
