<?php

namespace WP_AUX\Entities\PageTemplate;

use WP_AUX\Entities\PageTemplate\Traits\RenderTemplateTraits;
use WP_AUX\Entities\PageTemplateEntity;

class SidebarEntity
{
  use RenderTemplateTraits;

  public static array $supportedLayouts = ['none', 'left', 'right'];

  public PageTemplateEntity $pageTemplate;
  protected string $templateSlug = 'sidebar';

  protected string $type = 'none';

  public function __construct(PageTemplateEntity $pageTemplate)
  {
    $this->pageTemplate = $pageTemplate;
  }

  public function setFromRequest(): void
  {
    if (
      $this->pageTemplate->layout->isType("left") ||
      $this->pageTemplate->layout->isType("right")
    ) {
      $this->setType($this->pageTemplate->layout->getType());
    }
  }

  public function getType(): string
  {
    return $this->type;
  }

  public function setType(string $type): self
  {
    if (in_array($type, self::$supportedLayouts)) {
      $this->type = $type;
    }

    return $this;
  }

  public function parentLink(): string
  {
    $parentId = wp_get_post_parent_id($this->pageTemplate->getPostID());

    if (!$parentId) {
      return '';
    }

    return sprintf(
      '<a class="link--cta-leading" href="%s">Back to %s</a>',
      get_permalink($parentId),
      get_the_title($parentId),
    );
  }

  public function navMenu(bool $strict): string
  {
    $sidebarLinks = [];

    $parentId = wp_get_post_parent_id($this->pageTemplate->getPostID());

    $args = [
      'child_of' => $parentId,
      'sort_column' => 'menu_order'
    ];

    if ($strict) {
      $args['parent'] = $parentId;
    }

    $sibling_pages = get_pages($args);

    if (!$sibling_pages) {
      return '';
    }

    foreach ($sibling_pages as $page) {
      $classes = 'sidebar-nav__item sibling-page';

      if ($page->ID === $this->pageTemplate->getPostID()) {
        $classes .= ' sidebar-nav__item--current';
      }

      if (!empty($page->post_title)) {
        $sidebarLinks[] = sprintf(
          '<li class="%s"><a href="%s">%s</a></li>',
          $classes,
          get_permalink($page->ID),
          $page->post_title,
        );
      }
    }

    return sprintf('<ul class="sidebar-nav">%s</ul>', join($sidebarLinks));
  }
}
