<?php

namespace App\Admin;

use App\Entity\Flux;
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\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
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 cotisations.
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 *
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class CotisationAdmin extends AbstractAdmin
{
    protected $baseRouteName = 'cotisation';
    protected $baseRoutePattern = 'cotisation';
    protected $security;

    protected $translator;
    protected $datagridValues = [
        '_sort_order' => 'DESC',
        '_sort_by' => 'createdAt',
    ];

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

    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        $datagridMapper
            ->add('cotisationInfos.annee', null, ['label' => 'Année'])
            ->add('montant', null, ['label' => 'Montant'])
            ->add('cotisationInfos.recu', null, [
                'label' => 'Recu ?',
                'show_filter' => true,
                'advanced_filter' => false,
            ])
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $cotisation = $this->getSubject();
        $now = new \DateTime();
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $formMapper
            ->with('Cotisation', ['class' => 'col-md-8'])
                ->add('parenttype', HiddenType::class, [
                    'data' => Flux::TYPE_COTISATION,
                ])
                ->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);
                    },
                ])
        ;
        if (null != $this->security->getUser() && ($this->security->isGranted('ROLE_SUPER_ADMIN') || $this->security->isGranted('ROLE_TRESORIER'))) {
            $formMapper
                ->add('cotisationInfos.recu', CheckboxType::class, [
                    'label' => 'Paiement bien reçu',
                    'required' => false,
                ]);
        }
        $formMapper->end()
            ->with('Date', ['class' => 'col-md-4'])
                ->add('cotisationInfos.annee', null, [
                    'label' => 'Année',
                    'required' => false,
                ])
                ->add('cotisationInfos.debut', DateType::class, [
                    'label' => 'Date de début',
                    'widget' => 'single_text',
                    'required' => true,
                    // 'html5' => false,
                    'format' => 'yyyy-MM-dd',
                    'attr' => ['class' => 'js-datepicker'],
                ])
                ->add('cotisationInfos.fin', DateType::class, [
                    'label' => 'Date de fin',
                    'widget' => 'single_text',
                    // 'html5' => false,
                    'format' => 'yyyy-MM-dd',
                    'attr' => ['class' => 'js-datepicker'],
                ])
            ->end()
        ;
    }

    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', [
                'template' => '@kohinos/bundles/SonataAdminBundle/Block/cotisation_obj.html.twig',
            ])
            ->add('cotisationInfos.annee', null, [
                'label' => 'Année',
            ])
            ->add('montant', 'decimal', [
                'label' => 'Montant',
                'attributes' => ['fraction_digits' => 2],
            ])
            ->add('moyen', null, [
                'label' => 'Moyen',
            ])
            ->add('cotisationInfos.debut', null, [
                'label' => 'Crée le',
            ])
            ->add('cotisationInfos.fin', null, [
                'label' => 'Expire le',
            ])
            ->add('cotisationInfos.recu', null, [
                'label' => 'Paiement bien reçu ?',
                'editable' => true,
            ])
            ->add('operateurAndRole', null, [
                'label' => 'Opérateur',
            ])
            ->add('_action', null, [
                'actions' => [
                    'edit' => [],
                ],
            ])
        ;
    }
}