<?php

namespace ModernFields\FieldGroups\Repositories;

use ModernFields\FieldGroups\Entities\Field;

/**
 * Abstract class for field repositories.
 * 
 * This class is responsible for retrieving fields from the database or content.
 * 
 * @since 1.0.0
 */
abstract class FieldRepository
{
  /**
   * Retrieves indexed fields for a given field group from the database.
   *
   * Queries mf_field posts by post_parent, ordered by menu_order to preserve
   * the original field sequence.
   *
   * @since 0.6
   * @param int $group_id The mf_field_group post ID
   * @return array<Field> Ordered array of Field entities
   */
  public static function getFieldsByGroupId(int $group_id): array
  {
    $posts = get_posts([
      'post_type'      => MODERN_FIELDS_FIELD_CPT_SLUG,
      'posts_per_page' => -1,
      'post_status'    => 'publish',
      'orderby'        => 'menu_order',
      'order'          => 'ASC',
      'post_parent'    => $group_id,
    ]);

    $fields = array_map(fn(\WP_Post $post) => Field::fromDatabase($post), $posts);

    return array_values(array_filter($fields, fn(Field $field) => $field->getName() !== ''));
  }

}
