<?php

namespace App\Admin;

use App\Entity\AccountPrestataire;
use App\Entity\Groupe;
use App\Entity\OperationPrestataire;
use App\Entity\Prestataire;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

/**
 * Administration des operation des prestataires.
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 *
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class OperationPrestataireAdmin extends OperationAdmin
{
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper->add('account.accountableObject', null, ['label' => 'Compte prestataire', 'template' => '@kohinos/bundles/SonataAdminBundle/Block/accountable.html.twig']);
        parent::configureListFields($listMapper);
    }

    /**
     * {@inheritdoc}
     */
    public function createQuery($context = 'list')
    {
        $user = $this->security->getUser();
        $query = parent::createQuery($context);
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $operationPrestatable = $em->getMetadataFactory()->getMetadataFor(OperationPrestataire::class)->getTableName();

        if ($user && ($this->security->isGranted('ROLE_GESTION_GROUPE') || $this->security->isGranted('ROLE_CONTACT') || $this->security->isGranted('ROLE_TRESORIER'))) {
            if ($this->hasRequest()) {
                if (empty($this->getRequest()->getSession()->get('_groupegere'))) {
                    if (!$this->security->isGranted('ROLE_TRESORIER')) {
                        $query->andWhere('false = true');
                    }
                } else {
                    $groupe = $this->getRequest()->getSession()->get('_groupegere');
                    $connection = $em->getConnection();
                    $prestatable = $em->getMetadataFactory()->getMetadataFor(Prestataire::class)->getTableName();
                    $accountTable = $em->getMetadataFactory()->getMetadataFor(AccountPrestataire::class)->getTableName();
                    $statement = $connection->prepare('SELECT f.id FROM ' . $operationPrestatable . ' f WHERE f.account_id IN  
                        (SELECT a.id FROM ' . $accountTable . ' a WHERE a.prestataire_id IN  
                            (SELECT p.id FROM ' . $prestatable . ' p WHERE p.groupe_id = "' . $groupe->getId() . '")
                        )');
                    $statement->execute();
                    $ids = $statement->fetchAll();
                    $query
                        ->andWhere($query->expr()->in($query->getRootAliases()[0] . '.id', ':ids'))
                        ->setParameter('ids', $ids)
                    ;
                }
            }
        }

        return $query;
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        parent::configureDatagridFilters($datagridMapper);
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $datagridMapper
            ->add('account.prestataire', null, [
                'label' => 'Prestataire',
                'advanced_filter' => false,
                'show_filter' => true,
            ])
            ->add('groupe', 'doctrine_orm_callback', [
                'label' => 'Groupe local',
                'callback' => function ($queryBuilder, $alias, $field, $value) {
                    if (!$value['value']) {
                        return;
                    }
                    $queryBuilder
                        ->leftJoin($alias . '.account', 'a')
                        ->leftJoin('App\Entity\Prestataire', 'p', 'WITH', 'a.prestataire = p')
                        ->andWhere('p.groupe = :groupe')
                        ->setParameter('groupe', $value['value']);

                    return true;
                },
                'advanced_filter' => false,
                'show_filter' => true,
                'field_type' => ChoiceType::class,
                'field_options' => [
                    'choices' => $em->getRepository(Groupe::class)->findBy(['enabled' => true], ['name' => 'ASC']),
                    'choice_label' => 'name',
                    'placeholder' => 'Indifférent',
                    'expanded' => false,
                    'multiple' => false,
                ],
            ])
        ;
    }
}
