<?php

namespace App\Admin;

use App\Entity\Adherent;
use App\Entity\User;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;

/**
 * Administration des cotisations des adhérents
 *
 * LOCO : Outil de gestion de Monnaie Locale Complémentaire
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class CotisationAdherentAdmin extends CotisationAdmin
{
    protected $baseRouteName = 'cotisation_adherent';
    protected $baseRoutePattern = 'cotisation_adherent';

    public function configure()
    {
        parent::configure();
    }

    /**
    * {@inheritdoc}
    */
    public function createQuery($context = 'list')
    {
        $user = $this->security->getUser();
        $query = parent::createQuery($context);
        $query->leftJoin($query->getRootAliases()[0] . '.operateur', 'u')
              ->andWhere($query->getRootAliases()[0] .".type='cotisation_adherent'")
              // ->andWhere('u.adherent IS NOT NULL')
        ;
        if ($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT')) {
            if (empty($user->getGroupesgere())) {
                $query->andWhere('false');
            } else {
                $groupe = $user->getGroupesgere();
                $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getEntityManager();
                $connection = $em->getConnection();
                $statement = $connection->prepare('SELECT f.id FROM flux f INNER JOIN adherent a ON (a.id = f.adherent_id OR a.id = f.adherent_dest_id) WHERE a.groupe_id = '.$groupe->getId());
                $statement->execute();
                $ids = $statement->fetchAll();
                $query
                    ->andWhere($query->expr()->in($query->getRootAliases()[0].'.id', ':ids'))
                    ->setParameter('ids', $ids)
                ;
            }
        }
        return $query;
    }

    /**
    * {@inheritdoc}
    */
    protected function configureShowFields(ShowMapper $showMapper)
    {
        parent::configureShowFields($showMapper);
    }

    /**
    * {@inheritdoc}
    */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        parent::configureDatagridFilters($datagridMapper);
    }

    /**
    * {@inheritdoc}
    */
    protected function configureFormFields(FormMapper $formMapper): void
    {
        $formMapper
            ->with('Cotisation', ['class' => 'col-md-8'])
                ->add('reference', HiddenType::class, array(
                    'data' => 'cotisation_adherent'
                ))
                ->add('type', HiddenType::class, array(
                    'data' => 'cotisation_adherent'
                ))
                ->add('expediteur', EntityType::class, array(
                    'label' => 'Expéditeur',
                    'class' => Adherent::class,
                    'choices' =>  $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Adherent::class)->findBy(array('enabled' => true), array('lastname'=> 'ASC')),
                    'placeholder' => 'Choisir un adhérent',
                    'required' => true,
                ))
                ->add('operateur', HiddenType::class, array(
                    'data' => $this->security->getUser()->getId(),
                    'entity_class' => User::class,
                    'em' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager()
                ))
            ->end()
        ;
        parent::configureFormFields($formMapper);
    }

    /**
    * {@inheritdoc}
    */
    protected function configureRoutes(RouteCollection $collection)
    {
        parent::configureRoutes($collection);
    }

    /**
    * {@inheritdoc}
    */
    protected function configureListFields(ListMapper $listMapper): void
    {
        unset($this->listModes['mosaic']);
        $listMapper
            ->addIdentifier('expediteur', null, array(
                'label' => 'Adherent'
            ))
            ->addIdentifier('expediteur.user.email', null, array(
                'label' => 'Email'
            ))
        ;
        parent::configureListFields($listMapper);
    }
}
