<?php

namespace App\Admin;

use App\Entity\Flux;
use App\Entity\User;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Security\Core\Security;


/**
 * Administration des flux 'Achat de monnaie'
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 * @author Damien Moulard <dam.moulard@gmail.com>
 */
class AchatMonnaieAdmin extends FluxAdmin
{
    protected $baseRouteName = 'achat_monnaie';
    protected $baseRoutePattern = 'achat_monnaie';

    /**
    * {@inheritdoc}
    */
    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);
        $query->andWhere($query->getRootAliases()[0].".parenttype = :parenttype")
                ->setParameter('parenttype', Flux::TYPE_ACHAT);
        ;
        return $query;
    }

    /**
    * {@inheritdoc}
    */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        $datagridMapper->add('type', null, array(
            'advanced_filter' => false,
            'show_filter' => true,
            'field_type' => ChoiceType::class,
            'field_options' => array(
                'choices' => array('Adhérent' => 'achat_monnaie_adherent', 'Prestataire' => 'achat_monnaie_prestataire'),
                'placeholder' => 'Indifférent',
                'expanded' => true,
                'multiple' => false
            )
        ));
    }

    /**
    * {@inheritdoc}
    */
    protected function configureListFields(ListMapper $listMapper)
    {
        parent::configureListFields($listMapper);
        $listMapper
            ->remove('type')
            ->remove('expediteur')
        ;
    }

    public function getTotalLabel()
    {
        return $this->translator->trans('Total des achats de eMLC :');
    }

    public function getTotal()
    {
        $datagrid = $this->getDatagrid();
        $datagrid->buildPager();

        $query = clone $datagrid->getQuery();
        $query
            ->select('SUM( ' . $query->getRootAlias() . '.montant) as total')
            ->andWhere($query->getRootAlias().".parenttype = :parenttype")
            ->setParameter('parenttype', Flux::TYPE_ACHAT)
            ->setFirstResult(null)
            ->setMaxResults(null);

        $result = $query->execute(array(), \Doctrine\ORM\Query::HYDRATE_SINGLE_SCALAR);

        return $result;
    }
}
