<?php
declare(strict_types=1);

namespace AuxCF\Entities\Field\Traits;

/**
 * Provides functionalities for constructing the array representation of ACF fields.
 * This trait includes methods to define and merge base, custom, and additional properties.
 *
 * @since 1.0.0
 */
trait FieldArrayTraits
{
  /**
   * Creates the base array of common properties for all fields in ACF
   *
   * This method cannot be overidden by child classes.
   *
   * @since 1.0.0
   */
  protected final function getBaseArray(): array
  {
    return [
      'key' => $this->key,
      'label' => $this->label,
      'name' => $this->getEffectiveName(),
      'type' => $this->type->value,
      'instructions' => $this->instructions,
      'required' => $this->required->value,
      'conditional_logic' => isset($this->conditionalLogicSet) ? $this->conditionalLogicSet->getValueForField() : [],
      'wrapper' => $this->wrapper,
      'default_value' => (is_object($this->defaultValue)) ? $this->defaultValue->value : $this->defaultValue,
    ];
  }

  /**
   * Default implementation of the getFieldArray method. Child classes may provide their own implementation
   * to provide additional properties for the ACF field configuration.
   *
   * @since 1.0.0
   */
  protected function getFieldArray(): array
  {
    return [];
  }

  /**
   * Get an array of all properties for the ACF field configuration. The base array is merged
   * with the field array, and then additional properties for the field type are merged in.
   *
   * @since 1.0.0
   * @see \AuxCF\Entities\FieldEntity::$arrayPropertiesMethods
   */
  public final function getArray(): array
  {
    $array = array_replace_recursive($this->getBaseArray(), $this->getFieldArray());

    if (property_exists(static::class, 'arrayPropertiesMethods') && !empty(static::$arrayPropertiesMethods)) {
      foreach (static::$arrayPropertiesMethods as $method) {
        $array = array_replace_recursive($array, $this->{$method}());
      }
    }

    return $array;
  }
}
