<?php
declare(strict_types=1);

namespace WP_AUX\Entities\AuxFramework\Partials;

use WHOOP\Entities\Elements\Comment;
use WHOOP\Entities\Elements\Ul;

/**
 * Represents a header utility CTAs entity that contains a collection of CTA items
 * @since 1.0.0
 */
class HeaderUtilityCtasEntity
{
  protected Ul $ul;
  protected bool $mobile = false;
  /**
   * @var HeaderUtilityCtasItemEntity[]
   */
  protected $items = [];

  public function __construct(bool $mobile = false)
  {
    $this->mobile = $mobile;
    $this->ul = Ul::create('', [
      'class' => $this->mobile ? 'cta__collection' : 'utility-nav__ctas',
    ]);
  }

  /**
   * Add a link with an array containing at least 'url' and 'title'
   * @since 1.0.0
   */
  public function addLink(array $link): ?HeaderUtilityCtasItemEntity
  {
    // Catch invalid/incomplete link and add an HTML comment in its place
    if (!is_array($link)) {
      $node = Comment::create('Invalid/incomplete link');
      $this->ul->appendElement($node);

      return null;
    }

    $item = HeaderUtilityCtasItemEntity::create($link, $this->mobile);

    $this->items[] = $item;

    return $this->ul->appendElement($item);
  }

  /**
   * If there are items, render the Quicklinks
   * @since 1.0.0
   */
  public function __toString(): string
  {
    if (empty($this->items)) {
      return '';
    }

    return (string) $this->ul;
  }

  public static function create(bool $mobile = false): static
  {
    return new static($mobile);
  }
}
