<?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\Comptoir;
use App\Entity\GlobalParameter;
use App\Entity\Siege;
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, array(
                    'data' => 1,
                    'data_class' => null,
                    'entity_class' => Siege::class,
                    'em' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager()
                ))
                ->add('name', TextType::class, array(
                    'label' => 'Nom du groupe :',
                    'required' => true
                ))
                ->add('content', CKEditorType::class, array(
                    'label' => 'Description :',
                    'required' => false,
                ))
                // ->add('content', SimpleFormatterType::class, [
                //     'format' => 'richhtml',
                //     'ckeditor_context' => 'default',
                //     'label' => 'Description :',
                //     'required' => false,
                // ])
                ->add('comptoirs', CollectionType::class, array(
                    'label' => 'Comptoirs',
                    'entry_type' => EntityType::class,
                    'entry_options' => array(
                        '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
                ))
                ->add('enabled', CheckboxType::class, array(
                    'label' => 'Activé ?',
                    'required' => false,
                    'label_attr' => array('class' => 'checkbox-inline')
                ))
            ->end()
        ;
    }

    public function postPersist($object)
    {
        // $this->addFlash(
        //     'sonata_flash_success',
        //     $this->trans(
        //         "Après avoir créer le groupe %name%, il est conseiller d'ajouter un gestionnaire de groupe",
        //         ['%name%' => $this->escapeHtml($this->admin->toString($object))]
        //     )
        // );
    }

    /**
    * {@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', array('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 ($isWordpressActivated == 'false') {
            $actions = [
                'show' => ['template' => '@SonataAdmin/CRUD/list__action_showonfront.html.twig'],
                'edit' => []
            ];
        } else {
            $actions = [
                'edit' => []
            ];
        }

        $listMapper
            ->addIdentifier('name', null, array('label' => 'Nom du groupe'))
            ->add('gestionnaires', null, array('label' => 'Gestionnaires'))
            ->add('content', 'html', array('truncate' => array('length' => 80), 'label' => 'Description'))
            ->add('compte', null, array('label' => 'Solde'))
            ->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, array(
                'label' => 'Activé',
                'editable' => true
            ))
            ->add('_action', null, [
                'actions' => $actions
            ])
        ;
    }
}
