<?php

// src/EventListener/MenuBuilderListener.php

namespace App\EventListener;

use App\Entity\GlobalParameter;
use App\Entity\SolidoumeParameter;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Menu\Util\MenuManipulator;
use Sonata\AdminBundle\Event\ConfigureMenuEvent;
use Symfony\Component\Security\Core\Security;

final class MenuBuilderListener
{
    private $em;
    private $security;

    public function __construct(EntityManagerInterface $em, Security $security)
    {
        $this->em = $em;
        $this->security = $security;
    }

    public function addMenuItems(ConfigureMenuEvent $event): void
    {
        $menu = $event->getMenu();

        if ($this->security->isGranted('ROLE_ADMIN_HELLOASSO_ALL') || $this->security->isGranted('ROLE_SUPER_ADMIN') || $this->security->isGranted('ROLE_ADMIN_HELLOASSO_LIST')) {
            $useHelloasso = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_HELLOASSO);
            if ('true' == $useHelloasso) {
                $child = $menu->addChild('helloasso', [
                    'label' => 'HelloAsso',
                    'route' => 'helloasso_list',
                ])->setExtras([
                    'icon' => '<i class="fa fa-bookmark-o"></i>',
                ]);
                $manipulator = new MenuManipulator();
                $manipulator->moveToPosition($child, 7);
            }
        }

        if ($this->security->isGranted('ROLE_ADMIN_HELLOASSO_ALL') || $this->security->isGranted('ROLE_SUPER_ADMIN') || $this->security->isGranted('ROLE_ADMIN_SOLIDOUME_LIST')) {
            $useSolidoume = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_SOLIDOUME);
            $soliParam = $this->em->getRepository(SolidoumeParameter::class)->findTheOne();
            $name = 'Sécurité sociale alimentaire';
            if (!empty($soliParam)) {
                $name = $soliParam->getName();
            }
            if ('true' == $useSolidoume) {
                $childS = $menu->addChild('solidoume', [
                    'label' => $name,
                    'route' => 'solidoume_list',
                ])->setExtras([
                    'icon' => '<i class="fa fa-handshake-o"></i>',
                ]);
                $manipulator = new MenuManipulator();
                $manipulator->moveToPosition($childS, 8);
            }
        }
    }
}
