<?php

/**
 * CMS2+ Navigation Helper Class
 * Class for generating navigation data for the cms in the frontend templates.
 * See more: http://wiki.mtcmedia.co.uk/index.php?title=CMS2#Navigation
 * @copyright MTC media Ltd
 * @author Rihards Silins
 * @version 1 07/04/2016
 */

namespace Mtc\Cms\Helpers;

use ContentManager;
use Page;

class Navigation
{
    /**
     * Navigation::getBreadcrumbTrail()
     * Generates breadcrumb trail for a page
     * @param Page Object[] $current_page
     * @return Page Object[] $trail
     */
    public static function getBreadcrumbTrail(Page $current_page)
    {
        // If it's a frontpage - return empty trail
        if ($current_page->frontpage) {
            return array();
        }
        $trail = $current_page->get_trail();
        $frontpage = new Page(ContentManager::getFrontPageId());
        array_unshift($trail, $frontpage);
        // Adjust to fit breadcrumbs.twig
        for ($i = 0; $i < count($trail); $i++) {
            $trail[$i]->name = $trail[$i]->title;
            if (
                $i == (count($trail) - 1)
                && defined('BREADCRUMBS_LINK_LAST_CRUMB')
                && BREADCRUMBS_LINK_LAST_CRUMB === false
            ) {
                $trail[$i]->url = null;
            } elseif (! empty($trail[$i]->url)) {
                // Add trailing slash
                if (substr($trail[$i]->url, -1) !== '/') {
                    $trail[$i]->url .= '/';
                }
            }
            $trail[$i] = (array) $trail[$i];
        }

        return $trail;
    }
}
