<?php

namespace AppBundle\Controller\Admin;

use AppBundle\Entity\Testimonial;
use AppBundle\Form\Type\TestimonialType;
use Cocur\Slugify\Slugify;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class TestimonialController extends Controller
{
    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var SessionInterface
     */
    private $session;
    
    public function __construct(EntityManagerInterface $em, SessionInterface $session)
    {
        $this->em = $em;
        $this->session = $session;
    }


    /**
     *
     * @Route(
     *      "/testimonial/list/{page}",
     *      requirements = {"page": "\d+"},
     *      name = "admin_testimonial"
     * )
     *
     * @param Request $request
     * @param int $page
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction(Request $request, int $page = 1)
    {
        $resultsMaxPerPage = $this->getParameter('results.admin.max_per_page');
        $search_witness = $request->get('witness');

        // Mise à jour de la session avec les nouvelles valeurs
        $this->session->set($request->get('_route'), array(
            'page' => $page,
        ));

        $qbTestimonials = $this->em->createQueryBuilder()
            ->select('t')
            ->from(Testimonial::class, 't')
            ->orderBy('t.created', 'desc')
            ->addOrderBy('t.id', 'desc')
            ->setFirstResult(($page - 1) * $resultsMaxPerPage)
            ->setMaxResults($resultsMaxPerPage)
        ;
        
        if ($search_witness) {
            $qbTestimonials
                ->andWhere($qbTestimonials->expr()->like(
                    $qbTestimonials->expr()->upper('t.witness'),
                    $qbTestimonials->expr()->upper(':t_witness')
                ))
                ->setParameter('t_witness', '%'.$search_witness.'%')
            ;
        }

        $testimonials = new Paginator($qbTestimonials->getQuery());

        return $this->render('Admin/Testimonial/index.html.twig', array(
            'search_witness' => $search_witness,
            'testimonials' => $testimonials,
            'nb_pages' => ceil(count($testimonials) / $resultsMaxPerPage),
            'pageactuelle' => $page,
        ));
    }

    /**
     * @Route(
     *      "/testimonial/add",
     *      name = "admin_testimonial_add"
     * )
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function addAction(Request $request)
    {
        $slugify = new Slugify();

        $testimonial = new Testimonial;

        $form = $this->createForm(TestimonialType::class, $testimonial);
        $form->handleRequest($request);
        
        if ($form->isSubmitted() && $form->isValid()) {
            $testimonial->setCreated(new \DateTime);
            
            $testimonial->preUploadFilePicture(); // @ORM\PrePersist() not working ?
            $this->em->persist($testimonial);
            $testimonial->uploadFilePicture(); // @ORM\PostPersist() not working ?

            $this->em->flush();

            // On définit un message flash
            $this->addFlash('success', 'Témoignage ajouté');

            return $this->redirectToRoute('admin_testimonial_edit', array(
                'id' => $testimonial->getId(),
            ));
        }

        return $this->render('Admin/Testimonial/add.html.twig', array(
            'form' => $form->createView()
        ));
    }

    /**
     *
     * @Route(
     *      "/testimonial/edit/{id}",
     *      requirements = {"id": "\d+"},
     *      name = "admin_testimonial_edit"
     * )
     *
     * @param Request $request
     * @param Testimonial $testimonial
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function editAction(Request $request, Testimonial $testimonial)
    {
        $slugify = new Slugify();

        $form = $this->createForm(TestimonialType::class, $testimonial);
        $form->handleRequest($request);
        
        if ($form->isSubmitted() && $form->isValid()) {
            $testimonial->setUpdated(new \DateTime);
            
            $testimonial->preUploadFilePicture(); // @ORM\PrePersist() not working ?
            $this->em->persist($testimonial);
            $testimonial->uploadFilePicture(); // @ORM\PostPersist() not working ?

            $this->em->flush();

            // On définit un message flash
            $this->addFlash('success', 'Témoignage modifié');

            return $this->redirectToRoute('admin_testimonial_edit', array(
                'id' => $testimonial->getId(),
            ));
        }

        return $this->render('Admin/Testimonial/add.html.twig', array(
            'form' => $form->createView()
        ));
    }


    /**
     *
     * @Route(
     *      "/testimonial/actif",
     *      name = "admin_testimonial_actif"
     * )
     * @param Request $request
     * @return Response
     */
    public function actifAction(Request $request)
    {
        $id = $request->get('id');
        $actif = $request->get('actif');
        $type = 'Testimonial';

        $element = $this->em->getRepository('AppBundle:' . $type)->find($id);

        if (!$element) {
            throw $this->createNotFoundException(
                'No testimonial found for id '.$id
            );
        }

        $element->setIsActive($actif);
        $this->em->flush();
        
        return new Response();
    }

    /**
     *
     * @Route(
     *      "/testimonial/delete/{id}",
     *      requirements = {"id" = "\d+"},
     *      name = "admin_testimonial_delete"
     * )
     * @param int $id
     * @return Response
     */
    public function deleteAction(int $id)
    {
        //$id = $request->get('id');
        $type = 'Testimonial';

        $entity = $this->em->getRepository('AppBundle:' . $type)->findOneById($id);

        $this->em->remove($entity);
        $this->em->flush();

        $this->addFlash('success', 'Témoignage supprimé');

        return new Response();
    }
}
