<?php
/**
 * REST API bootstrap — registers all endpoint controllers.
 *
 * @since 1.0.0
 */

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

class ZINV_REST_API {

	private const NAMESPACE = 'zoventic-invoices/v1';

	public static function register_routes(): void {
		$controllers = [
			'ZINV_REST_Clients',
			'ZINV_REST_Invoices',
			'ZINV_REST_Estimates',
			'ZINV_REST_Payments',
			'ZINV_REST_Dashboard',
			'ZINV_REST_Settings',
			'ZINV_REST_Users',
			'ZINV_REST_Onboarding',
			'ZINV_REST_Pro_Stubs',
		];

		$ns = self::NAMESPACE;
		foreach ( $controllers as $controller ) {
			if ( class_exists( $controller ) ) {
				$instance = new $controller( $ns );
				$instance->register();
			}
		}

		// Nonce refresh endpoint.
		register_rest_route( $ns, '/nonce', [
			'methods'             => 'GET',
			'callback'            => [ __CLASS__, 'get_nonce' ],
			'permission_callback' => function () {
				return current_user_can( 'zinv_view_dashboard' )
					|| current_user_can( 'zinv_manage_clients' )
					|| current_user_can( 'zinv_manage_invoices' )
					|| current_user_can( 'zinv_manage_settings' );
			},
		] );
	}

	public static function get_nonce(): WP_REST_Response {
		return new WP_REST_Response( [
			'nonce' => wp_create_nonce( 'wp_rest' ),
		] );
	}

	protected static function get_namespace(): string {
		return self::NAMESPACE;
	}
}
