<?php
declare(strict_types=1);

namespace AuxCF\Entities\Field;

use AuxCF\Entities\Settings\Enum\OperatorEnum;

class ConditionalLogicGroupEntity
{
  /**
   * @var ConditionalLogicGroupEntity[]
   */
  protected $conditions = [];

  public function __construct() {}

  public function addCondition(string|ConditionalLogicConditionEntity $field, string|OperatorEnum|null $operator = null, string|null $value = null): void
  {
    if ($field instanceof ConditionalLogicConditionEntity) {
      $this->conditions[] = $field;
    } else {
      $this->conditions[] = new ConditionalLogicConditionEntity($field, $operator, $value);
    }
  }

  public function hasConditions(): bool
  {
    return !empty($this->conditions);
  }

  public function getArray(): array
  {
    $array = [];

    foreach ($this->conditions as $condition) {
      $array[] = $condition->getArray();
    }

    return $array;
  }

  public static function create(array $conditions): self
  {
    $group = new self();

    foreach ($conditions as $condition) {
      if ($condition instanceof ConditionalLogicConditionEntity) {
        $group->addCondition($condition);
      } else {
        if (strpos($condition[0], 'field_') === 0) {
          $field = $condition[0];
        } else {
          $field = 'field_' . $condition[0]::$name;
        }

        $value = @$condition[2];
        if ($value instanceof \UnitEnum) {
          $value = $value->value;
        }

        $group->addCondition($field, $condition[1], $value);
      }
    }

    return $group;
  }
}
