<?php

namespace ModernFields\Taxonomies\Hooks;

use ModernFields\WordPress\Interfaces\Hooks;

defined('ABSPATH') || exit;

/**
 * Reads taxonomy definitions stored in the DB and registers them with WordPress.
 *
 * Runs at `init` with a low priority so the storage CPT is already registered
 * before we query it.
 *
 * @since 1.0.0
 */
class TaxonomiesRegistration implements Hooks
{
  public function registerHooks(): void
  {
    # Priority 20 so the storage CPT (priority default 10) is ready first
    add_action('init', [$this, 'registerTaxonomies'], 20);
  }

  /**
   * Queries all published mf_taxonomy definitions and registers each one.
   */
  public function registerTaxonomies(): void
  {
    $posts = get_posts([
      'post_type'      => MODERN_FIELDS_TAXONOMIES_CPT_SLUG,
      'post_status'    => 'publish',
      'posts_per_page' => -1,
    ]);

    foreach ($posts as $post) {
      $config = $post->post_content ? json_decode($post->post_content, true) : [];
      $this->registerSingle($config);
    }
  }

  /**
   * Registers a single taxonomy from a config array.
   */
  protected function registerSingle(array $config): void
  {
    $key        = $config['key'] ?? '';
    $post_types = $config['post_types'] ?? [];

    if (empty($key) || taxonomy_exists($key)) {
      return;
    }

    $singular = $config['singular'] ?? $key;
    $plural   = $config['plural'] ?? $key;

    $labels = [
      'name'              => $plural,
      'singular_name'     => $singular,
      'search_items'      => sprintf(__('Search %s', 'modern-fields'), strtolower($plural)),
      'all_items'         => sprintf(__('All %s', 'modern-fields'), strtolower($plural)),
      'parent_item'       => sprintf(__('Parent %s', 'modern-fields'), strtolower($singular)),
      'parent_item_colon' => sprintf(__('Parent %s:', 'modern-fields'), strtolower($singular)),
      'edit_item'         => sprintf(__('Edit %s', 'modern-fields'), strtolower($singular)),
      'update_item'       => sprintf(__('Update %s', 'modern-fields'), strtolower($singular)),
      'add_new_item'      => sprintf(__('Add new %s', 'modern-fields'), strtolower($singular)),
      'new_item_name'     => sprintf(__('New %s name', 'modern-fields'), strtolower($singular)),
      'menu_name'         => $plural,
    ];

    $args = [
      'labels'            => $labels,
      'description'       => $config['description'] ?? '',
      'public'            => $config['public'] ?? true,
      'hierarchical'      => $config['hierarchical'] ?? false,
      'show_in_rest'      => $config['show_in_rest'] ?? true,
      'show_admin_column' => $config['show_admin_column'] ?? true,
      'show_tagcloud'     => $config['show_tag_cloud'] ?? true,
      'show_in_nav_menus' => $config['show_in_nav_menus'] ?? true,
    ];

    $rewrite_slug = $config['rewrite_slug'] ?? '';
    $args['rewrite'] = !empty($rewrite_slug)
      ? ['slug' => $rewrite_slug]
      : true;

    if (!empty($config['rest_base'])) {
      $args['rest_base'] = sanitize_key($config['rest_base']);
    }

    register_taxonomy($key, $post_types ?: [], $args);
  }
}
