<?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;

final class MenuBuilderListener
{
    private $em;

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

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

        $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);
        }

        $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);
        }
    }
}
