<?php

namespace Diamond;

use Core\Breadcrumb\Breadcrumb;
use Core\Compress\Minify;
use Core\Concrete\AuthFactory;
use Core\Concrete\PropelSessionHandler;
use Core\Console\Application;
use Core\Contracts\ServiceProviderInterface;
use Core\Contracts\UserAuthAwareInterface;
use Core\Logger\FileFormatter;
use Core\MailingPreparation\MailingAnchorPrepare;
use Core\MailingPreparation\MailingCook;
use Core\MailingPreparation\MailingDefaultData;
use Core\PageInterface;
use Core\Template\Template;
use Core\TwigAwareInterface;
use DebugBar\Bridge\MonologCollector;
use DebugBar\Bridge\NamespacedTwigProfileCollector;
use DebugBar\Bridge\Propel2Collector;
use DebugBar\Bridge\Twig\TimeableTwigExtensionProfiler;
use DebugBar\StandardDebugBar;
use Diamond\Application\Mailing\MailingFactory;
use Diamond\Application\Mailing\MailingRecipientsCollection;
use Diamond\Application\Notification\SendSms\SendSmsCommand;
use Diamond\Application\Notification\SendSms\SendSmsHandler;
use Diamond\Application\User\UserService;
use Diamond\Config\Counters;
use Diamond\Config\Mail;
use Diamond\Config\Main;
use Diamond\Console\MailingCommand;
use Diamond\Console\SystemNotificationCommand;
use Diamond\Controllers\AdminController;
use Diamond\Controllers\FileManagerController;
use Diamond\Controllers\MailingController;
use Diamond\Controllers\MenuController;
use Diamond\Controllers\ServiceController;
use Diamond\Controllers\StatController;
use Diamond\Application\Notification\SendEmail\SendEmailCommand;
use Diamond\Application\Notification\SendEmail\SendEmailHandler;
use Diamond\Controllers\SystemController;
use Diamond\Infrastructure\Cache\StaticCache;
use Diamond\Infrastructure\Logging\DuplicateQueryLogger;
use Diamond\Infrastructure\Logging\RuntimeLogger;
use League\Container\Container;
use League\Container\ServiceProvider\AbstractServiceProvider;
use League\Container\ServiceProvider\BootableServiceProviderInterface;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Propel\Runtime\Propel;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerAwareInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\RedisSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Twig\Cache\FilesystemCache;
use Twig\Environment;

/**
 * Description of SystemServiceProvider
 *
 * @author Dmitriy
 */
class ServiceProvider extends AbstractServiceProvider implements
    BootableServiceProviderInterface, ServiceProviderInterface
{

    protected $provides = [
        'admin_path',
        'diamond.views_path',
        AuthFactory::class,
        Request::class,
        Logger::class,
        Template::class,
        StandardDebugBar::class,
        Breadcrumb::class,
        Session::class,
        Main::class,
        MailingCook::class,
        Application::class,
        Environment::class
    ];

    /**
     * @return array
     */
    public static function getCommandBusMap(): array
    {
        return [
            SendEmailCommand::class => [SendEmailHandler::class, 'handle'],
            SendSmsCommand::class => [SendSmsHandler::class, 'handle'],
        ];
    }

    /**
     * @return string
     */
    public static function getPackageName(): string
    {
        return 'diamond';
    }

    /**
     * @return string
     */
    public static function getViewsPath(): string
    {
        return __DIR__ . '/Views/';
    }

    /**
     * @return array
     */
    public static function getRoutes(): array
    {
        return [
            //[['GET', 'POST'], ADMIN_PATH . '/auth', [IndexController::class, 'index']],
            [['GET', 'POST'], ADMIN_PATH . '[/{more:.*}]', [AdminController::class, 'index']],
            [['GET'], '/_service/diamond/system/helthcheck', [SystemController::class, 'helthCheck']],
            [['GET'], '/_service/diamond/stat/requests', [StatController::class, 'requests']],
            [['GET', 'POST'], '/_service/diamond/stat/performance', [StatController::class, 'performance']],
            [['GET'], '/_service/diamond/stat/errors', [StatController::class, 'errors']],
            [['GET'], '/_service/diamond/stat/mail_requests', [StatController::class, 'mailRequests']],


            [['GET'], '/_service/diamond/menu', [MenuController::class, 'index']],
            [['GET'], '/_service/compress', [ServiceController::class, 'compress']],
            [['GET', 'POST'], '/_diamond/widgets/assets/jquery/filemanager/[{more:.*}]', [FileManagerController::class, 'action']],
            [['GET'], '/_service/diamond/mailing/ping_image_{id}', [MailingController::class, 'pingImage']],
            [['PUT'], '/_service/diamond/admin/checked', [AdminController::class, 'checked']],
            [['POST'], '/_service/diamond/settings/sendmail', [MailingController::class, 'sendMail']],
        ];
    }

    public static function getConsoleCommandMap(): array
    {
        return [
            MailingCommand::class,
            SystemNotificationCommand::class
        ];
    }


    public function register()
    {
        $this->getContainer()->defaultToShared();

        //create mailer
        $this->getContainer()->share(\Nette\Mail\FallbackMailer::class, function () {
            /**
             * @var MailingFactory $factory
             */
            $factory = $this->getContainer()->get(MailingFactory::class);
            return $factory->buildFallbackMailer();
        });

        /**
         * Configs
         */
        $this->getContainer()->share(Main::class);
        $this->getContainer()->share(Mail::class);
        $this->getContainer()->share(Counters::class);

        $this->getContainer()->share(Minify::class, function () {
            return new Minify(BASEPATH . '/public_html', '/cache/');
        });

        /**
         * set Request
         */
        $this->getContainer()->share(Request::class, Request::createFromGlobals());

        /**
         * set Monolog
         */
        $this->getContainer()->share(Logger::class)
            ->addArgument('defaultLogger')
            ->addMethodCall('pushHandler', [
                (new StreamHandler(sprintf(
                    BASEPATH . '/app/logs/errors_%s.log',
                    date('Y_m_d')
                ), Logger::ERROR)
                )
                    ->setFormatter(
                        new FileFormatter()
                    )
            ]);


        $this->getContainer()->share(PropelSessionHandler::class, function () {
            return (new PropelSessionHandler(
                sprintf(
                    'mysql:host=%s;dbname=%s',
                    getenv('DB_HOST'),
                    getenv('DB_NAME')
                ),
                [
                    'db_username' => getenv('DB_USER'),
                    'db_password' => getenv('DB_PASS')
                ]
            ));
        });

        $this->getContainer()->share(RedisSessionHandler::class, function () {
            $redis = new \Predis\Client([
                'host' => getenv('REDIS_HOST'),
                'port' => getenv('REDIS_PORT'),
            ]);
            $redis->select(getenv('REDIS_DATABASE'));
            $lifetime = $this->getContainer()->get(Main::class)->getSessionLife();
            return (new RedisSessionHandler($redis, [
                'ttl' => $lifetime * 60 * 60
            ]));
        });


        /**
         * Адаптер сессии + настройки жизни из конфига
         * set AuthFactory
         */
        $this->getContainer()->share(AuthFactory::class, function () {
            return new AuthFactory($_COOKIE);
        });

        /**
         * set Debug bar
         */
        $this->getContainer()->share(Session::class, function () {
            $lifetime = $this->getContainer()->get(Main::class)->getSessionLife();
            $request = $this->getContainer()->get(Request::class);
            if (!$lifetime) {
                $lifetime = 1;//час
            }
            //@todo регулирование жизни (30дней) повышенной сессии можно вынести в настройки
            //@todo Убрать отсюда в инфраструктуру
            if ((int)$request->cookies->get('remember') === 1) {
                $lifetime = 24 * 30;
            }

            if (getenv('REDIS_HOST')) {
                $sessionHandler = $this->getContainer()->get(RedisSessionHandler::class);
            } else {
                $sessionHandler = $this->getContainer()->get(PropelSessionHandler::class);
            }

            return new Session(
                new NativeSessionStorage([
                    'cookie_lifetime' => $lifetime * 60 * 60 * 10,
                    'gc_maxlifetime' => $lifetime * 60 * 60
                ], $sessionHandler)
            );
        });

        /**
         * singliton BreadCrumbs
         */
        $this->getContainer()->share(Breadcrumb::class);
        $this->getContainer()->share(Application::class);

        $container = $this->getContainer();
        $profile = new \Twig\Profiler\Profile();


        /**
         * set Template
         */
        $this->getContainer()->share(Template::class);

        //для вывода логово в панели отладки
        $log = new RuntimeLogger('runtime');
        $log->pushHandler(new \Monolog\Handler\StreamHandler('php://stdout', \Monolog\Logger::DEBUG));

        //для вывода логов базы
        $propelLogger = new DuplicateQueryLogger('defaultLogger');

        $this->getContainer()->share(RuntimeLogger::class,$log);
        $this->getContainer()->share(DuplicateQueryLogger::class,$propelLogger);
        $this->getLeagueContainer()->share(StaticCache::class);

        /**
         * set Propel2 Logger
         */
        Propel::getServiceContainer()->setLogger('defaultLogger', $propelLogger);

        /**
         * set Debug bar
         */
        $this->getContainer()->share(StandardDebugBar::class, function () use ($profile, $log) {



            $debugBar = new \Core\Concrete\StandardDebugBar();

            if (getenv('MODE') === 'dev') {


                $debugBar->addCollector(
                    new Propel2Collector(Propel::getConnection())
                );
                $debugBar->addCollector(
                    new MonologCollector($log)
                );

                $debugBar->addCollector(
                    new NamespacedTwigProfileCollector($profile)
                );

            }


            return $debugBar;
        });


        /**
         * set Twig
         * @todo Выделить в класс
         */
        $this->getContainer()->share(Environment::class, static::buildTwig($profile, $container));

//        $this->getContainer()->share(CustomerEmailFinderInterface::class,function (){
//            return new CustomerFinder();
//        });

        $this
            ->getContainer()
            ->share(MailingCook::class)
            ->addMethodCall('addDriver', [
                $this->getContainer()->get(MailingDefaultData::class)
            ])
            ->addMethodCall('addDriver', [
                $this->getContainer()->get(MailingAnchorPrepare::class)
            ]);


        $this
            ->getContainer()
            ->share(MailingRecipientsCollection::class)
            ->addMethodCall('push', [
                $this
                    ->getContainer()->get(UserRecipients::class)
            ]);

    }

    /**
     * @param \Twig\Profiler\Profile $profile
     * @return Environment
     */
    public static function buildTwig(\Twig\Profiler\Profile $profile, Container $container): Environment
    {

        $env = new Environment(
            new \Twig\Loader\FilesystemLoader(),
            [
                'cache' => new FilesystemCache(BASEPATH . '/app/cache/twig'),
                /**
                 * auto_reload: При разработке с Twig, полезно повторно компилировать шаблон при изменении кода-исходника.
                 * Если вы не установили значение опции auto_reload, то она будет определена автоматически на основании переменной debug.
                 */
                "auto_reload" => true,
                'debug' => strtoupper(getenv('MODE')) === 'DEV'
            ]
        );

        $env
            ->addExtension(
                new TwigExtensions()
            );
        $env->addExtension(
            new TimeableTwigExtensionProfiler(
                $profile, $container->get(StandardDebugBar::class)['time']
            )
        );

        return $env;
    }

    /**
     *
     */
    public function boot()
    {

        $this->getContainer()
            ->inflector(\Core\Contracts\RequestAwareInterface::class)
            ->invokeMethod('setRequest', [Request::class]);

        /**
         * inflector interfaces
         */
        $this->getContainer()->inflector(LoggerAwareInterface::class)
            ->invokeMethod('setLogger', [Logger::class]);

        $this->getContainer()->inflector(PageInterface::class)
            ->invokeMethod('setDebugbar', [StandardDebugBar::class]);

        $this->getContainer()->inflector(TwigAwareInterface::class)
            ->invokeMethod('setTwig', [Environment::class]);

        $this->getContainer()->inflector(UserAuthAwareInterface::class)
            ->invokeMethod('setUserAuthService', [UserService::class]);


    }

    public function afterInit(ContainerInterface $container): void
    {
    }

    public static function getPermissions(): array
    {
        return [
            // Главная -------------------------------
            'diamond.dashboard.read' => [
                'tab' => 'CMS - Главная',
                'label' => 'Чтение',
                'order' => 1
            ],
            // Профиль  -------------------------------
            'diamond.profile.read' => [
                'tab' => 'CMS - Профиль',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.profile.update' => [
                'tab' => 'CMS - Профиль',
                'label' => 'Изменение',
                'order' => 1
            ],
            'diamond.profile_info.read' => [
                'tab' => 'CMS - Профиль - Новости',
                'label' => 'Чтение',
                'order' => 1
            ],
            // Рассылка  -------------------------------
            'diamond.mailing.read' => [
                'tab' => 'CMS - Рассылка - Задания рассылки',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.mailing_templates.read' => [
                'tab' => 'CMS - Рассылка - Шаблоны',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.mailing_master.read' => [
                'tab' => 'CMS - Рассылка - Мастер рассылки',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.mailing_subscribers.read' => [
                'tab' => 'CMS - Рассылка - Подписчики',
                'label' => 'Чтение',
                'order' => 1
            ],
            // Гостевая книга  -------------------------------
            'diamond.books.read' => [
                'tab' => 'CMS - Гостевая книга - Книги',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.book_items.read' => [
                'tab' => 'CMS - Гостевая книга - Отызы',
                'label' => 'Чтение',
                'order' => 1
            ],
            // Контент  -------------------------------
            'diamond.content_pages.read' => [
                'tab' => 'CMS - Контент - Страницы',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.content_archive_pages.read' => [
                'tab' => 'CMS - Контент - Архивные страницы',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.content_contents.read' => [
                'tab' => 'CMS - Контент - Материалы',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.content_categories.read' => [
                'tab' => 'CMS - Контент - Разделы материалов',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.content_tags.read' => [
                'tab' => 'CMS - Контент - Теги материалов',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.promoblocks.read' => [
                'tab' => 'CMS - Контент - Промоблоки',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.menu.read' => [
                'tab' => 'CMS - Контент - Навигация',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.sliders.read' => [
                'tab' => 'CMS - Контент - Слайдеры',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.filemanager.read' => [
                'tab' => 'CMS - Контент - Менеджер файлов',
                'label' => 'Чтение',
                'order' => 1
            ],
            // Система  -------------------------------
            'diamond.system_users.read' => [
                'tab' => 'CMS - Система - Пользователи',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.system_users_groups.read' => [
                'tab' => 'CMS - Система - Роли пользователей',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.system_logs.read' => [
                'tab' => 'CMS - Система - Логи',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.email_requests.read' => [
                'tab' => 'CMS - Система - Логи писем',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.system_seo.read' => [
                'tab' => 'CMS - Система - Трафик',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.system_performance.read' => [
                'tab' => 'CMS - Система - Нагрузка на сайт',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.system_stat_chart.read' => [
                'tab' => 'CMS - Система - График посещений',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.system_stat_rules.read' => [
                'tab' => 'CMS - Система - Правила блокировки ресурсов',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.system_stat_bans.read' => [
                'tab' => 'CMS - Система - Заблокированные ресурсы',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.system_info_php.read' => [
                'tab' => 'CMS - Система - Информация о php',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.system_test.read' => [
                'tab' => 'CMS - Система - Проверка системы',
                'label' => 'Чтение',
                'order' => 1
            ],
            // Настройки  -------------------------------
            'diamond.settings_report.read' => [
                'tab' => 'CMS - Настройки - Шаблоны уведомлений',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.settings_templates.read' => [
                'tab' => 'CMS - Настройки - Шаблоны сайта',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.settings_domains.read' => [
                'tab' => 'CMS - Настройки - Домены',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.settings_main.read' => [
                'tab' => 'CMS - Конфигурация - Основные',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.settings_counters.read' => [
                'tab' => 'CMS - Конфигурация - Счетчики',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.settings_seo.read' => [
                'tab' => 'CMS - Конфигурация - Сео',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.settings_email.read' => [
                'tab' => 'CMS - Конфигурация - Установки почты',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.settings_content.read' => [
                'tab' => 'CMS - Конфигурация - Контент',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.settings_mailing.read' => [
                'tab' => 'CMS - Конфигурация - Рассылка',
                'label' => 'Чтение',
                'order' => 1
            ],
            'diamond.settings_other.read' => [
                'tab' => 'CMS - Конфигурация - Прочее',
                'label' => 'Чтение',
                'order' => 1
            ],
        ];
    }

    public static function getControllerPermissions(): array
    {

        return [
            admin_path('/diamond/settings/other') => [
                'diamond.settings_other.read'
            ],
            admin_path('/diamond/settings/mailing') => [
                'diamond.settings_mailing.read'
            ],
            admin_path('/diamond/settings/content') => [
                'diamond.settings_content.read'
            ],
            admin_path('/diamond/settings/email') => [
                'diamond.settings_email.read'
            ],
            admin_path('/diamond/settings/seo') => [
                'diamond.settings_seo.read'
            ],
            admin_path('/diamond/settings/counters') => [
                'diamond.settings_counters.read'
            ],
            admin_path('/diamond/settings/main') => [
                'diamond.settings_main.read'
            ],
            admin_path('/diamond/system/domains') => [
                'diamond.settings_domains.read'
            ],
            admin_path('/diamond/system/templates') => [
                'diamond.settings_templates.read'
            ],
            admin_path('/diamond/system/report') => [
                'diamond.settings_report.read'
            ],
            admin_path('/diamond/system/system_test') => [
                'diamond.system_test.read'
            ],
            admin_path('/diamond/system/info_php') => [
                'diamond.system_info_php.read'
            ],
            admin_path('/diamond/seo/stat_bans') => [
                'diamond.system_stat_bans.read'
            ],
            admin_path('/diamond/seo/stat_rules') => [
                'diamond.system_stat_rules.read'
            ],
            admin_path('/diamond/seo/stat-chart') => [
                'diamond.system_stat_chart.read'
            ],
            admin_path('/diamond/system/performance') => [
                'diamond.system_performance.read'
            ],
            admin_path('/diamond/seo/stat') => [
                'diamond.system_seo.read'
            ],
            admin_path('/diamond/system/logs') => [
                'diamond.system_logs.read'
            ],
            admin_path('/diamond/system/user-groups') => [
                'diamond.system_users_groups.read'
            ],
            admin_path('/diamond/system/users') => [
                'diamond.system_users.read'
            ],
            admin_path('/diamond/content/filemanager') => [
                'diamond.filemanager.read'
            ],
            admin_path('/diamond/content/sliders') => [
                'diamond.sliders.read'
            ],
            admin_path('/diamond/content/menu') => [
                'diamond.menu.read'
            ],
            admin_path('/diamond/content/promoblock') => [
                'diamond.promoblocks.read'
            ],
            admin_path('/diamond/content/content-tags') => [
                'diamond.content_tags.read'
            ],
            admin_path('/diamond/content/categories') => [
                'diamond.content_categories.read'
            ],
            admin_path('/diamond/content/content') => [
                'diamond.content_contents.read'
            ],
            admin_path('/diamond/content/pages-archive') => [
                'diamond.content_archive_pages.read'
            ],
            admin_path('/diamond/content/pages') => [
                'diamond.content_pages.read'
            ],
            admin_path('/diamond/content/book-items') => [
                'diamond.book_items.read'
            ],
            admin_path('/diamond/content/books') => [
                'diamond.books.read'
            ],
            admin_path('/diamond/mailing/mailing_subscribers') => [
                'diamond.mailing_subscribers.read'
            ],
            admin_path('/diamond/mailing/mailing_master') => [
                'diamond.mailing_master.read'
            ],
            admin_path('/diamond/mailing/mailing_templates') => [
                'diamond.mailing_templates.read'
            ],

            admin_path('/diamond/mailing/mailing') => [
                'diamond.mailing.read'
            ],
            admin_path('/diamond/mailing/mailing_list_report') => [
                'diamond.mailing.read'
            ],
            admin_path('/diamond/mailing/mailing_list_demo') => [
                'diamond.mailing.read'
            ],

            admin_path() => [
                'diamond.dashboard.read'
            ],
            admin_path('/diamond/system/dashboard') => [
                'diamond.dashboard.read'
            ],
            admin_path('/diamond/profile/main') => [
                'diamond.profile.read', 'diamond.profile.update'
            ],
            admin_path('/diamond/profile/info') => [
                'diamond.profile_info.read'
            ],

            admin_path('/diamond/system/email_requests') => [
                'diamond.email_requests.read'
            ]
        ];
    }

    public static function getAdminNavigation(): array
    {
        return [
            'CMS' => [
                'home' => [
                    'label' => 'Главная',
                    'url' => admin_path('/diamond/system/dashboard'),
                    'related' => [admin_path()],
                    'icon' => 'fa fa-home'
                ],
                'mailing' => [
                    'label' => 'Рассылка',
                    'url' => admin_path('/diamond/mailing/mailing'),
                    'icon' => 'fa fa-envelope',
                    'related' => [
                        admin_path('/diamond/mailing/mailing_templates'),
                        admin_path('/diamond/mailing/mailing_master'),
                        admin_path('/diamond/mailing/mailing_subscribers')
                    ]
                ],
                'guest-book' => [
                    'label' => 'Гостевая книга',
                    'url' => admin_path('/diamond/content/books'),
                    'icon' => 'fa fa-book',
                    'related' => [admin_path('/diamond/content/book-items')]
                ],
                'content' => [
                    'label' => 'Контент',
                    'icon' => 'fa fa-file-text-o',
                    'items' => [
                        'pages' => [
                            'label' => 'Страницы сайта',
                            'url' => admin_path('/diamond/content/pages'),
                            'related' => [
                                admin_path('/diamond/content/pages-archive')
                            ]
                        ],
                        'stories' => [
                            'label' => 'Материалы',
                            'url' => admin_path('/diamond/content/content'),
                            'related' => [
                                admin_path('/diamond/content/categories'),
                                admin_path('/diamond/content/content-tags')
                            ]
                        ],
                        'promoblocks' => [
                            'label' => 'Промоблоки',
                            'url' => admin_path('/diamond/content/promoblock')
                        ],
                        'menu' => [
                            'label' => 'Навигация',
                            'url' => admin_path('/diamond/content/menu')
                        ],
                        'sliders' => [
                            'label' => 'Слайдеры',
                            'url' => admin_path('/diamond/content/sliders')
                        ],
                        'filemanager' => [
                            'label' => 'Менеджер файлов',
                            'url' => admin_path('/diamond/content/filemanager')
                        ],
                    ]
                ],
                'system' => [
                    'label' => 'Система',
                    'icon' => 'demo-psi-bar-chart',
                    'items' => [
                        'users' => [
                            'label' => 'Пользователи',
                            'url' => admin_path('/diamond/system/users'),
                            'related' => [admin_path('/diamond/system/user-groups')]
                        ],
                        'logs' => [
                            'label' => 'Логи',
                            'url' => admin_path('/diamond/system/logs')
                        ],
                        'message_request' => [
                            'label' => 'Лог отправки писем',
                            'url' => admin_path('/diamond/system/email_requests'),
                            'related' => [
                                admin_path('/diamond/system/email_requests_chart'),
                            ]
                        ],
                        'performance' => [
                            'label' => 'Трафик',
                            'url' => admin_path('/diamond/seo/stat'),
                            'related' => [
                                admin_path('/diamond/system/performance'),
                                admin_path('/diamond/seo/stat-chart'),
                                admin_path('/diamond/seo/stat_rules'),
                                admin_path('/diamond/seo/stat_bans'),
                            ]
                        ],
                        'info_php' => [
                            'label' => 'Информация о php',
                            'url' => admin_path('/diamond/system/info_php')
                        ],
                        'system_test' => [
                            'label' => 'Проверка системы',
                            'url' => admin_path('/diamond/system/system_test')
                        ],
                    ]
                ],

                'settings' => [
                    'label' => 'Настройки',
                    'icon' => 'fa fa-gear',
                    'items' => [
                        'reports' => [
                            'label' => 'Шаблоны уведомлений',
                            'url' => admin_path('/diamond/system/report')
                        ],
                        'templates' => [
                            'label' => 'Шаблоны сайта',
                            'url' => admin_path('/diamond/system/templates')
                        ],
                        'domains' => [
                            'label' => 'Домены',
                            'url' => admin_path('/diamond/system/domains')
                        ],
                        'settings-main' => [
                            'label' => 'Конфигурация',
                            'url' => admin_path('/diamond/settings/main'),
                            'related' => [
                                admin_path('/diamond/settings/email'),
                                admin_path('/diamond/settings/counters'),
                                admin_path('/diamond/settings/seo'),
                                admin_path('/diamond/settings/other'),
                                admin_path('/diamond/settings/content'),
                                admin_path('/diamond/settings/mailing')
                            ]
                        ]
                    ]
                ]
            ]
        ];
    }

}