<?php
/**
 * @package     DOCman
 * @copyright   Copyright (C) 2019 Timble CVBA. (http://www.timble.net)
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.joomlatools.com
 */

namespace Foliolabs\Docman\Admin;

use Foliolabs\Component\Base;
use Foliolabs\Library;

class ControllerToolbarMenubar extends Base\ControllerToolbarMenubar
{
    public static function getPages()
    {
        $manager = \Foliokit::getObject('manager');

        $t = $manager->getObject('translator');

        $canManage = function() use ($manager) {
            return $manager->getObject('com:docman.model.configs')->fetch()->canManage();
        };

        $canConfigure = function() use ($manager) {
            return $manager->getObject('com:docman.model.configs')->fetch()->canConfigure();
        };

        return [
            [
                'title' => $t('Docman Submenu Documents'),
                'page'  => 'docman-documents',
                'route' => 'component=docman&view=documents&page=docman-documents',
                'permission' => $canManage
            ],
            [
                'title' => $t('Docman Submenu Categories'),
                'page'  => 'docman-categories',
                'route' => 'component=docman&view=categories&page=docman-categories',
                'permission' => $canManage
            ],
            [
                'title' => $t('Docman Submenu Tags'),
                'page'  => 'docman-tags',
                'route' => 'component=docman&view=tags&page=docman-tags',
                'permission' => $canConfigure
            ],
            [
                'title' => $t('Docman Submenu Groups'),
                'page'  => 'docman-usergroups',
                'route' => 'component=docman&view=usergroups&page=docman-usergroups',
                'permission' => $canConfigure
            ],
            [
                'title' => $t('Docman Submenu Settings'),
                'page'  => 'docman-settings',
                'route' => 'component=docman&view=config&page=docman-settings',
                'permission' => $canConfigure
            ]
        ];
    }

    public function getCommands()
    {
        $name = $this->getController()->getIdentifier()->name;

        $user = $this->getObject('user');

        foreach (self::getPages() as $page)
        {
            parse_str($page['route'], $query);

            $query['page'] = $page['page'];

            $permission = $page['permission'] ?? 'read';

            if (is_callable($permission) ? $permission() : $user->capable($permission))
            {
                $this->addCommand($page['title'], [
                    'href'   => $page['route'],
                    'active' => isset($query['view']) && ($name == Library\StringInflector::singularize($query['view']))
                ]);
            }
        }

        return parent::getCommands();
    }
}
