<?php

namespace AppBundle\Controller\Admin;

use AppBundle\Entity\Contact;
use AppBundle\Enum\ContactCategory;
use AppBundle\Enum\ContactSubject;
use AppBundle\Form\Type\ContactType;
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;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

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

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


    /**
     *
     * @Route(
     *      "/contact/list/{page}",
     *      requirements = {"page": "\d+"},
     *      name = "admin_contact"
     * )
     *
     * @param Request $request
     * @param int $page
     * @return Response
     */
    public function indexAction(Request $request, int $page = 1)
    {
        $resultsMaxPerPage = $this->getParameter('results.admin.max_per_page');
        $search_email = $request->get('email');
        $search_category = $request->get('category');
        $search_subject = $request->get('subject');
        $search_dateMin = $request->get('datemin');
        $search_dateMax = $request->get('datemax');

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

        $qbContacts = $this->em->createQueryBuilder()
            ->select('c')
            ->from(Contact::class, 'c')
            ->orderBy('c.created', 'desc')
            ->addOrderBy('c.id', 'desc')
            ->setFirstResult(($page - 1) * $resultsMaxPerPage)
            ->setMaxResults($resultsMaxPerPage)
        ;
        
        if ($search_email) {
            $qbContacts
                ->andWhere($qbContacts->expr()->like(
                    $qbContacts->expr()->upper('c.email'),
                    $qbContacts->expr()->upper(':c_email')
                ))
                ->setParameter('c_email', '%'.$search_email.'%')
            ;
        }

        if ($search_category) {
            $qbContacts
                ->andWhere($qbContacts->expr()->like(
                    $qbContacts->expr()->upper('c.category'),
                    $qbContacts->expr()->upper(':c_category')
                ))
                ->setParameter('c_category', '%'.$search_category.'%')
            ;
        }

        if ($search_subject) {
            $qbContacts
                ->andWhere($qbContacts->expr()->like(
                    $qbContacts->expr()->upper('c.subject'),
                    $qbContacts->expr()->upper(':c_subject')
                ))
                ->setParameter('c_subject', '%'.$search_subject.'%')
            ;
        }

        if ($search_dateMin) {
            $qbContacts->andWhere('c.created >= :c_datemin')
                ->setParameter('c_datemin', \DateTime::createFromFormat('d/m/Y', $search_dateMin));
        }
        if ($search_dateMax) {
            $qbContacts->andWhere('c.created <= :c_datemax')
                ->setParameter('c_datemax', \DateTime::createFromFormat('d/m/Y', $search_dateMax));
        }

        $contacts = new Paginator($qbContacts->getQuery());

        $categories = ContactCategory::getConstants();
        $subjects = ContactSubject::getConstants();

        return $this->render('Admin/Contact/index.html.twig', array(
            'search_email' => $search_email,
            'search_category' => $search_category,
            'search_subject' => $search_subject,
            'search_datemin' => $search_dateMin,
            'search_datemax' => $search_dateMax,
            'contacts' => $contacts,
            'categories' => $categories,
            'subjects' => $subjects,
            'nb_pages' => ceil(count($contacts) / $resultsMaxPerPage),
            'pageactuelle' => $page,
        ));
    }

    /**
     *
     * @Route(
     *      "/contact/view/{id}",
     *      requirements = {"id": "\d+"},
     *      name = "admin_contact_view"
     * )
     *
     * @param Request $request
     * @param Contact $contact
     * @return RedirectResponse|Response
     */
    public function viewAction(Request $request, Contact $contact)
    {
        return $this->render('Admin/Contact/view.html.twig', array(
            'contact' => $contact
        ));
    }

    /**
     *
     * @Route(
     *      "/contact/delete/{id}",
     *      requirements = {"id" = "\d+"},
     *      name = "admin_contact_delete"
     * )
     * @param int $id
     * @return Response
     */
    public function deleteAction(int $id)
    {
        $entity = $this->em->getRepository(Contact::class)->findOneById($id);

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

        $this->addFlash('success', 'Données supprimées');

        return new Response();
    }
}
