<?php

namespace App\Admin;

use App\Entity\AccountGroupe;
use App\Entity\Comptoir;
use App\Entity\GlobalParameter;
use App\Entity\Siege;
use App\Enum\CurrencyEnum;
use FOS\CKEditorBundle\Form\Type\CKEditorType;
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 Sonata\DoctrineORMAdminBundle\Filter\CallbackFilter;
use Sonata\FormatterBundle\Form\Type\SimpleFormatterType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

/**
 * Administration des groupes locaux.
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 *
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class GroupeAdmin extends AbstractAdmin
{
    protected $datagridValues = [
        '_sort_order' => 'ASC',
        '_sort_by' => 'name',
    ];

    public function configure()
    {
        parent::configure();
        $this->classnameLabel = 'Groupes locaux';
    }

    /**
     * {@inheritdoc}
     */
    protected function configureShowFields(ShowMapper $showMapper)
    {
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $groupe = $this->getSubject();
        $formMapper
            ->with("Création d'un groupe")
                ->add('siege', HiddenType::class, [
                    'data' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager()->getRepository(Siege::class)->getTheOne(),
                    'data_class' => null,
                    'entity_class' => Siege::class,
                    'em' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager(),
                ])
                ->add('name', TextType::class, [
                    'label' => 'Nom du groupe :',
                    'required' => true,
                ])
                ->add('content', CKEditorType::class, [
                    'label' => 'Description :',
                    'required' => false,
                ])
                // ->add('content', SimpleFormatterType::class, [
                //     'format' => 'richhtml',
                //     'ckeditor_context' => 'default',
                //     'label' => 'Description :',
                //     'required' => false,
                // ])
                ->add('comptoirs', CollectionType::class, [
                    'label' => 'Comptoirs',
                    'entry_type' => EntityType::class,
                    'entry_options' => [
                        'class' => Comptoir::class,
                        'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Comptoir::class)->findAll(),
                        'choice_label' => 'slug',
                        'placeholder' => 'Comptoir',
                        'required' => false,
                        'label' => false, ],
                    'by_reference' => false,
                    'allow_add' => true,
                    'allow_delete' => true,
                ]);
        if (count($groupe->getPrestataires()) > 0) {
            $formMapper
                ->add('enabled', CheckboxType::class, [
                    'label' => 'Activé ?',
                    'help' => '(impossible de désactiver un groupe local contenant au moins 1 prestataire',
                    'required' => false,
                    'disabled' => true,
                    'label_attr' => ['class' => 'checkbox-inline'],
                ]);
        } else {
            $formMapper
                ->add('enabled', CheckboxType::class, [
                    'label' => 'Activé ?',
                    'required' => false,
                    'label_attr' => ['class' => 'checkbox-inline'],
                ]);
        }
        $formMapper->end();
    }

    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        $datagridMapper
            ->add('full_text', CallbackFilter::class, [
                'callback' => [$this, 'getFullTextFilter'],
                'field_type' => TextType::class,
                'label' => 'Recherche par nom',
                'show_filter' => true,
                'advanced_filter' => false,
            ])
        ;
    }

    public function getFullTextFilter($queryBuilder, $alias, $field, $value)
    {
        if (!$value['value']) {
            return;
        }

        // Use `andWhere` instead of `where` to prevent overriding existing `where` conditions
        $queryBuilder->andWhere(
            $queryBuilder->expr()->like($alias . '.name', $queryBuilder->expr()->literal('%' . $value['value'] . '%'))
        );

        return true;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        $collection->remove('delete');
    }

    public function getRouteShowOnFront($object)
    {
        return $this->routeGenerator->generate('show_groupe', ['slug' => $object->getSlug()]);
    }

    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        unset($this->listModes['mosaic']);

        $isWordpressActivated = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_WORDPRESS);
        if ('false' == $isWordpressActivated) {
            $actions = [
                'show' => ['template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list__action_showonfront.html.twig'],
                'edit' => [],
            ];
        } else {
            $actions = [
                'edit' => [],
            ];
        }

        $listMapper
            ->addIdentifier('name', null, ['label' => 'Nom du groupe'])
            ->add('gestionnaires', null, ['label' => 'Gestionnaires'])
            ->add('content', 'html', ['truncate' => ['length' => 80], 'label' => 'Description'])
            ->add('balance', null, ['label' => 'Solde', 'template' => '@kohinos/block/balance.html.twig', 'currency' => 'mlc'])
            ->add(
                'getPrestatairesCount',
                null,
                [
                    'label' => 'Nombre de prestas',
                    'sortable' => true,
                    'sort_field_mapping' => ['fieldName' => 'id'],
                    'sort_parent_association_mappings' => [],
                ]
            )->add(
                'getAdherentsCount',
                null,
                [
                    'label' => 'Nb adherents',
                    'sortable' => true,
                    'sort_field_mapping' => ['fieldName' => 'id'],
                    'sort_parent_association_mappings' => [],
                ]
            )
            ->add(
                'getComptoirsCount',
                null,
                [
                    'label' => 'Nb comptoirs',
                    'sortable' => true,
                    'sort_field_mapping' => ['fieldName' => 'id'],
                    'sort_parent_association_mappings' => [],
                ]
            )
            ->add('enabled', null, [
                'label' => 'Activé'
            ])
            ->add('_action', null, [
                'actions' => $actions,
            ])
        ;
    }

    public function preUpdate($groupe)
    {
        $this->prePersist($groupe);
    }

    public function prePersist($groupe)
    {
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();

        $account = $em->getRepository(AccountGroupe::class)->findOneBy(['groupe' => $groupe, 'currency' => CurrencyEnum::CURRENCY_MLC]);
        if (null == $account) {
            $account = new AccountGroupe();
            $account
                ->setCurrency(CurrencyEnum::CURRENCY_MLC)
            ;
            $groupe->addAccount($account);
            $em->persist($account);
        }
        $em->persist($groupe);
        $em->flush();
    }
}
