<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Historique;
use AppBundle\Entity\Thematique;
use DateTime;
use Exception;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Thematique controller.
 *
 * @Route("/panel/thematique")
 */
class ThematiqueAdminController extends Controller
{
    /**
     * Lists all thematique entities.
     *
     * @Route("/", name="thematique_index")
     * @Method("GET")
     * @Template("@App/Admin/thematique/index.html.twig")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'GestionThematique']);

        //$agence = $em->getRepository('AppBundle:Agence')->find($this->get('session')->get('agence'));
        $agences = $this->getUser()->getAgences();
        if (count($agences) != 0) {
            $agence = $agences[0];
            $thematiques=$agence->getThematique();
        }
        else
        {
            $agence=null;
            $thematiques = [];
        }

        return [
            'agence' => $agence,
            'thematiques' => $thematiques,
            'entete'=> $entete
        ];
    }
    /**
     * Creates a new thematique entity.
     *
     * @Route("/new", name="thematique_new")
     * @Method({"GET", "POST"})
     * @Template("@App/Admin/thematique/new.html.twig")
     * @param Request $request
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_ADMIN')")
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function newAction(Request $request)
    {
        $thematique = new Thematique();
        $form = $this->createForm('AppBundle\Form\ThematiqueType', $thematique);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $pkCheck = $em->getRepository('AppBundle:Thematique')->find($thematique->getCode());
            if($pkCheck) {
                $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_THEMATIQUE_PK'));
            } else {
                $thematique->setDateCreated(new DateTime());
                $thematique->setAgenceCodeAgence($em->getRepository('AppBundle:Agence')->findAll()[0]);
                $histo = new Historique("Création", "Thematique", "Création thématique : ".$thematique->getCode(), $this->getUser());

                $em->persist($thematique);
                $em->persist($histo);

                try {
                    $em->flush();
                    $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('THEMATIQUE_ADD_SUCCESS'));

                    return $this->redirectToRoute('thematique_index');
                } catch (Exception $e) {
                    $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_500_HELP'));
                }
            }
        }

        return [
            'thematique' => $thematique,
            'form' => $form->createView(),
        ];
    }

    /**
     * Displays a form to edit an existing thematique entity.
     *
     * @Route("/{code}/edit", name="thematique_edit")
     * @Method({"GET", "POST"})
     * @Template("@App/Admin/thematique/edit.html.twig")
     * @param Request $request
     * @param Thematique $thematique
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_ADMIN')")
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function editAction(Request $request, Thematique $thematique)
    {
        $editForm = $this->createForm('AppBundle\Form\ThematiqueType', $thematique);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $histo = new Historique("Modification", "Thematique", "Modification thématique : ".$thematique->getCode(), $this->getUser());

            $em->persist($thematique);
            $em->persist($histo);

            try {
                $em->flush();
                $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('THEMATIQUE_EDIT_SUCCESS'));
            } catch (Exception $e) {
                $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_500_HELP'));
            }

            return $this->redirectToRoute('thematique_index');
        }

        return [
            'thematique' => $thematique,
            'form' => $editForm->createView(),
        ];
    }

    /**
     * @param Thematique $thematique
     * @Route("/{code}/{siret}/extensions", name="thematique_extensions", options={"expose"=true})
     * @Method("GET")
     * @return JsonResponse
     */
    public function getExtensionsAction(Thematique $thematique, $siret)
    {
        $ext = strlen($thematique->getExtension()) > 0 ? explode(',',$thematique->getExtension()) : null;
        $this->get('session')->set('thematique', $thematique->getCode());
        $this->get('session')->set('siret', $siret);



        return new JsonResponse($ext);
    }
}
