<?php

namespace Ignite\Core\Http\ViewComposers;

use Ignite\Core\Models\Menu\NavigationMenu;
use Illuminate\Support\HtmlString;
use Illuminate\View\View;
use Ignite\Core\Contracts\Repositories\PageRepository;
use Ignite\Core\Models\Menu\Item;
use Ignite\Core\Auth\Impersonation;

class NavigationMenuComposer
{
    /**
     * The page repository implementation.
     *
     * @var PageRepository
     */
    protected $pageRepository;

    /**
     * The menu manager.
     *
     * @var NavigationMenu
     */
    protected $manager;

    /**
     * Create a new pages composer.
     *
     * @param PageRepository $pages
     * @param NavigationMenu $manager
     */
    public function __construct(PageRepository $pages, NavigationMenu $manager)
    {
        $this->pageRepository = $pages;
        $this->manager = $manager;
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $pages = $this->pageRepository->findForNavigation();
        $this->manager->merge($pages);

        if ($this->manager->has('/contact')) {
            $this->manager->get('/contact')->setPosition(1000);
        }

        if (! auth()->check()) {
            $this->manager->merge(collect($this->getUnauthenticatedItems()));
        } else {
            $this->manager->merge(collect([
                new Item(url('/participant/profile'), 'Account', 600, true, $this->getAuthenticatedItems())
            ]));
            $this->manager->remove('/enroll');
        }

        $view->with('menu', new HtmlString($this->manager->render()));
    }

    /**
     * Get the additional menu links for when a user is unauthenticated.
     *
     * @return array
     */
    protected function getUnauthenticatedItems()
    {
        return [
            new Item(url('/login'), 'Sign In', 600)
        ];
    }

    /**
     * Get the additional menu links for when a user is authenticated.
     *
     * @return array
     */
    protected function getAuthenticatedItems()
    {
        $items = [
            new Item(url('/participant/profile'), 'My Profile', 10),
            new Item(url('/transactions'), 'My Transactions', 20),
            new Item(url('/logout'), 'Sign Out', 60),
        ];

        if (auth()->user()->can('core.dashboard.browse')) {
            $items[] = new Item(url('/admin'), 'Admin', 50);
        }

        if (app(Impersonation::class)->isImpersonating()) {
            $items[] = new Item(url('/admin/unmask'), 'Unmask', 55);
        }

        return $items;
    }
}
