<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Cgu;
use AppBundle\Entity\CguUtilisateur;
use AppBundle\Entity\Entete;
use AppBundle\Entity\Historique;
use AppBundle\Form\CGUType;
use AppBundle\Form\EnteteType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class HistoriqueAdminController
 * @package AppBundle\Controller
 * @Route("/panel")
 */
class AdminController extends Controller
{
    /**
     * @return array
     * @Route("/historique", name="historique_index")
     * @Template("@App/Admin/listHistorique.html.twig")
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function historiqueIndexAction()
    {
        $histo = $this->getDoctrine()->getRepository("AppBundle:Historique")->findBy([],['date'=>'desc']);
        $entete = $this->getDoctrine()->getManager()->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'Historique']);

        return [
            'histo' => $histo,
            'entete'=>$entete
        ];
    }

    /**
     * @Route("/cgu/update", name="update_cgu")
     * @Template("@App/Admin/cguUpdate.html.twig")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function cguUpdateAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'GestionCGU']);

        $status = 200;
        $errors=[];

        $Cgus = $em->getRepository('AppBundle:Cgu')->findBy([], ['dateUpdated'=>'DESC']);

        if (!empty($Cgus))
            $currentCgu = $Cgus[0];
        else
            $currentCgu = new Cgu();

        //Couldn't pass $currentCgu as data because doctrine would overwrite previous entry
        $form = $this->createForm(CGUType::class, null, ['data'=>[$currentCgu->getIntitule()]]);
        $form->handleRequest($request);

        if ($form->isValid())
        {
            $data = $form->getData();

            if($status==200)
            {
                /** @var Cgu $cgu */
                $cgu = new Cgu();
                $cgu->setDateUpdated(new \DateTime());
                $cgu->setIntitule($data['intitule']);
                $histo = new Historique('Modification', 'CGU', $this->getUser()->getUsername()." a modifié les CGU", $this->getUser());

                $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('SUCCESS_CGU_CREATED'));




                $em->persist($cgu);
                $em->persist($histo);
                $em->flush();

                //todo : implement auto cgu validation for the admin that updated them

                $user= $this->getUser();
                $cguId = $em->getRepository('AppBundle:Cgu')->findBy([],['dateUpdated'=>'DESC'])[0]->getId();

                $cguUti = new CguUtilisateur();
                $cguUti->setUtilisateurID($user->getId());
                $cguUti->setCguId($cguId);
                $cguUti->setDateLecture(new \DateTime());
                $histo = new Historique('Confirmation', 'CGU', $user->getUsername().' a accepté les CGU '.$cguId, $user);

                $em->persist($histo);
                $em->persist($cguUti);
                $em->flush();

                return $this->redirectToRoute('panel');
            }
        }
        return [
            'form' => $form->createView(),
            'errors'=>$errors,
            'entete'=>$entete
        ];
    }

    /**
     * @Route("/entetes", name="entetes_list")
     * @Template("@App/Admin/entete.html.twig")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function listeEnteteAction()
    {

        $em = $this->getDoctrine()->getManager();
        $entetes = $em->getRepository('AppBundle:Entete')->findAll();
        $enteteF = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'GestionEntete']);
        $entetesWithMail = [];
        $entetesWithoutMail = [];


        $localisations = ['Connexion', 'Accueil', 'EspaceUsager', 'DocumentDisposition', 'Depots', 'ParticipationFinanciere', 'DossierAide',
            'OperationComptable', 'GestionUtilisateur', 'GestionThematique', 'GestionEntete', 'GestionCGU', 'Historique'];

        foreach ($localisations as $loc)
        {
            $exists = false;
            foreach($entetes as $ent)
            {
                if ($ent->getLocalisation() == $loc)
                    $exists = true;
            }
            if (!$exists)
            {
                $entete = new Entete();
                $entete->setLocalisation($loc);
                $entetes[] = $entete;
            }

        }

        foreach ($entetes as $entete)
        {
            if(!is_null($entete->getUtilisateurUpdate()))
            {
                $mail = $em->getRepository('AppBundle:Utilisateur')->findOneBy(['id'=>$entete->getUtilisateurUpdate()])->getEmail();
                $entetesWithMail[] = [$mail, $entete, ['descriptionWithoutHTML' => strip_tags($entete->getDescription())]];
            }
            else
                $entetesWithoutMail[] = $entete;
        }

        return [
            'entetes' => $entetes,
            'entete' => $enteteF,
            'entetesWithMail'=>$entetesWithMail,
            'entetesWithoutMail'=>$entetesWithoutMail

        ];
    }

    /**
     * @Route("/entetes/{localisation}", name="entete_update")
     * @Template("@App/Admin/updateEntete.html.twig")
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function UpdateEnteteAction(Request $request, $localisation)
    {
        $errors= [];
        $em = $this->getDoctrine()->getManager();
        $user= $this->getUser();
        $status = 200;

        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>$localisation]);

        if (is_null($entete))
        {
            $entete = new Entete();
            $entete->setLocalisation($localisation);
        }

        $form = $this->createForm(EnteteType::class, $entete);
        $form->handleRequest($request);

        if ($form->isValid())
        {
            $data = $form->getData();

            /** @var Entete $newEntete */
            $newEntete = $data;



            if ($status == 200)
            {
                $newEntete->setUtilisateurUpdate($user->getId());
                $newEntete->setDateUpdate(new \DateTime('now'));

                $histo = new Historique('Modification', 'Entete', $user->getUsername().' a modifié l\'entête de la page '.$localisation, $user);

                $em->persist($histo);
                $em->persist($newEntete);
                $em->flush();

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



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

}
