<?php
declare(strict_types=1);

namespace AuxCF\Entities\Field\Traits;

use AuxCF\Entities\Field\ConditionalLogicConditionEntity;
use AuxCF\Entities\Field\ConditionalLogicGroupEntity;
use AuxCF\Entities\Field\ConditionalLogicSetEntity;
use AuxCF\Entities\Settings\Enum\OperatorEnum;
use WP_AUX\Services\AuxCF\FieldsService;

/**
 * Provides functionalities for constructing conditional logic for ACF fields.
 * @since 1.0.0
 */
trait FieldConditionalLogicTraits
{
  protected array $initConditionalLogic = [];
  protected ConditionalLogicSetEntity $conditionalLogicSet;

  /**
   * Default conditional logic initialization, which happens before field initialization
   *
   * Create this method in your field if you want to add conditional logic before
   * the field is initialized.
   *
   * @since 1.0.0
   */
  protected final function initConditionalLogic(): void
  {
    $this->conditionalLogicSet = ConditionalLogicSetEntity::create($this->initConditionalLogic);
  }

  /**
   * Add a condition to a field
   * @since 1.0.0
   */
  public function addCondition(
    string|ConditionalLogicConditionEntity $field,
    string|OperatorEnum|null $operator = null,
    string|null $value = null
  ): static
  {
    if ($fieldName = FieldsService::getDynamicFieldName($field, $this)) {
      $field = 'field_' . $fieldName;
    }

    $condition = new ConditionalLogicConditionEntity($field, $operator, $value);
    $conditionalLogicGroup = ConditionalLogicGroupEntity::create([$condition]);

    $this->conditionalLogicSet->addGroup($conditionalLogicGroup);

    return $this;
  }
}
