<?php
declare(strict_types=1);

namespace WP_AUX\Services\AuxCF;

use AuxCF\Entities\FieldEntity;

class FieldsService
{
  /**
   * Remove field by name from ACF fields list
   * @since 1.0.0
   */
  public static function removeFieldFromGroup(array &$fields, string|array $fieldName): void
  {
    $fieldNames = (array) $fieldName;

    foreach ($fieldNames as $fieldName) {
      foreach ($fields as $fieldKey => $fieldData) {
        if ($fieldName === $fieldData['name']) {
          unset($fields[$fieldKey]);
        }
      }
    }
  }

  /**
   * Get the name for a field that may have a dynamic name (ie: reusable fields)
   *
   * @param string|FieldEntity $fieldEntity The field or field object path string to get the name for
   * @param FieldEntity|null $fieldObject The field object to get the root wildcard string from (optional, will attempt to use the field entity if it is an abject)
   *
   * @since 1.0.0
   */
  public static function getDynamicFieldName(
    string|FieldEntity $fieldEntity,
    null|string|FieldEntity $fieldObject = null
  ): ?string
  {
    $fieldName = null;
    if (is_null($fieldObject)) {
      $fieldObject = $fieldEntity;
    }

    if (property_exists($fieldEntity, 'namePattern') && $namePattern = $fieldEntity::$namePattern) {
      if (is_string($fieldObject)) {
        $rootWildcard = $fieldObject;
      } else {
        $rootWildcard = $fieldObject->getRootWildcard();
      }

      $fieldName = sprintf($namePattern, $rootWildcard);
    } elseif ($fieldEntity instanceof FieldEntity && method_exists($fieldEntity, 'getEffectiveName')) {
      $fieldName = $fieldEntity->getEffectiveName();
    } elseif (property_exists($fieldEntity, 'name')) {
      $fieldName = $fieldEntity::$name;
    }

    return $fieldName;
  }
}
