<?php

namespace WP_AUX\Entities;

class ValuesListEntity {
  public array $data;
  protected string $displayKey = '';
  protected string $separator = ' ';
  protected string $itemTag = '';
  protected string $itemClasses = '';
  protected string $wrapper = '';

  public function __construct(array $data, string $displayKey = '')
  {
    $this->data = $data;
    $this->displayKey = $displayKey;
  }

  public function setDisplayKey(string $displayKey): self
  {
    $this->displayKey = $displayKey;

    return $this;
  }

  public function setSeparator(string $separator): self
  {
    $this->separator = $separator;

    return $this;
  }

  public function setItemTag(string $itemTag): self
  {
    $this->itemTag = $itemTag;

    return $this;
  }

  public function setWrapper(string $wrapper): self
  {
    $this->wrapper = $wrapper;

    return $this;
  }

  protected function itemDisplayValue($dataValue): string
  {
    if (empty($this->displayKey)) {
      return (string) $dataValue;
    }

    $dataValueArray = (array) $dataValue;

    return (string) $dataValueArray[$this->displayKey] ?? '';
  }

  public function __toString(): string
  {
    $itemsString = '';

    if (!empty($this->data)) {
      $items = [];

      foreach ($this->data as $dataKey => $dataValue) {
        $displayValue = $this->itemDisplayValue($dataValue);

        if ($this->itemTag) {
          $items[] = sprintf('<%s class="%s">%s</%s>', $this->itemTag, $this->itemClasses, $displayValue, $this->itemTag);
        } else {
          $items[] = $displayValue;
        }
      }

      $itemsString = join($this->separator, $items);

      if (!empty($this->wrapper)) {
        $itemsString = sprintf($this->wrapper, $itemsString);
      }
    }

    return $itemsString;
  }
}
