<?php
declare(strict_types=1);

namespace WP_AUX\Entities\AuxFramework\Partials;

use WHOOP\Entities\Elements\Dl;
use WP_AUX\Enum\IconsEnum;
use WP_AUX\Services\AuxFramework\ElementClassesService;
use WP_AUX\Services\HtmlService;

/**
 * AUX description list entity
 * @since 1.0.0
 */
class DescriptionListEntity
{
  protected string $type = 'slim';
  protected array $items = [];

  public function __construct(string $type = 'slim') {
    $this->type = $type;
  }

  /**
   * Add a term + description item to the list
   *
   * If the term or description is empty, then the item will not be added.
   *
   * @since 1.0.0
   */
  public function addItem(
    string $term,
    string $description,
    string|IconsEnum|null $icon = null,
    array|string|null $cta = null
  ): static
  {
    if (empty($term) || empty($description)) {
      return $this;
    }

    if (!empty($icon) && !($icon instanceof IconsEnum)) {
      $icon = IconsEnum::tryFrom($icon);
    }

    $this->items[] = [
      'term' => $term,
      'description' => $description,
      'icon' => $icon,
      'cta' => $cta
    ];

    return $this;
  }

  public function setType(string $type): static
  {
    $this->type = $type;
    return $this;
  }

  public function getCount(): int
  {
    return count($this->items);
  }

  public function __toString(): string
  {
    if (empty($this->items)) {
      return '';
    }

    $dl = Dl::create();
    $dl->addClass((string) ElementClassesService::buildClasses('description-list', $this->type));

    foreach ($this->items as $item) {
      $descriptionContent = $item['description'];
      $termContent = $item['term'];

      if (!empty($item['icon'])) {
        $termContent = IconEntity::create($item['icon']) . $termContent;
      }

      if ('custom' === $this->type) {
        $descriptionContent = HtmlService::paragraph($descriptionContent);
      }

      if (!empty($item['cta'])) {
        $descriptionContent .= sprintf('<a href="%s" class="link--cta">%s</a>', $item['cta']['url'], $item['cta']['title']);
      }

      $itemContent = sprintf('<dt>%s</dt><dd>%s</dd>', $termContent, $descriptionContent);

      if ('custom' === $this->type) {
        $itemContent = sprintf('<div class="description-list__item">%s</div>', $itemContent);
      }

      $dl->append($itemContent);
    }

    return (string) $dl;
  }

  /**
   * Create a new description list entity by type
   * @since 1.0.0
   */
  public static function create(string $type = 'slim'): static
  {
    return new static($type);
  }
}
