<?php

namespace Actigraph\ActipageBaseBundle\Controller;

use Actigraph\ActipageBaseBundle\Entity\Actus;
use Actigraph\ActipageBaseBundle\Entity\FormuleSell;
use Actigraph\ActipageBaseBundle\Entity\Objets;
use Actigraph\ActipageBaseBundle\Entity\Pages;
use Actigraph\ActipageBaseBundle\Entity\ParticipantJeux;
use Actigraph\ActipageBaseBundle\Services\ActipageService;
use Actigraph\ActipageBaseBundle\Services\EspaceClient\EspaceClientService;
use Actigraph\ActipageBaseBundle\Services\CaptchaService;
use Actigraph\ActipageBaseBundle\Services\FilesService;
use Actigraph\ActipageBaseBundle\Services\NewsletterService;
use Actigraph\ActipageModulesReferentiel\FrontModules;
use Actigraph\ActipageBaseBundle\Entity\Formule;
use Actigraph\ActipageBaseBundle\Entity\FormuleProfile;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\ORM\EntityManagerInterface;
use \DateTime as DateTime;
use \DateInterval as DateInterval;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Twig\Environment;

class ActipageModuleController extends ActipageBaseController
{

    private $params, $translator;

    public function __construct($params, TranslatorInterface $translator)
    {
        $this->params = $params;
        $this->translator = $translator;
    }

    //Les fonctions doivent avoir les paramétres suivants (mafonction) :
    // mafonctionAction(Request $request, $globalParams = null, ActipageService $actipageService, NewsletterService $newsletterService, $em = null)

    /*
     * Modules classiques (dans les pages)
     */

    public function getListActusAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService)
    {
        //TODO gerer les redirections externe de l'actu

        if (is_numeric($globalParams)) {
            $globalParams = array("typeId" => $globalParams);
        } else {
            $globalParams = json_decode($globalParams, true);
            if ($globalParams == false)
                $globalParams = array();//Si JSON pas bien fait dans la config on le transforme en tableau vide
        }
        $globalParams = array_merge(array("typeId" => 1, "messageNoActus" => "Pas d'information"), $globalParams);
        $actus = $actipageService->getActualitesByTypeId($globalParams["typeId"]);

        return $this->render('@ActigraphActipageBaseBundle/Modules/liste_actus.html.twig', array("actus" => $actus, "params" => $globalParams));
    }

    public function getPdf2mapAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService)
    {
        $mapinfo = $actipageService->getPdf2MapInfoFromId($pageParams);
        if (is_array($mapinfo))
            return $this->render('@ActigraphActipageBaseBundle/Modules/pdf2map.html.twig', array(
                "mapinfo" => $mapinfo
            ));
        else //Pas trouvé
            return new Response("");
    }

    public function getGMapIframeAction(Request $request, $globalParams = null, $pageParams = null, $em = null)
    {
        $repositoryGmap = $em->getRepository('ActigraphActipageBaseBundle:GMapIframe');
        $gmap = $repositoryGmap->findOneBy(array("GMapIFrameID" => $pageParams));
        $gmapContent="";
        if($gmap)
            $gmapContent = $gmap->getGMapIFrameContent();

        return $this->render('@ActigraphActipageBaseBundle/Modules/GMapIframe.html.twig', array("gmapContent" => $gmapContent));

    }

    public function getFichesHorairesAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, $em = null)
    {
        $fichesInfos = $actipageService->getAllInfoFichesHoraire();

        if ($request->getMethod() == 'POST') {
            $result = array();
            $titre = "";
            $data = $request->request->all();
            $requestLaunch = false;
            $lieux = array();
            if (isset($data["categorieId"]) && $data["categorieId"] > 0) {
                $requestLaunch = true;
                $lieux = $actipageService->getLieuFicheHoraireFromCatgeorie($data["categorieId"]);
            }

            if (isset($data["ligneId"]) && $data["ligneId"] > 0) {
                $requestLaunch = true;
                $sqlLines = 'SELECT * FROM ficheshoraires_lignes WHERE id_ligne = :ligneId AND actif = 1';
                $query = $em->getConnection()->prepare($sqlLines);
                $query->bindParam(":ligneId", $data["ligneId"]);
                $query->execute();

                $ficheshorairesligne = $query->fetchAll();
                foreach ($ficheshorairesligne as $fiches) {
                    $cleanedData = array();
                    foreach ($this->mb_unserialize($fiches["data"]) as $ficheData) {
                        $cleanedData[] = array(
                            "url" => $ficheData["url"],
                            "nom" => $ficheData["nom"]
                        );
                    }
                    $fiches["data"] = $cleanedData;
                    $result[] = $fiches;
                    $titre = "";
                }
            } elseif (isset($data["communeId"]) && $data["communeId"] > 0) {
                $requestLaunch = true;
                $sqlLines = 'SELECT * FROM ficheshoraires_commune_lignes LEFT JOIN ficheshoraires_lignes ON ficheshoraires_lignes.id_ligne = ficheshoraires_commune_lignes.id_ligne WHERE id_commune=:idCommune AND ficheshoraires_lignes.actif =1';
                $query = $em->getConnection()->prepare($sqlLines);
                $query->bindParam(":idCommune", $data["communeId"]);
                $query->execute();
                $ficheshorairescommuneligne = $query->fetchAll();

                foreach ($ficheshorairescommuneligne as $fiches) {
                    $cleanedData = array();
                    foreach ($this->mb_unserialize($fiches["data"]) as $ficheData) {
                        $cleanedData[] = array(
                            "url" => $ficheData["url"],
                            "nom" => $ficheData["nom"]
                        );
                    }
                    $fiches["data"] = $cleanedData;
                    $result[] = $fiches;
                }

                $sqlLines = 'SELECT * FROM ficheshoraires_communes WHERE id_commune=:idCommune';
                $query = $em->getConnection()->prepare($sqlLines);
                $query->bindParam(":idCommune", $data["communeId"]);
                $query->execute();
                $resultat = $query->fetch();
                $titre = "Commune : " . $resultat["nom_commune"];

            } elseif (isset($data["lieuId"]) && $data["lieuId"] > 0) {
                $requestLaunch = true;
                $sqlLines = 'SELECT * FROM ficheshoraires_lieu_lignes LEFT JOIN ficheshoraires_lignes ON ficheshoraires_lignes.id_ligne = ficheshoraires_lieu_lignes.id_ligne WHERE id_lieu=:idLieu AND ficheshoraires_lignes.actif =1';
                $query = $em->getConnection()->prepare($sqlLines);
                $query->bindParam(":idLieu", $data["lieuId"]);
                $query->execute();
                $ficheshoraireslieu = $query->fetchAll();

                foreach ($ficheshoraireslieu as $fiches) {
                    $cleanedData = array();
                    foreach ($this->mb_unserialize($fiches["data"]) as $ficheData) {
                        $cleanedData[] = array(
                            "url" => $ficheData["url"],
                            "nom" => $ficheData["nom"]
                        );
                    }
                    $fiches["data"] = $cleanedData;
                    $result[] = $fiches;
                }

                $sqlLines = 'SELECT * FROM ficheshoraires_lieux WHERE id_lieu=:lieuId';
                $query = $em->getConnection()->prepare($sqlLines);
                $query->bindParam(":lieuId", $data["lieuId"]);
                $query->execute();
                $resultat = $query->fetch();

                $titre = "Lieu : " . $resultat["nom_lieu"];
            }
            return $this->render('@ActigraphActipageBaseBundle/Modules/fichesHoraires.html.twig', array(
                    "request" => $request->request->all(),
                    "requestLaunched" => $requestLaunch,
                    "result" => $result,
                    "titre" => $titre,
                    "fichesData" => $fichesInfos,
                    "lieux" => $lieux
                )
            );
        }

        return $this->render('@ActigraphActipageBaseBundle/Modules/fichesHoraires.html.twig', array(
                "request" => "",
                "lieux" => "",
                "requestLaunched" => false,
                "fichesData" => $fichesInfos
            )
        );
    }

    public function getActuAgendaAction(Request $request, ActipageService $actipageService)
    {
        $actus = $actipageService->getActuIsAgenda();
        $allEvents = array();

        foreach ($actus as $actu) {
            $allEvents[] = array(
                'id' => $actu["actu_id"],
                'start' => strtotime($actu["actu_date_deb_eve"]),
                'end' => strtotime($actu["actu_date_fin_eve"]),
                'title' => $actu["actu_titre"],
                'content' => $actu["actu_accroche"],
                'image' => $actu["actu_image"],
                'link' => $actipageService->generatePath("detail_actu", array("idEncoded" => $actipageService->encodeId($actu["actu_id"])))
            );
        }

        $events = json_encode($allEvents);
        return $this->render('@ActigraphActipageBaseBundle/Modules/agenda.html.twig', array("actus" => $allEvents));

    }

    public function getJeuAction(Request $request, $globalParams = null, ActipageService $actipageService, NewsletterService $newsletterService, CaptchaService $captchaService, \Swift_Mailer $mailer, TranslatorInterface $translator, $em = null)
    {
        $sqlJeu = 'SELECT id_jeux, titre_jeux, code_gagnant, mail_admin FROM jeux WHERE actif=1 order by id_jeux desc';
        $query = $em->getConnection()->prepare($sqlJeu);
        $query->execute();
        $jeu = $query->fetch();
        if(!$jeu){
            return $this->render('@ActigraphActipageBaseBundle/Modules/jeu.html.twig', array("questions" => [], "jeu" => false));
        }

        $sqlQuestion = 'SELECT id_question,libelle_question,ordre_question FROM question WHERE id_jeux=:idJeu order by ordre_question';
        $query = $em->getConnection()->prepare($sqlQuestion);
        $query->bindParam(":idJeu", $jeu["id_jeux"]);
        $query->execute();
        $questions = $query->fetchAll();

        $questionsArray = array();

        foreach ($questions as $question) {

            $questionArray = array(
                "idQuestion" => $question["id_question"],
                "libQuestion" => $question["libelle_question"]
            );

            $sqlResponse = 'SELECT id_reponse,libelle_reponse,lettre,bonne_reponse FROM reponse WHERE id_question=:idQuestion order by lettre';
            $query = $em->getConnection()->prepare($sqlResponse);
            $query->bindParam(":idQuestion", $question["id_question"]);
            $query->execute();
            $responses = $query->fetchAll();

            $questionArray["reponse"] = $responses;
            array_push($questionsArray, $questionArray);
        }

        if ($request->getMethod() == 'POST') {
            $data = $request->request->all();

            $sql = "SELECT * FROM participant_jeux WHERE id_jeu=:idJeu AND mail=:mail";
            $query = $em->getConnection()->prepare($sql);
            $query->bindParam(":idJeu", $data["id_jeux"]);
            $query->bindParam(":mail", $data["mail"]);
            $query->execute();
            $ckeckIfParticipate = $query->fetchAll();

            if (empty($ckeckIfParticipate) && $captchaService->isCaptchaValid($data)) {
                $textemail = $jeu["titre_jeux"] . "\n\n";
                $code_joueur = "";
                $code_gagnant = $jeu["code_gagnant"];

                foreach ($data as $i => $datareponse) {
                    if (substr($i, 0, 7) == "reponse") {
                        $question = str_replace("reponse", "", $i);
                        $sql = "select libelle_question,ordre_question from question where id_question=:idQuestion";

                        $query = $em->getConnection()->prepare($sql);
                        $query->bindParam(":idQuestion", $question);
                        $query->execute();
                        $responses = $query->fetch();

                        $textemail .= $responses["libelle_question"] . " - " . $responses["ordre_question"];

                        $sql = "select libelle_reponse,bonne_reponse from reponse where id_question =:idQuestion and lettre=:valueResponse";
                        $query = $em->getConnection()->prepare($sql);
                        $query->bindParam(":idQuestion", $question);
                        $query->bindParam(":valueResponse", $datareponse);
                        $query->execute();
                        $response = $query->fetch();
                        $textemail .= " Réponse : " . $response["libelle_reponse"];

                        if ($response["bonne_reponse"] == 1) {
                            $textemail .= " (VRAI)";
                        } else {
                            $textemail .= " (FAUX)";
                        }
                        $textemail .= "\n\n";
                        $code_joueur .= $datareponse;
                    }
                }

                $textemail .= "\n\n";

                if ($code_joueur == $code_gagnant) {
                    $textemail .= "GAGNANT";
                } else {
                    $textemail .= "PERDANT";
                }

                $participantJeux = new ParticipantJeux();
                $participantJeux->setIdJeu($data["id_jeux"]);
                $participantJeux->setCivilite($data["civilite"]);
                $participantJeux->setNom($data["nom"]);
                $participantJeux->setPrenom($data["prenom"]);
                $participantJeux->setAdresse($data["adresse"]);
                $participantJeux->setCp($data["cp"]);
                $participantJeux->setVille($data["ville"]);
                $participantJeux->setMail($data["mail"]);
                $participantJeux->setTel($data["tel"]);
                $participantJeux->setCodeReponse($code_joueur);
                $participantJeux->setComplement("");
                $participantJeux->setDateParticipation(\DateTime::createFromFormat('Y-m-d H:i:s', date('Y-m-d H:i:s')));
                $this->getDoctrine()->getManager()->persist($participantJeux);
                $this->getDoctrine()->getManager()->flush();

                if (isset($data["newsletter"]) && $data["newsletter"] == 1) {
                    try {
                        $urlReturn = $actipageService->findPageWithModuleClass(FrontModules::MODULE_NEWSLETTER, false);

                        if ($urlReturn == false) {
                            $urlReturn = $actipageService->findPageWithModuleClass(FrontModules::MODULE_NEWSLETTER_AVANCEE, true);
                        }
                        $newsletterService->addNewInscrit($data, $urlReturn);
                        $this->addFlash(
                            'success',
                            $this->translator->trans("message.confirm.demandeinscriptionnewsletter")
                        );
                    } catch (\Exception $e) {
                        $message = $translator->trans($e->getMessage());
                        $this->addFlash(
                            'error',
                            $message
                        );
                    }
                }
                $paramsClient = $actipageService->getSiteParams();
                $emailFrom = $paramsClient["emailFrom"];

                if ($jeu["mail_admin"] != "") {
                    $message = $textemail . "\n\n";
                    $message .= "Email : " . $data["mail"] . "\n\n";
                    $message .= "Nom : " . $data["nom"];
                    $message .= "\n\nPrénom : " . $data["prenom"];
                    $message .= "\n\nadresse : " . $data["adresse"] . " " . $data["cp"] . " " . $data["ville"];
                    $message .= "\n\nTéléphone  : " . $data["tel"];

                    $message = (new \Swift_Message("Participant au jeu"))
                        ->setFrom($emailFrom)
                        ->setTo($jeu["mail_admin"])
                        ->setBody(
                            $message,
                            'text/html'
                        );
                    $mailer->send($message);

                    $this->addFlash(
                        'success',
                        'Votre participation au jeu a bien été prise en compte'
                    );
                }
            } else {
                //TODO captcha peut ne pas etre valide il faut adapter le message selon l'erreur du if
                $response = "Vous avez déjà participé à ce jeu, vous pouvez retenter votre chance ultérieurement";
                $this->addFlash(
                    'error',
                    $response
                );
            }
            return $this->render('@ActigraphActipageBaseBundle/Modules/jeu.html.twig', array("questions" => $questionsArray, "jeu" => $jeu["id_jeux"]));
        }
        return $this->render('@ActigraphActipageBaseBundle/Modules/jeu.html.twig', array("questions" => $questionsArray, "jeu" => $jeu["id_jeux"]));
    }

    public function getNewsletterSimpleAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, CaptchaService $captchaService, NewsletterService $newsletterService)
    {
        $urlReturn = $actipageService->findPageWithModuleClass(FrontModules::MODULE_NEWSLETTER, false);

        if ($urlReturn == false) {
            $urlReturn = $actipageService->findPageWithModuleClass(FrontModules::MODULE_NEWSLETTER_AVANCEE, true);
        }

        $data = array(
            "nom" => "",
            "prenom" => "",
            "mail" => $request->query->get("mail", ""),
            "removeMail" => "",
        );
        if ($request->getMethod() == "POST") {
            $dataPost = $request->request->all();

            if ($dataPost["action"] == "desinscription") {
                $data["removeMail"] = $dataPost["removeMail"];
                try {
                    if ($newsletterService->deleteInscrit($data, $urlReturn)) {
                        $this->addFlash(
                            'success',
                            $this->translator->trans("message.confirm.desinscriptionnewsletter")
                        );
                    }
                } catch (\Exception $e) {
                    $this->addFlash(
                        'error',
                        $this->translator->trans($e->getMessage())
                    );
                }
            } else {
                $data["nom"] = $dataPost["nom"];
                $data["prenom"] = $dataPost["prenom"];
                $data["mail"] = $dataPost["mail"];

                if (!$captchaService->isCaptchaValid($dataPost)) {
                    $this->addFlash(
                        'error',
                        $this->translator->trans("message.error.captchainvalid")
                    );
                } else {
                    try {
                        if ($newsletterService->addNewInscrit($data, $urlReturn)) {
                            $this->addFlash(
                                'success',
                                $this->translator->trans("message.confirm.demandeinscriptionnewsletter")
                            );
                        }
                    } catch (\Exception $e) {
                        $this->addFlash(
                            'error',
                            $this->translator->trans($e->getMessage())
                        );
                    }
                }
            }
        }
        return $this->render('@ActigraphActipageBaseBundle/Modules/newsletter_simple.html.twig', $data);
    }

    public function getNewsletterAvanceeAction(Request $request, ActipageService $actipageService, NewsletterService $newsletterService, TranslatorInterface $translator, CaptchaService $captchaService, $em = null)
    {
        $sqlGroupeType = 'SELECT * FROM newsletter_groupes_type WHERE id_type != 0 AND visible = 1';
        $query = $em->getConnection()->prepare($sqlGroupeType);
        $query->execute();
        $groupesTypes = $query->fetchAll();

        $allTypes = array();
        foreach ($groupesTypes as $type) {
            $sqlGroupe = "select * from newsletter_groupes WHERE groupe_type=:groupeType AND visible_front = 1 ORDER BY sort_order ASC";
            $query = $em->getConnection()->prepare($sqlGroupe);
            $query->bindParam(":groupeType", $type["id_type"]);
            $query->execute();
            $groupes = $query->fetchAll();

            $type["groupes"] = $groupes;

            array_push($allTypes, $type);
        }

        $urlReturn = $actipageService->findPageWithModuleClass(FrontModules::MODULE_NEWSLETTER_AVANCEE, false);
        $data = array(
            "nom" => "",
            "prenom" => "",
            "mail" => $request->query->get("mail", ""),
            "bdate" => "",
            "removeMail" => "",
        );

        if ($request->getMethod() == 'POST') {
            $dataForm = $request->request->all();

            if ($dataForm["action"] == "desinscription") {
                $data["removeMail"] = $dataForm["removeMail"];
                try {
                    if ($newsletterService->deleteInscrit($data, $urlReturn)) {
                        $messageConfirm = $translator->trans("message.confirm.desinscriptionnewsletter");
                        $this->addFlash(
                            'success',
                            $messageConfirm
                        );
                    }
                } catch (\Exception $e) {
                    $messageErreur = $translator->trans($e->getMessage());
                    $this->addFlash(
                        'error',
                        $messageErreur
                    );
                }
            } else {

                $groupeClient = array();
                foreach ($dataForm as $i => $dataUser) {
                    if (substr($i, 0, 12) == "choix_groupe") {
                        $idGroup = str_replace("choix_groupe", '', $i);
                        array_push($groupeClient, $idGroup);
                        $data["groupes"] = $groupeClient;
                    }
                }

                $data["nom"] = $dataForm["nom"];
                $data["prenom"] = $dataForm["prenom"];
                $data["mail"] = $dataForm["mail"];
                $data["bdate"] = $dataForm["date_annees"] . '-' . $dataForm["date_mois"] . '-' . $dataForm["date_jour"];

                if (!$captchaService->isCaptchaValid($dataForm)) {
                    $this->addFlash(
                        'error',
                        $translator->trans("message.error.captchainvalid")
                    );
                } else {
                    try {
                        if ($newsletterService->addNewInscrit($data, $urlReturn)) {
                            $messageConfirm = $translator->trans("message.confirm.demandeinscriptionnewsletter");
                            $this->addFlash(
                                'success',
                                $messageConfirm
                            );
                        }
                    } catch (\Exception $e) {
                        $messageErreur = $translator->trans($e->getMessage());
                        $this->addFlash(
                            'error',
                            $messageErreur
                        );
                    }
                }
            }
        }
        return $this->render('@ActigraphActipageBaseBundle/Modules/newsletter_avancee.html.twig', array(
            "allTypes" => $allTypes, "mail" => $request->query->get("mail", "")
        ));
    }

    public function getDepotCandidatureAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, CaptchaService $captchaService, Environment $templating, \Swift_Mailer $mailer, $em = null, TranslatorInterface $translator)
    {
        if ($globalParams == "")
            $paramsModule = array();
        else
            $paramsModule = json_decode($globalParams, true);


        $paramsClient = $actipageService->getSiteParams();
        $emailFrom = $paramsClient["emailFrom"];
        $emailDestinataireDefault = array();

        if (isset($paramsModule["emailDestinataire"])) {
            if (is_array($paramsModule["emailDestinataire"]))
                $emailDestinataireDefault = $paramsModule["emailDestinataire"];
            else
                $emailDestinataireDefault[] = $paramsModule["emailDestinataire"];
        } else { //Si pas de configuration alors on prend l'email d'expedition faute de mieux
            $emailDestinataireDefault = $emailFrom;
        }

        $themes = array();
        if (isset($paramsModule["themes"]) && is_array($paramsModule["themes"])) {
            foreach ($paramsModule["themes"] as $key => $currentTheme) {
                if (isset($currentTheme["nom"])) {
                    if (!isset($currentTheme["emailDestinataire"])) //Si je n'ai pas d'email de destinaires pour ce theme je prend les emails par défaut
                        $themeEmailDestinataire = $emailDestinataireDefault;
                    else {
                        if (is_array($currentTheme["emailDestinataire"]))
                            $themeEmailDestinataire = $currentTheme["emailDestinataire"];
                        else
                            $themeEmailDestinataire = array($currentTheme["emailDestinataire"]);
                    }
                    $themes[] = array(
                        "id" => $key,
                        "nom" => $currentTheme["nom"],
                        "emailDestinataire" => $themeEmailDestinataire);
                }
            }
        }


        if ($request->getMethod() == 'POST') {
            $result = array();
            $titre = "";
            $data = $request->request->all();

            if (!$captchaService->isCaptchaValid($data)) {
                $this->addFlash(
                    'error',
                    $translator->trans("message.error.captchainvalid")
                );
            } else {
                if (isset($data["theme"])) {
                    $theme = $themes[$data["theme"]];
                    $emailDestinataire = $theme["emailDestinataire"];
                } else {
                    $theme = false;
                    $emailDestinataire = $emailDestinataireDefault;
                }

                $message = (new \Swift_Message("Nouvelle candidature"))
                    ->setFrom($emailFrom)
                    ->setTo($emailDestinataire)
                    ->setBody($templating->render(
                        '@ActigraphActipageBaseBundle/Mails/candidature.html.twig',
                        array(
                            'baseUrl' => $request->getSchemeAndHttpHost(),
                            'data' => $data,
                            'theme' => $theme
                        )
                    ),
                        'text/html'
                    );

                /** @var File $cv */
                $cv = $request->files->get("cv", false);
                if ($cv) {
                    $message->attach(\Swift_Attachment::fromPath($cv->getPathname())->setFilename($cv->getClientOriginalName()));
                }
                $mailer->send($message);
                $this->addFlash(
                    'success',
                    $translator->trans("message.confirm.requestSended")
                );
            }
            return $this->render('@ActigraphActipageBaseBundle/Modules/formulaire_candidature.html.twig', array(
                "data" => $data,
                "themes" => $themes
            ));
        }

        return $this->render('@ActigraphActipageBaseBundle/Modules/formulaire_candidature.html.twig', array(
            "themes" => $themes
        ));
    }

    public function getLocationCarAction(Request $request, $globalParams = null, ActipageService $actipageService, CaptchaService $captchaService, Environment $templating, \Swift_Mailer $mailer, $em = null, TranslatorInterface $translator)
    {
        $dataGet = array(
            "depart" => $request->query->get("depart", ""),
            "destination" => $request->query->get("arrivee", ""),
        );
        if ($globalParams == "")
            $paramsModule = array();
        else
            $paramsModule = json_decode($globalParams, true);

        if ($request->getMethod() == 'POST') {
            $dataForm = $request->request->all();

            if (!$captchaService->isCaptchaValid($dataForm)) {
                $this->addFlash(
                    'error',
                    $translator->trans("message.error.captchainvalid")
                );
                return $this->render('@ActigraphActipageBaseBundle/Modules/location-car.html.twig', array(
                    "data" => $dataForm,
                    "paramsModule" => $paramsModule
                ));
            } else {
                $paramsClient = $actipageService->getSiteParams();
                $emailFrom = $paramsClient["emailFrom"];

                $emailDestinataire = array();
                if (isset($paramsModule["emailDestinataire"])) {
                    if (is_array($paramsModule["emailDestinataire"]))
                        $emailDestinataire = $paramsModule["emailDestinataire"];
                    else
                        $emailDestinataire[] = $paramsModule["emailDestinataire"];
                } else { //Si pas de configuration alors on prend l'email d'expedition faute de mieux
                    $emailDestinataire = $emailFrom;
                }

                $message = (new \Swift_Message("Demande de location de car depuis le site"))
                    ->setFrom($emailFrom)
                    ->setTo($emailDestinataire)
                    ->setBody($templating->render(
                        '@ActigraphActipageBaseBundle/Mails/demande_devis.html.twig',
                        array(
                            'baseUrl' => $request->getSchemeAndHttpHost(),
                            'data' => $dataForm,
                        )
                    ),
                        'text/html'
                    );

                /** @var File $cv */
                $fichier = $request->files->get("fichier", false);
                if ($fichier) {
                    $message->attach(\Swift_Attachment::fromPath($fichier->getPathname())->setFilename($fichier->getClientOriginalName()));
                }

                $mailer->send($message);
                $this->addFlash(
                    'success',
                    $translator->trans("message.confirm.requestSended")
                );

                return $this->render('@ActigraphActipageBaseBundle/Modules/location-car.html.twig', array(
                    "data" => array(),
                    "paramsModule" => $paramsModule
                ));
            }
        }
        return $this->render('@ActigraphActipageBaseBundle/Modules/location-car.html.twig', array(
            "data" => $dataGet,
            "paramsModule" => $paramsModule
        ));
    }

    public function getInfoTraficAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, $em = null)
    {
        if (is_numeric($globalParams)) {
            $globalParams = array("typeId" => $globalParams);
        } else {
            $globalParams = json_decode($globalParams, true);
            if ($globalParams == false)
                $globalParams = array();//Si JSON pas bien fait dans la config on le transforme en tableau vide
        }
        $globalParams = array_merge(array("sourceOption" => 10, "messageNoActus" => "Pas de perturbations sur le réseau","source"=>"actus","affichage"=>array("type"=>"indices")), $globalParams);
        $globalParams["preselect"] = $request->query->get("indice", "");

        if ($globalParams["source"] == "actus") {
            $actus = $actipageService->getActualitesByTypeId($globalParams["sourceOption"]);
            $repositoryLines = $em->getRepository('ActigraphActipageBaseBundle:Lignes');
            $allLines = array();
            $perturbations = array();
            foreach ($actus as $actu) {
                $perturbLignes = array();
                $plageHoraire = json_decode($actu->getPlageHoraire());
                if (count($actu->getLignes()) > 0) {
                    foreach ($actu->getLignes() as $ligne) {
                        $lineConcerned = $repositoryLines->findOneBy(array("lineexternalcode" => $ligne->getLineexternalcode()));
                        $urlLigne = $actipageService->findPageWithModuleClass(FrontModules::MODULE_INFOTRAFIC, false);
                        if (!$urlLigne)
                            continue;

                        $lineCode = preg_replace('/[^A-Za-z0-9\-]/', '', $lineConcerned->getLinecode());
                        $lineCode = strtolower($lineCode);
                        $currentLigne = array(
                            "id" => $lineConcerned->getLineexternalcode(),
                            "indiceId" => "",//TODO pourquoi vide ?
                            "code" => $lineCode,
                            "nom" => $lineCode,
                            "urlLigne" => $urlLigne . "?indice=" . $lineConcerned->getLineexternalcode(),
                            "ordre"=>$lineConcerned->getOrdre()
                        );
                        $perturbLignes[] = $currentLigne;
                        array_push($allLines, $currentLigne);
                    }
                    $allLines = array_unique($allLines, SORT_REGULAR);
                    usort($allLines, function ($item1, $item2) {
                        return $item1['ordre'] <=> $item2['ordre'];
                    });
                }


                $debut = $actu->getActuDateDebEve();
                $fin = $actu->getActuDateFinEve();
                if ($debut->format("d/m/y") == $fin->format("d/m/y") && $debut->format("H:i") == "00:00" && $fin->format("H:i") == "23:59") {
                    $agenda = "<div class='date-agenda'>(Le " . $debut->format("d/m/y") . ")</div>";
                } else if ($debut->format("H:i") == "00:00" && $fin->format("H:i") == "23:59") {
                    $agenda = "<div class='date-agenda'>(Du " . $debut->format("d/m/y") . " au " . $fin->format("d/m/y") . ")</div>";
                } else if ($debut->format("d/m/y") == $fin->format("d/m/y")) {
                    $agenda = "<div class='date-agenda'>(Le " . $debut->format("d/m/y") . " de <span class='label label-default'>" . $debut->format("H") . "H" . $debut->format("i") . "</span> à <span class='label label-default'>" . $fin->format("H") . "H" . $fin->format("i") . ")</span></div>";
                } else {
                    $agenda = "<div class='date-agenda'>(Du " . $debut->format("d/m/y") . "<span class='label label-default'>" . $debut->format("H:i") . "</span> au " . $fin->format("d/m/y") . "<span class='label label-default'>" . $fin->format("H:i") . "</span>)</div>";
                }

                $perturbations[] = array(
                    "id" => $actu->getActuId(),
                    "titre" => $actu->getActuTitre(),
                    "message" => $actu->getActuAccroche(),
                    "contenu" => $actu->getActuTexte(),
                    "agenda" => $agenda,
                    "actuLink" => $actipageService->generatePath("detail_actu", array("idEncoded" => $actipageService->encodeId($actu->getActuId()))),
                    "lignes" => $perturbLignes,
                    "plageHoraire" => $plageHoraire,
                    "gravite" => $actu->getGraviteActu()
                );

            }
        }
        if ($globalParams["affichage"]["type"] == "liste") {
            $viewToRedirect = "@ActigraphActipageBaseBundle/Modules/info_trafic_liste.html.twig";
        } else if ($globalParams["affichage"]["type"] == "indices") {
            $viewToRedirect = "@ActigraphActipageBaseBundle/Modules/info_trafic_indices.html.twig";
        }

        return $this->render($viewToRedirect, array(
            "actus" => $perturbations,
            "lines" => $allLines,
            "params" => $globalParams
        ));
    }

    public function getFormAlertesSMSAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, $em = null, TranslatorInterface $translator, NewsletterService $newsletterService, CaptchaService $captchaService)
    {
        if (is_numeric($globalParams)) {
            $globalParams = array("typeId" => $globalParams);
        } else {
            $globalParams = json_decode($globalParams, true);
            if ($globalParams == false)
                $globalParams = array();//Si JSON pas bien fait dans la config on le transforme en tableau vide
        }
        $globalParams = array_merge(array("allowNewsletterInscription" => true), $globalParams);

        $data = array(
            "tel" => "",
            "nom" => "",
            "mail" => "",
            "prenom" => "",
        );

        $lignes = $em->getRepository('ActigraphActipageBaseBundle:Lignes')->findBy(array("affiche" => 1), array("ordre" => "ASC"));

        if ($request->getMethod() == 'POST') {
            $dataForm = $request->request->all();

            if (!$captchaService->isCaptchaValid($dataForm)) {
                $this->addFlash(
                    'error',
                    $translator->trans("message.error.captchainvalid")
                );
            } else {
                if (isset($dataForm["action"]) && $dataForm["action"] == "inscription") {
                    $data["tel"] = $dataForm["tel"];
                    $data["nom"] = $dataForm["nom"];
                    $data["prenom"] = $dataForm["prenom"];

                    $formErreurs = array();
                    if (strlen(trim($data["tel"])) == 0 || !is_numeric($data["tel"])) {
                        $formErreurs[] = $translator->trans("message.error.invalidphonenumber");
                    }
                    if (strlen(trim($data["nom"])) == 0) {
                        $formErreurs[] = $translator->trans("message.error.emptyname");
                    }
                    if (strlen(trim($data["prenom"])) == 0) {
                        $formErreurs[] = $translator->trans("message.error.emptyfirstname");
                    }
                    $inscriptionsLignes = array();
                    foreach ($dataForm as $dateFormKey => $dataFormValue) {
                        if (strpos($dateFormKey, "|") !== false) {
                            list($ligneExternalCode, $inutile) = explode("|", $dateFormKey);
                            $inscriptionsLignes[] = $ligneExternalCode;
                        }
                    }
                    if (count($inscriptionsLignes) == 0) {
                        $formErreurs[] = $translator->trans("message.error.emptyselectedlignes");
                    }

                    if (count($formErreurs) == 0) {
                        if (isset($dataForm["newsletter"]) && $dataForm["newsletter"] == 1) {
                            $data["mail"] = $dataForm["mail"];
                            try {
                                $urlReturn = $actipageService->findPageWithModuleClass(FrontModules::MODULE_NEWSLETTER, false);
                                if (!$urlReturn)
                                    $urlReturn = $actipageService->findPageWithModuleClass(FrontModules::MODULE_NEWSLETTER_AVANCEE, true);
                                if ($newsletterService->addNewInscrit($data, $urlReturn)) {
                                    $this->addFlash(
                                        'success',
                                        $this->translator->trans("message.confirm.demandeinscriptionnewsletter")
                                    );
                                }
                            } catch (\Exception $e) {
                                $this->addFlash(
                                    'error',
                                    $this->translator->trans($e->getMessage())
                                );
                            }
                        }

                        $actipageService->inscriptionAlertSMS($data["nom"], $data["prenom"], $data["tel"], $inscriptionsLignes); //TODO Liste des lignes externalcode ici
                        $this->addFlash(
                            'success',
                            $this->translator->trans("message.confirm.requestSended")
                        );
                    } else {
                        $this->addFlash("error", implode("<br>", $formErreurs));
                    }
                } else {
                    $data["tel2"] = $dataForm["tel2"];

                    $formErreurs = array();
                    if (strlen(trim($data["tel2"])) == 0 || !is_numeric($data["tel2"])) {
                        $formErreurs[] = $translator->trans("message.error.invalidphonenumber");
                    }

                    if (count($formErreurs) == 0) {
                        $actipageService->desinscriptionAlertesSMS($data["tel2"]);
                        $this->addFlash(
                            'success',
                            $this->translator->trans("message.confirm.requestSended")
                        );
                    } else {
                        $this->addFlash("error", implode("<br>", $formErreurs));
                    }
                }
            }
        }
        return $this->extendAndRender('@ActigraphActipageBaseBundle/Modules/formulaire_inscriptionsms.html.twig', array(
            "data" => $data,
            "lignes" => $lignes,
            "params" => $globalParams
        ), "FormAlertesSMS", array(), $actipageService);
    }

    public function getFormulaireTimeoAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, $em = null){
        $params = json_decode($globalParams, true);

        if ($globalParams == "")
            $globalParams = array();
        else {
            $globalParams = json_decode($globalParams, true);
            if (!$globalParams)
                $globalParams = array();
        }
        $globalParams = array_merge(array("urliFrame" => ""), $globalParams);

        $postData = $request->request->all();
        if(isset($postData["a"])){
            $action="acti.php?a=".$postData["a"];
            if(isset($postData["arret"])){
                $action.="&arret=".$postData["arret"];
            }
            if(isset($postData["ligne_sens"])){
                $action.="&ligne_sens=".$postData["ligne_sens"];
            }
            if(isset($postData["code_arret"])){
                $action.="&code_arret=".$postData["code_arret"];
            }
            if(isset($postData["ligne"])){
                $action.="&ligne=".$postData["ligne"];
            }
            if(isset($postData["refs"])){
                $action.="&refs=".$postData["refs"];
            }
            if(isset($postData["sens"])){
                $action.="&sens=".$postData["sens"];
            }
            if(isset($postData["refs"]) && isset($postData["code_arret"])){
                $action.="&list_refs=".$postData["refs"]."_".$postData["code_arret"];
            }
        }else{
            $action="relais.html.php";
        }

        return $this->render('@ActigraphActipageBaseBundle/Modules/formulaire_timeo.html.twig', array(
            "url"=>$globalParams["urliFrame"].$action
        ));
    }

    /*
     * Modules en page d'accueil (intégrable dans le site)
     */

    public function getFormulaireTimeoAccueilModuleAction(Request $request, $globalParams = null)
    {
        $params = $globalParams;
        return $this->render('@ActigraphActipageBaseBundle/ModuleAccueil/formulairetimeo_accueil.html.twig', array(
            "params" => $params
        ));

    }

    public function getNewsletterAccueilModuleAction(Request $request, $globalParams = null, ActipageService $actipageService, NewsletterService $newsletterService, $em = null)
    {
        $params = $globalParams;
        return $this->render('@ActigraphActipageBaseBundle/ModuleAccueil/newsletter_accueil.html.twig', array(
            "params" => $params
        ));
    }

    public function getLocationCarAccueilModuleAction(Request $request, $globalParams = null, ActipageService $actipageService, $em = null)
    {
        $params = $globalParams;
        return $this->render('@ActigraphActipageBaseBundle/ModuleAccueil/location-car.html.twig', array(
            "params" => $params,
        ));
    }

    public function getDiapoActuAccueilModuleAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, $em = null)
    {
        $params = json_decode($globalParams);
        $defaultImage = $params->defaultImage;
        $defaultImageByType = $params->defaultImageByType;
        $hideText = $params->hideText;
        if(isset($params->idTypeActu))
            $idTypeActu = $params->idTypeActu;
        else
            $idTypeActu = $pageParams;

        return $this->render('@ActigraphActipageBaseBundle/ModuleAccueil/actu_diapo.html.twig', array(
            "typeActu" => $idTypeActu,
            "defaultImage" => $defaultImage,
            "defaultImageByType" => $defaultImageByType,
            "hideText" => $hideText
        ));
    }

    public function getTwitterModuleAction(ActipageService $actipageService, $globalParams = null)
    {
        $params = json_decode($globalParams);

        return $this->render('@ActigraphActipageBaseBundle/ModuleAccueil/twitter.html.twig', array(
            "params" => $params,
        ));
    }

    public function getMeteoModuleAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, $em = null)
    {

        return $this->render('@ActigraphActipageBaseBundle/ModuleAccueil/meteo.html.twig', array(
            "params" => $globalParams,
        ));

    }

    public function getActuAccueilAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, $em = null)
    {
        return $this->render("@ActigraphActipageBaseBundle/ModuleAccueil/actu_accueil_line.html.twig", array(
            "globalParams" => $globalParams
        ));
    }

    public function getDiapoAccueilAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, $em = null)
    {
        return $this->render('@ActigraphActipageBaseBundle/ModuleAccueil/diapo_accueil.html.twig', array(
            "idDiaporama" => $pageParams
        ));
    }

    public function getNavitiaIframeAccueilAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, $em = null)
    {
        return $this->render('@ActigraphActipageBaseBundle/ModuleAccueil/navitia_iframe.html.twig', array());
    }

    public function getFormulaireDeContactAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, CaptchaService $captchaService, Environment
    $templating, \Swift_Mailer $mailer, $em = null)
    {
        if ($globalParams == "")
            $paramsModule = array();
        else {
            $paramsModule = json_decode($globalParams, true);
            if (!$paramsModule)
                $paramsModule = array();
        }

        $paramsClient = $actipageService->getSiteParams();
        $emailFrom = $paramsClient["emailFrom"];
        $emailDestinataireDefault = array();
        $disableMotif = false;
        if (array_key_exists("disableMotif", $paramsModule)) {
            $disableMotif = $paramsModule["disableMotif"];
        }
        if (isset($paramsModule["emailDestinataire"])) {
            if (is_array($paramsModule["emailDestinataire"]))
                $emailDestinataireDefault = $paramsModule["emailDestinataire"];
            else
                $emailDestinataireDefault[] = $paramsModule["emailDestinataire"];
        } else { //Si pas de configuration alors on prend l'email d'expedition faute de mieux
            $emailDestinataireDefault = $emailFrom;
        }

        $themes = array();
        if (isset($paramsModule["themes"]) && is_array($paramsModule["themes"])) {
            foreach ($paramsModule["themes"] as $key => $currentTheme) {
                if (isset($currentTheme["nom"])) {
                    if (!isset($currentTheme["emailDestinataire"])) //Si je n'ai pas d'email de destinaires pour ce theme je prend les emails par défaut
                        $themeEmailDestinataire = $emailDestinataireDefault;
                    else {
                        if (is_array($currentTheme["emailDestinataire"]))
                            $themeEmailDestinataire = $currentTheme["emailDestinataire"];
                        else
                            $themeEmailDestinataire = array($currentTheme["emailDestinataire"]);
                    }
                    $themes[] = array(
                        "id" => $key,
                        "nom" => $currentTheme["nom"],
                        "emailDestinataire" => $themeEmailDestinataire);
                }
            }
        }

        if ($request->getMethod() == 'POST') {
            $result = array();
            $titre = "";
            $data = $request->request->all();

            if ($captchaService->isCaptchaValid($data)) {
                if (isset($data["theme"])) {
                    $theme = $themes[$data["theme"]];
                    $emailDestinataire = $theme["emailDestinataire"];
                } else {
                    $theme = false;
                    $emailDestinataire = $emailDestinataireDefault;
                }
                $message = (new \Swift_Message("Nouvelle demande de contact"))
                    ->setFrom($emailFrom)
                    ->setTo($emailDestinataire)
                    ->setBody($templating->render(
                        '@ActigraphActipageBaseBundle/Mails/demande_contact.html.twig',
                        array(
                            'baseUrl' => $request->getSchemeAndHttpHost(),
                            'data' => $data,
                            'theme' => $theme
                        )
                    ),
                        'text/html'
                    );
                $mailer->send($message);

                $this->addFlash(
                    'success',
                    $this->translator->trans("message.confirm.requestSended")
                );
                return $this->render('@ActigraphActipageBaseBundle/Modules/formulaire_contact.html.twig', array("themes" => $themes, "disableMotif" => $disableMotif));
            } else {
                $this->addFlash(
                    'error',
                    $this->translator->trans("message.error.captchainvalid")
                );
                return $this->render('@ActigraphActipageBaseBundle/Modules/formulaire_contact.html.twig', array(
                    "data" => $data,
                    "themes" => $themes,
                    "disableMotif" => $disableMotif
                ));
            }
        }
        return $this->render('@ActigraphActipageBaseBundle/Modules/formulaire_contact.html.twig', array("themes" => $themes, "disableMotif" => $disableMotif));
    }

    public function getMeilleurFormuleAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, $em = null)
    {

        $params = json_decode($globalParams);

        $repositoryTypeDeplacement = $em->getRepository('ActigraphActipageBaseBundle:TypeDeplacement');
        $repositoryTypeVoyageur = $em->getRepository('ActigraphActipageBaseBundle:TypeVoyageur');
        $repositoryTitre = $em->getRepository('ActigraphActipageBaseBundle:Titre');
        $repositoryTitreFormule = $em->getRepository('ActigraphActipageBaseBundle:TitreFormule');
        $repositoryTitreTarif = $em->getRepository('ActigraphActipageBaseBundle:TitreTarif');

        $typeDeplacement = $repositoryTypeDeplacement->findAll();
        $typeVoyageur = $repositoryTypeVoyageur->findAll();
        $titreFormule = $repositoryTitreFormule->findAll();

        $repositoryPages = $em->getRepository('ActigraphActipageBaseBundle:Pages');

        $allFormules = array();


        $pages = $params->liens;
        foreach ($titreFormule as $formule) {
            $typeVoyage = $formule->getIdTypeVoyageur();
            $typeDep = $formule->getIdTypeDeplacement();
            $titre = $repositoryTitre->findOneBy(array("idTitre" => $formule->getIdTitre()));
            $tarif = $repositoryTitreTarif->findOneBy(array("idTitre" => $formule->getIdTitre()));
            $link = "";
            foreach ($pages as $page) {
                if ($page->value == $titre->getTypeTitre()) {
                    $link = $page->idPage;
                }
            }
            $pageConcerned = $repositoryPages->findOneBy(array("pageId" => $link));
            $urlObj = "";
            if (!empty($pageConcerned)) {
                $objetConcerned = $pageConcerned->getObjet();
                $urlObj = $actipageService->generateUrlForObjet($objetConcerned);
            }

            $allFormules[] = array(
                "typeVoyageur" => $typeVoyage,
                "typeDeplacement" => $typeDep,
                "titreNom" => $titre->getNomTitre(),
                "descriptifTitre" => $titre->getDescriptifTitre(),
                "ordreTitre" => $titre->getOrdreTitre(),
                "ventreTitre" => $titre->getVenteTitre(),
                "typeTitre" => $titre->getTypeTitre(),
                "dateTarif" => $tarif->getDateTitreTarif(),
                "prixTarif" => $tarif->getPrixTitre(),
                "prisValide" => $tarif->getPrixValide(),
                "pageLink" => $urlObj
            );

        }

        return $this->render('@ActigraphActipageBaseBundle/Modules/meilleure_formule.html.twig', array(
            "typeDeplacement" => $typeDeplacement,
            "typeVoyageur" => $typeVoyageur,
            "allFormules" => $allFormules,
            "devise" => $params->devise

        ));

    }

    public function getMeilleureFormuleV2(Request $request)
    {
        $formuleSells = $this->getDoctrine()->getRepository(FormuleSell::class)->findAll();
        $profiles = $this->getDoctrine()->getRepository(FormuleProfile::class)->findAll();
        if ($request->getMethod() == 'POST') {
            $name = $request->get('profile');
            $pref = $request->get('pref');

            if ($name == null || $pref == null) {
                $this->addFlash('danger', 'Vous devez remplir tous les champs.');

                return $this->render('@ActigraphActipageBaseBundle/Modules/meilleure_formuleV2.html.twig', [
                    'formules' => [],
                    'formuleSells' => $formuleSells,
                    'profiles' => $profiles,
                    'profile' => $name ?? null,
                    'pref' => $pref ?? null,
                ]);
            }

            $formules = $this->getDoctrine()->getRepository(Formule::class)->getFormules($name, $pref);
        }

        return $this->render('@ActigraphActipageBaseBundle/Modules/meilleure_formuleV2.html.twig', [
            'formules' => $formules ?? [],
            'formuleSells' => $formuleSells,
            'profiles' => $profiles,
            'profile' => $name ?? null,
            'pref' => $pref ?? null,
        ]);
    }

    public function getEspaceClientAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, EspaceClientService $espaceClientService, $em = null)
    {
        $paramsSite = $actipageService->getSiteParams();
        if(!isset($paramsSite["espaceClient"]))
            return new Response("");

        $paramsEspaceClient = $paramsSite["espaceClient"];

        if ($request->getMethod() == 'POST') {
            $arrayOfData = $request->request->all();
            $result = $espaceClientService->validateData($arrayOfData);

            if (is_array($result)) {
                if (count($result) > 0) {
                    $message = '';
                    foreach ($result as $error) {
                        $message .= $error . "  -  ";
                    }
                    $this->addFlash(
                        'error',
                        $message
                    );
                }
            } else {
                $espaceClientService->saveData($arrayOfData);
            }

        }
        return $this->render('@ActigraphActipageBaseBundle/Modules/EspaceClient/form_espaceclient.html.twig', array(
            "paramsEspaceClient" => $paramsEspaceClient
        ));
    }

    public function getGalerieAction(Request $request, $globalParams = null, $pageParams = null, ActipageService $actipageService, EspaceClientService $espaceClientService, FilesService $filesService, $em = null)
    {
        $repositoryGaleries = $em->getRepository('ActigraphActipageBaseBundle:Galeries');
        $repositoryGaleriesImages = $em->getRepository('ActigraphActipageBaseBundle:GaleriesImages');
        $galerieImagesConcerned = $repositoryGaleriesImages->findBy(["idGalerie"=>$pageParams, "visible"=>1], ['ordre' => 'ASC']);
        $galerieConcerned = $repositoryGaleries->findOneBy(["id"=>$pageParams]);

        return $this->render('@ActigraphActipageBaseBundle/Modules/galerie.html.twig', array(
            "path"=>'/photos/Galeries/'.$galerieConcerned->getFolder()."/",
            "listImage" => $galerieImagesConcerned
        ));
    }


    private function mb_unserialize($string)
    {
        $string2 = preg_replace_callback(
            '!s:(\d+):"(.*?)";!s',
            function ($m) {
                $len = strlen($m[2]);
                $result = "s:$len:\"{$m[2]}\";";
                return $result;

            },
            $string);
        return unserialize($string2);
    }

}
