<?php

namespace App\Admin;

use App\Entity\Geoloc;
use App\Entity\Groupe;
use App\Form\Type\GeolocFormType;
use Doctrine\ORM\EntityRepository;
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 Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Form\Extension\Core\Type\TextType;

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

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

    /**
    * {@inheritdoc}
    */
    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);
        $user = $this->security->getUser();
        if ($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT')) {
            if (empty($user->getGroupesgeres())) {
                $query->andWhere('false');
            } else {
                $groupes = $user->getGroupesgeres();
                $query
                    ->andWhere($query->expr()->in($query->getRootAliases()[0].'.groupe', ':group'))
                    // ->andWhere($query->getRootAliases()[0] . '.groupe = :group')
                    ->setParameter('group', $groupes)
                ;
            }
        }
        return $query;
    }

    /**
    * {@inheritdoc}
    */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $comptoir = $this->getSubject();
        $user = $this->security->getUser();
        if ($this->isCurrentRoute('create')) {
            $geoloc = new Geoloc();
            $comptoir->setGeoloc($geoloc);
        }
        $formMapper
            ->with('Comptoir', ['class' => 'col-md-8']);
        if (($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT')) && !empty($user->getGroupesgeres())) {
            $em = $this->modelManager->getEntityManager(Groupe::class);

            $formMapper->add('groupe', null, array(
                    'label' => 'Groupe local',
                    'required' => true,
                    'query_builder' => function (EntityRepository $repo) use ($user) {
                        return $repo->createQueryBuilder('g')
                            ->select('g')
                            ->join('g.gestionnaires', 'c')
                            ->where('c.id = :user')
                            ->setParameter('user', $user->getId());
                    },
                ));
        } else {
            $formMapper->add('groupe', null, array(
                    'label' => 'Groupe local',
                    'required' => true,
                ));
        }
        $formMapper
                ->add('name', null, array(
                    'label' => 'Nom',
                    'required' => true,
                ))
                ->add('email', null, array(
                    'label' => 'Email',
                    'required' => true,
                ))
                ->add('tel', null, array(
                    'label' => 'Téléphone',
                    'required' => true,
                ))
                ->add('enabled', null, array('label' => 'Activé ?'))
            ->end()
            ->with('Geoloc', ['class' => 'col-md-4'])
                ->add('geoloc', GeolocFormType::class, array(
                    'label' => false,
                    'required' => true
                ))
            ->end()
        ;
    }

    /**
    * {@inheritdoc}
    */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        if ($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_SUPER_ADMIN') || $this->isGranted('ROLE_ADMIN_SIEGE')) {
            $datagridMapper
                ->add('groupe', null, [
                    'label' => "Groupe",
                    'show_filter' => true,
                    'advanced_filter' => false
                ])
            ;
        }
        $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');
    }

    /**
    * {@inheritdoc}
    */
    protected function configureListFields(ListMapper $listMapper)
    {
        unset($this->listModes['mosaic']);
        $listMapper
            ->addIdentifier('name')
            ->addIdentifier('email')
            ->addIdentifier('compte', null, array('label' => 'Solde'))
            ->addIdentifier('geoloc.adresse', null, array('label' => 'Adresse'))
            ->addIdentifier('tel', null, array('label' => 'Téléphone'))
            ->addIdentifier('enabled', null, array('label' => 'Activé', 'datatype' => 'App.Comptoir', 'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'))
        ;
    }
}
