<?php

namespace ModernFields\WordPress\Endpoints;

use ModernFields\WordPress\Interfaces\Hooks;
use ModernFields\WordPress\Traits\ChecksPermissions;

use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

/**
 * Defines the PostTypes REST API route for Modern Fields plugin.
 *
 * This file registers the `/modern-fields/v1/post-types` endpoint which
 * returns a list of custom public post types. This is used in the
 * plugin's UI for selecting locations where field groups can apply.
 *
 * @since 1.0.0
 */
class PostTypes implements Hooks
{
  use ChecksPermissions;

  /**
   * @since 1.0.0
   */
  public function registerHooks(): void
  {
    add_action('rest_api_init', [$this, 'registerRestEndpoints']);
  }

  /**
   * @since 1.0.0
   */
  public function registerRestEndpoints(): void
  {
    register_rest_route(MODERN_FIELDS_REST_NAMESPACE, '/post-types', [
      'methods'             => 'GET',
      'callback'            => [$this, 'getPostTypes'],
      'permission_callback' => [$this, 'checkPermissions'],
    ]);
  }

  /**
   * Retrieves a list of custom post types that are either public or expose an admin UI.
   *
   * @since 1.0.0
   * @return WP_REST_Response
   */
  public function getPostTypes(): WP_REST_Response
  {
    # use_block_editor_for_post_type() lives in wp-admin and is not loaded during REST.
    if (!function_exists('use_block_editor_for_post_type')) {
      require_once ABSPATH . 'wp-admin/includes/post.php';
    }

    $post_types = get_post_types([], 'objects');
    $custom_post_types = [];

    foreach ($post_types as $post_type_name => $post_type_object) {
      # Skip WordPress core/internal post types (post, page, attachment, wp_block, wp_template, nav_menu_item, …).
      if ($post_type_object->_builtin) {
        continue;
      }

      # Skip the Modern Fields field group CPT itself — it is never a field target.
      if ($post_type_name === MODERN_FIELDS_CPT_SLUG) {
        continue;
      }

      # Include post types that are publicly queryable or that expose an admin UI.
      if (!$post_type_object->public && !$post_type_object->show_ui) {
        continue;
      }

      $custom_post_types[] = [
        'slug' => $post_type_name,
        'name' => $post_type_object->label,
        # Some post types (e.g. WooCommerce orders / coupons) register no menu_icon;
        # fall back to a generic dashicon so the picker always shows an icon.
        'icon' => $post_type_object->menu_icon ?: 'dashicons-admin-post',
        # Whether the post type edits with the block editor; used to disable
        # block-editor-only positions (inspector / panel / modal / drawer).
        'hasBlockEditor' => use_block_editor_for_post_type($post_type_name),
      ];
    }

    return rest_ensure_response([
      'postTypes' => $custom_post_types,
    ]);
  }


}
