<?php
declare(strict_types=1);

namespace WP_AUX\Entities\AuxFramework\Partials;

use WHOOP\Entities\Elements\A;
use WHOOP\Entities\Elements\Li;
use WP_AUX\Services\HtmlService;

class LinkListItemEntity
{
  protected A $anchor;
  protected ?string $description = null;
  protected ?LinkListEntity $nestedList = null;

  public function __construct(array $link) {
    $this->anchor = A::create($link['content'] ?? $link['title'], [
      'href' => $link['url'],
      'target' => !empty($link['target']) ? $link['target'] : '_self',
    ]);

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

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

  public function addNestedLink(array $link): LinkListItemEntity
  {
    if (is_null($this->nestedList)) {
      $this->nestedList = LinkListEntity::create();
      $this->nestedList->setIsNested(true);
    }

    return $this->nestedList->addLink($link);
  }

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

  public function __toString() {
    $return = (string) $this->anchor;
    $return .= HtmlService::formattedValue($this->description, '<p>%s</p>');

    if ($this->nestedList) {
      $return .= (string) $this->nestedList;
    }

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

  public static function create(array $link): static
  {
    return new static($link);
  }
}
