<?php

namespace App\Admin;

use App\Entity\Geoloc;
use App\Entity\Groupe;
use App\Form\Type\GeolocFormType;
use Doctrine\ORM\EntityRepository;
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 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 $baseRouteName = 'comptoir';
    protected $baseRoutePattern = 'comptoir';
    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 (empty($this->getRequest()->getSession()->get('_groupegere'))) {
            if ($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT')) {
                $query->andWhere('false');
            }
        } else {
            $query
                ->andWhere($query->getRootAliases()[0].'.groupe = :groupe')
                ->setParameter('groupe', $this->getRequest()->getSession()->get('_groupegere'))
            ;
        }
        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($this->getRequest()->getSession()->get('_groupegere'))) {
            $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' => false,
                ))
                ->add('tel', null, array(
                    'label' => 'Téléphone',
                    'required' => false,
                ))
                ->add('content', CKEditorType::class, array(
                    'label' => 'Description :',
                    'required' => false
                ))
                ->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->add('test');
        $collection->remove('delete');
    }

    public function configureActionButtons($action, $object = null)
    {
        $list = parent::configureActionButtons($action, $object);

        $list['test']['template'] = '@SonataAdmin/show_map_comptoir.html.twig';

        return $list;
    }
    
    public function getRouteShowOnFront($object)
    {
        return $this->routeGenerator->generate('show_comptoir', array('slug' => $object->getSlug()));
    }

    public function getRouteShowMap()
    {
        return $this->routeGenerator->generate('comptoirs_carte');
    }

    /**
    * {@inheritdoc}
    */
    protected function configureListFields(ListMapper $listMapper)
    {
        unset($this->listModes['mosaic']);
        $listMapper
            ->addIdentifier('name')
            ->add('compte', null, array('label' => 'Solde'))
            ->add('geoloc', null, array('label' => 'Adresse'))
            ->add('tel', null, array('label' => 'Téléphone'))
            ->add('enabled', null, array(
                'label' => 'Activé',
                'editable' => true
            ))
            ->add('_action', null, [
                'actions' => [
                    'show' => ['template' => '@SonataAdmin/CRUD/list__action_showonfront.html.twig'],
                    'edit' => []
                ]
            ])
        ;
    }
}
