<?php
declare(strict_types=1);

namespace WP_AUX\Entities\AuxFramework\Partials;

use WHOOP\Entities\Elements\A;
use WHOOP\Entities\Elements\Node;

/**
 * A single header utility nav item entity
 * @since 1.0.0
 */
class HeaderUtilityNavItemEntity
{
  protected HeaderUtilityNavEntity $parent;
  protected A $anchor;
  protected ?string $description = null;

  public function __construct(array $link, HeaderUtilityNavEntity $parent) {
    $this->parent = $parent;

    $this->anchor = A::create('', [
      'href' => $link['url'],
      'class' => $this->parent->getItemClass(),
      'target' => !empty($link['target']) ? $link['target'] : '_self',
    ]);

    $this->anchor->appendElement(Node::create($link['content'] ?? $link['title']));

    if (!empty($link['description'])) {
      $this->description = $link['description'];
    }

    if (!empty($link['rel'])) {
      $this->anchor->setAttribute('rel', $link['rel']);
    }

    if (!empty($link['id'])) {
      $this->anchor->setAttribute('id', $link['id']);
    }
  }

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

  public function __toString() {
    $anchor = clone $this->anchor;

    if ($this->description && $this->parent->getItemAllowDescription()) {
      $anchor->append('<span class="' . $this->parent->getItemClass() . '__description">'.$this->description.'</span>');
    }

    return '<li>' . $anchor . '</li>';
  }

  /**
   * Create a header utility nav item with an array consisting at least of 'url' and 'title'
   * @since 1.0.0
   */
  public static function create(array $link, HeaderUtilityNavEntity $parent): static
  {
    return new static($link, $parent);
  }
}
