<?php declare(strict_types=1);

namespace App\Twig\Extension;

use Exception;
use Pimcore\Model\Document;
use Pimcore\Model\Document\Link;
use Pimcore\Model\Document\Page;
use Pimcore\Navigation\Container;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class NavigationExtension extends AbstractExtension
{
    public function getFunctions(): array
    {
        return [
            new TwigFunction('extend_breadcrumbs', [$this, 'extendBreadcrumbs']),
            new TwigFunction('get_main_navigation', [$this, 'getMainNavigation']),
        ];
    }

    /**
     * @throws Exception
     */
    public function extendBreadcrumbs($navigation, $addToBreadcrumbs): ?Container
    {
        if (!$navigation instanceof Container || empty($addToBreadcrumbs->pages)) {
            return $navigation;
        }

        $activePages = $navigation->findAllBy('active', true);
        $deepestActive = end($activePages);

        foreach ($addToBreadcrumbs->pages as $key => $page) {
            $newPage = \Pimcore\Navigation\Page\Document::factory([
                'label' => $page['label'],
                'title' => $page['label'],
                'uri' => $page['url'],
                'active' => true,
            ]);
            $deepestActive->addPage($newPage);
            $deepestActive = $newPage;
        }

        return $navigation;
    }

    public function getMainNavigation(Document $rootDocument): array
    {
        $mainNav = [];
        $mainNavDocsListing = $rootDocument->getChildren();

        if (!$mainNavDocsListing->getCount()) {
            return $mainNav;
        }

        foreach ($mainNavDocsListing->getDocuments() as $mainNavDoc) {
            if (!$mainNavDoc->getProperty('hideInMainNav') && $mainNavDoc->isPublished() && ($mainNavDoc instanceof Page || $mainNavDoc instanceof Link)) {
                $mainNav[] = $mainNavDoc;
            }
        }

        return $mainNav;
    }
}
