<?php

namespace WP_AUX\Entities\Components;

use WP_AUX\Entities\ComponentEntity;
use WP_AUX\Entities\Components\Traits\ComponentItemsTraits;

class BreadcrumbsEntity extends ComponentEntity {
  use ComponentItemsTraits;

  public const ELEMENT_PRIMARY_CLASS = 'breadcrumbs';

  public const ITEM_FLAG_HOME = 'home';
  public const ITEM_FLAG_CURRENT = 'current';

  public function addCrumb(string $content, string $url = '', string $flag = ''): static
  {
    $this->addItem([
      'prepend' => '',
      'content' => $content,
      'url' => $url,
      'flag' => $flag
    ]);

    return $this;
  }

  public function setHome(string $content, string $url = ''): static
  {
    $this->items['home'] = [
      'prepend' => '<svg><use href="#aux_house-chimney"></use></svg>',
      'content' => $content,
      'url' => $url,
      'flag' => static::ITEM_FLAG_HOME
    ];

    return $this;
  }

  public function renderPattern(): string
  {
    return '<nav class="%s">%s</nav>';
  }

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

    $linksElements = [];
    foreach ($this->items as $item) {
      $flagClass = $item['flag'] ? "breadcrumbs__item--{$item['flag']}" : '';

      $itemContent = $item['url'] ? sprintf('<a href="%s">%s</a>', esc_url($item['url']), esc_html($item['content'])) : esc_html($item['content']);

      $linksElements[] = sprintf(
        '<li class="breadcrumbs__item %s">%s%s</li>',
        $flagClass,
        $item['prepend'],
        $itemContent
      );
    }

    return '<ol>' . join($linksElements) . '</ol>';
  }
}
