<?php

namespace WP_AUX\Services\PageTemplate;

use WP_AUX\Entities\Components\BreadcrumbsEntity;
use WP_AUX\Services\PostService;

class LayoutService
{
  public static function breadcrumbs(): BreadcrumbsEntity
  {
    $auxBreadcrumbs = BreadcrumbsEntity::create();

    $auxBreadcrumbs->setHome(__('Home', 'text-domain'), home_url('/'));

    // Get the current post/page information
    $currentObject = get_queried_object();

    if (is_archive()) {
      $auxBreadcrumbs->addCrumb( get_post_type_labels($currentObject)->name, '', BreadcrumbsEntity::ITEM_FLAG_CURRENT );
    } else {
      if (is_single($currentObject) && !in_array($currentObject->post_type, ['post', 'page'])) {
        $auxBreadcrumbs->addCrumb(
          PostService::getTypeLabelForPost($currentObject),
          get_post_type_archive_link($currentObject->post_type)
        );
      }

      if ($ancestorIds = get_post_ancestors($currentObject)) {
        $ancestorIds = array_reverse($ancestorIds);

        foreach ($ancestorIds as $ancestorId) {
          $ancestor = get_post($ancestorId);
          $auxBreadcrumbs->addCrumb( get_the_title($ancestor), get_the_permalink($ancestor) );
        }
      }

      $auxBreadcrumbs->addCrumb( get_the_title($currentObject), '', BreadcrumbsEntity::ITEM_FLAG_CURRENT );
    }

    return $auxBreadcrumbs;
  }
}
