<?php
declare(strict_types=1);

namespace WP_AUX\Entities\AuxFramework\Partials;

use WHOOP\Entities\Elements\A;

class ButtonEntity
{
  protected ?ButtonGroupEntity $buttonGroup = null;
  protected A $button;
  protected bool $useIcon = true;
  protected ?string $icon = null;
  protected ?string $modifier = null;

  public function __construct(array $link, ?ButtonGroupEntity $buttonGroup = null) {
    $this->buttonGroup = $buttonGroup;
    $this->prepareButton($link);
  }

  public function setUseIcon(bool $useIcon): static
  {
    $this->useIcon = $useIcon;
    return $this;
  }

  public function prepareButton(array $link): void
  {
    $linkContent = $link['title'];

    $this->button = A::create($linkContent, [
      'href' => $link['url'],
      'class' => 'btn',
    ]);

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

    $buttonClass = '';
    if ($this->buttonGroup) {
      if ($this->buttonGroup::$mode) {
        $buttonClass .= 'btn--' . $this->buttonGroup::$mode;
      }
    }

    if ($this->modifier) {
      $buttonClass .= '-'.$this->modifier;
    }

    if ($buttonClass) {
      $this->button->addClass($buttonClass);
    }
  }

  public function getButton(): A
  {
    return $this->button;
  }

  public function __toString(): string
  {
    $button = clone $this->button;

    if ($this->icon && $this->useIcon) {
      $button->setContent($button->getContent() . IconEntity::create($this->icon, false));
    }

    return (string) $button;
  }

  public static function create(array $link, ?ButtonGroupEntity $buttonGroup = null): static
  {
    return new static($link, $buttonGroup);
  }
}
