<?php
/**
 * Gutenberg-capable post types REST endpoint.
 *
 * @package JOCBM
 *
 * Copyright (C) 2026 JayOnCode
 * License: GPL-2.0-or-later
 */

namespace JOCBM\Rest;

use WP_REST_Response;
use WP_REST_Server;

defined( 'ABSPATH' ) || exit;

/**
 * Class PostTypesController
 */
final class PostTypesController {

	use RestPermissions;

	/**
	 * Register routes.
	 */
	public function register_routes(): void {
		register_rest_route(
			RestApi::NAMESPACE,
			'/post-types',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'index' ),
				'permission_callback' => array( $this, 'can_manage' ),
			)
		);
	}

	/**
	 * List post types that use the block editor.
	 */
	public function index(): WP_REST_Response {
		$types = get_post_types(
			array(
				'public' => true,
			),
			'objects'
		);

		$items = array();

		foreach ( $types as $type ) {
			if ( empty( $type->show_in_rest ) ) {
				continue;
			}

			if ( ! use_block_editor_for_post_type( $type->name ) ) {
				continue;
			}

			$items[] = array(
				'slug'  => $type->name,
				'label' => $type->labels->singular_name ?: $type->label,
			);
		}

		/**
		 * Filter Gutenberg post types exposed in Blockora Morph.
		 *
		 * @param array<int, array{slug:string,label:string}> $items Post types.
		 */
		$items = apply_filters( 'jocbm_gutenberg_post_types', $items );

		return new WP_REST_Response( array( 'items' => array_values( $items ) ), 200 );
	}
}
