<?php

namespace App\Admin;

use App\Entity\Flux;
use App\Entity\Groupe;
use App\Entity\Prestataire;
use App\Entity\User;
use App\Enum\MoyenEnum;
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\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Validator\Constraints\Regex;

/**
 * Administration des dons.
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 *
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class DonAdmin extends AbstractAdmin
{
    protected $baseRouteName = 'don';
    protected $baseRoutePattern = 'don';
    protected $security;

    protected $translator;
    protected $datagridValues = [
        '_sort_order' => 'DESC',
        '_sort_by' => 'createdAt',
        '_per_page' => 250,
    ];
    protected $maxPerPage = 250;
    protected $perPageOptions = [50, 100, 250, 500, 1000];

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

    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $datagridMapper
            ->add('montant', null, ['label' => 'Montant'])
            ->add('groupe', 'doctrine_orm_callback', [
                'label' => 'Groupe local',
                'callback' => function ($queryBuilder, $alias, $field, $value) {
                    if (!$value['value']) {
                        return;
                    }
                    $queryBuilder
                        ->leftJoin('App\Entity\DonPrestataire', 'c', 'WITH', $alias . '.id = c.id')
                        ->leftJoin('App\Entity\DonAdherent', 'ca', 'WITH', $alias . '.id = ca.id')
                        ->leftJoin('c.expediteur', 'e')
                        ->leftJoin('ca.expediteur', 'f')
                        ->andWhere('e.groupe = :groupe OR f.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,
                ],
            ])
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $cotisation = $this->getSubject();
        $now = new \DateTime();
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $formMapper
            ->with('Don', ['class' => 'col-md-8'])
                ->add('parenttype', HiddenType::class, [
                    'data' => Flux::TYPE_DON,
                ])
                ->add('operateur', HiddenType::class, [
                    'data' => $this->security->getUser(),
                    'data_class' => null,
                    'entity_class' => User::class,
                    'em' => $em,
                ])
                ->add('montant', MoneyType::class, [
                    'label' => 'Montant en euro(s)',
                    'scale' => 2,
                    'required' => true,
                    'constraints' => [
                        new Regex(['pattern' => '/[0-9]{1,}(\.[0-9]{1,2})?/']),
                    ],
                    'empty_data' => (float) 0.0,
                ])
                ->add('role', HiddenType::class, [
                    'data' => $this->security->getUser() ? $this->security->getUser()->getGroups()[0]->__toString() : '',
                ])
                ->add('destinataire', HiddenType::class, [
                    'data' => $em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]),
                    'data_class' => null,
                    'entity_class' => Prestataire::class,
                    'em' => $em,
                ])
                ->add('moyen', ChoiceType::class, [
                    'required' => true,
                    'choices' => MoyenEnum::getAvailableTypes(),
                    'choice_label' => function ($choice) {
                        return MoyenEnum::getTypeName($choice);
                    },
                ])
        ;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        $collection->remove('delete');
        if (null != $this->security->getUser() && !($this->security->isGranted('ROLE_TRESORIER') || $this->security->isGranted('ROLE_SUPER_ADMIN') || $this->security->isGranted('ROLE_COMPTOIR'))) {
            $collection->clearExcept(['list', 'export']);
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        unset($this->listModes['mosaic']);
        $listMapper
            ->add('id', 'text', [
                'label' => 'Expéditeur',
                'template' => '@kohinos/bundles/SonataAdminBundle/Block/don_obj.html.twig',
            ])
            ->add('expediteur.groupe.name', null, [
                'label' => 'Groupe',
            ])
            ->add('montant', 'decimal', [
                'label' => 'Montant',
                'attributes' => ['fraction_digits' => 2],
            ])
            ->add('moyen', null, [
                'label' => 'Moyen',
            ])
            ->add('operateurAndRole', null, [
                'label' => 'Opérateur',
            ])
            ->add('where', 'string', [
                'label' => 'Achat / Cotisation',
                'template' => '@kohinos/bundles/SonataAdminBundle/Block/don_type.html.twig',
            ])
            // ->add('_action', null, [
            //     'actions' => [
            //         // 'edit' => [],
            //     ],
            // ])
        ;
    }

    public function getDataSourceIterator()
    {
        $iterator = parent::getDataSourceIterator();
        $iterator->setDateTimeFormat('d/m/Y H:i:s'); //change this to suit your needs

        return $iterator;
    }

    public function getExportFields()
    {
        $ssaFriendlyTypeNames = $this->getConfigurationPool()->getContainer()->getParameter('tav_env')
            && $this->getConfigurationPool()->getContainer()->getParameter('ssa_friendly_flux_type_names');
        return [
            'Id' => $ssaFriendlyTypeNames ? 'expediteur.email' : 'expediteur',
            'Groupe' => 'expediteur.groupe.name',
            'Type' => 'type',
            'Montant' => 'montant',
            'Moyen' => 'moyen',
            'Operateur' => 'operateurAndRole',
            'Reference' => 'reference',
            'Date' => 'created_at',
        ];
    }
}
