<?php

/*
 * kohinos_cooperatic
 * Copyright (C) 2019-2020  ADML63
 * Copyright (C) 2020- Cooperatic
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
namespace App\Admin;

use App\Entity\Adherent;
use App\Entity\GlobalParameter;
use App\Entity\Prestataire;
use App\Entity\Siege;
use App\Entity\User;
use App\Enum\MoyenEnum;
use Doctrine\ORM\EntityManagerInterface;
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 Sonata\AdminBundle\Show\ShowMapper;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
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\Intl\DateFormatter\IntlDateFormatter;
use Symfony\Component\Security\Core\Security;

/**
 * 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, array('label' => 'Année'))
            ->add('montant', null, array('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, array(
                    'data' => 'cotisation'
                ))
                ->add('operateur', HiddenType::class, array(
                    'data' => $this->security->getUser()->getId(),
                    'data_class' => null,
                    'entity_class' => User::class,
                    'em' => $em
                ))
                ->add('role', HiddenType::class, array(
                    'data' => $this->security->getUser()->getGroups()[0]->__toString()
                ))
                ->add('destinataire', HiddenType::class, array(
                    'data' => $em->getRepository(Prestataire::class)->findOneBy(array('mlc' => true))->getId(),
                    'data_class' => null,
                    'entity_class' => Prestataire::class,
                    'em' => $em
                ))
                ->add('moyen', ChoiceType::class, array(
                    'required' => true,
                    'choices' => MoyenEnum::getAvailableTypes(),
                    'choice_label' => function ($choice) {
                        return MoyenEnum::getTypeName($choice);
                    },
                ))
        ;
        if ($this->security->getUser() != null && ($this->security->getUser()->isGranted('ROLE_SUPER_ADMIN') || $this->security->getUser()->isGranted('ROLE_TRESORIER'))) {
            $formMapper
                ->add('cotisationInfos.recu', CheckboxType::class, array(
                    'label' => 'Reçu',
                    'required' => false
                ));
        }
        $formMapper->end()
            ->with('Date', ['class' => 'col-md-4'])
                ->add('cotisationInfos.annee', null, array(
                    'label' => 'Année',
                    'required' => false
                ))
                ->add('cotisationInfos.debut', DateType::class, array(
                    'label' => 'Date de début',
                    'widget' => 'single_text',
                    'required' => true,
                    // 'html5' => false,
                    'format' => IntlDateFormatter::SHORT,
                    'attr' => ['class' => 'js-datepicker'],
                ))
                ->add('cotisationInfos.fin', DateType::class, array(
                    'label' => 'Date de fin',
                    'widget' => 'single_text',
                    // 'html5' => false,
                    'format' => IntlDateFormatter::SHORT,
                    'attr' => ['class' => 'js-datepicker'],
                ))
            ->end()
        ;
    }

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

    /**
    * {@inheritdoc}
    */
    protected function configureListFields(ListMapper $listMapper)
    {
        unset($this->listModes['mosaic']);
        $listMapper
            ->add('cotisationInfos.annee', null, array(
                'label' => 'Année'
            ))
            ->add('montant', null, array(
                'label' => 'Montant'
            ))
            ->add('moyen', null, array(
                'label' => 'Moyen'
            ))
            ->add('cotisationInfos.debut', null, array(
                'label' => 'Crée le'
            ))
            ->add('cotisationInfos.fin', null, array(
                'label' => 'Expire le'
            ))
            ->add('cotisationInfos.recu', null, array(
                'label' => 'Reçu ?',
                'editable' => true
            ))
            ->add('operateurAndRole', null, array(
                'label' => 'Opérateur'
            ))
            ->add('_action', null, [
                'actions' => [
                    'edit' => [],
                ]
            ])
        ;
    }
}