<?php

namespace App\Admin;

use App\Entity\AccountComptoir;
use App\Entity\Comptoir;
use App\Entity\OperationComptoir;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Symfony\Component\Security\Core\Security;

/**
 * Administration des operation des comptoirs.
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 *
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class OperationComptoirAdmin extends OperationAdmin
{
    protected $security;
    protected $session;
    protected $datagridValues = [
        '_sort_order' => 'DESC',
        '_sort_by' => 'createdAt',
    ];

    public function setSecurity(Security $security)
    {
        $this->security = $security;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        $collection->clearExcept(['list', 'export']);
    }

    /**
     * {@inheritdoc}
     */
    public function createQuery($context = 'list')
    {
        $user = $this->security->getUser();
        $query = parent::createQuery($context);
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $operationComptoirtable = $em->getMetadataFactory()->getMetadataFor(OperationComptoir::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->getUser()->isGranted('ROLE_TRESORIER')) {
                        $query->andWhere('false = true');
                    }
                } else {
                    $groupe = $this->getRequest()->getSession()->get('_groupegere');
                    $connection = $em->getConnection();
                    $ComptoirTable = $em->getMetadataFactory()->getMetadataFor(Comptoir::class)->getTableName();
                    $accountTable = $em->getMetadataFactory()->getMetadataFor(AccountComptoir::class)->getTableName();
                    $statement = $connection->prepare('SELECT f.id FROM ' . $operationComptoirtable . ' f WHERE f.account_id IN  
                        (SELECT a.id FROM ' . $accountTable . ' a WHERE a.prestataire_id IN 
                            (SELECT p.id FROM ' . $ComptoirTable . ' 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
    {
        $datagridMapper
            ->add('account.comptoir', null, [
                'label' => 'Comptoir',
                'advanced_filter' => false,
                'show_filter' => true,
            ])
        ;
    }
}
