<?php

namespace App\Admin;

use App\Entity\Prestataire;
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\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;

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

    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_prestataire'")
              // ->andWhere('u.prestataire 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 prestataire a ON (a.id = f.prestataire_id OR a.id = f.prestataire_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);
        $datagridMapper
            ->add('expediteur', null, array('label' => 'Prestataire'))
        ;
    }


    /**
    * {@inheritdoc}
    */
    protected function configureFormFields(FormMapper $formMapper): void
    {
        $expediteurInfos = array(
            'label' => 'Expéditeur',
            'class' => Prestataire::class,
            'choices' =>  $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Prestataire::class)->findBy(array('enabled' => true), array('raison'=> 'ASC')),
            'placeholder' => 'Choisir un prestataire',
            'required' => true,
        );
        $exp = $this->getRequest()->get('expediteur');
        if (!empty($exp)) {
            $expediteurInfos['data'] = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Prestataire::class)->findOneById($exp);
        }
        $formMapper
            ->with('Cotisation', ['class' => 'col-md-8'])
                ->add('reference', HiddenType::class, array(
                    'data' => 'cotisation_prestataire'
                ))
                ->add('type', HiddenType::class, array(
                    'data' => 'cotisation_prestataire'
                ))
                ->add('expediteur', EntityType::class, $expediteurInfos)
                ->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' => 'Prestataire'))
            ->addIdentifier('expediteur.user.email', null, array('label' => 'Email'));
        parent::configureListFields($listMapper);
    }
}
