<?php

namespace AppBundle\Controller;

use AppBundle\AppBundle;
use AppBundle\Entity\CguUtilisateur;
use AppBundle\Entity\DemandePaiement;
use AppBundle\Entity\Historique;
use AppBundle\Entity\Interlocuteur;
use AppBundle\Entity\Utilisateur;
use AppBundle\Form\User\AddUserInterloc;
use AppBundle\Form\User\PasswordUpdate;
use AppBundle\Form\User\UserUpdate;
use DateTime;
use Doctrine\Common\Collections\Criteria;
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
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\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\MimeType\FileinfoMimeTypeGuesser;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * Class UtilisateurController
 * @package AppBundle\Controller
 */
class UtilisateurController extends Controller
{
    /**
     * @param Request $request
     * @Route("/espace-usager", name="espace_usager")
     * @Template("@App/Utilisateur/espaceUsager.html.twig")
     * @Security("is_granted(['ROLE_USER', 'ROLE_AGENT', 'ROLE_ADMIN'])")
     * @return array
     */
    public function espaceUsagerAction(Request $request)
    {
        /** @var Utilisateur $user */
        $user = $this->getUser();
        $doc = $this->getDoctrine();
        $em = $doc->getManager();

        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'EspaceUsager']);
        $agence = $em->getRepository('AppBundle:Agence')->findAll()[0];
        $thems = $agence->getThematique();

        $userForm = $this->createForm(UserUpdate::class, $user);
        $passwordForm = $this->createForm(PasswordUpdate::class);
        $interlocForm= $this->createForm(AddUserInterloc::class);

        return [
            'userForm' => $userForm->createView(),
            'pwForm' => $passwordForm->createView(),
            'interlocForm' => $interlocForm->createView(),
            'them' => $thems,
            'agence' => $agence,
            'user' => $user,
            'entete'=>$entete
        ];
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @Method("POST")
     * @Route("/user/update", name="user_update", options={"expose"=true})
     * @Security("is_granted(['ROLE_USER', 'ROLE_AGENT', 'ROLE_ADMIN'])")
     * @throws \Exception
     */
    public function updateUserAction(Request $request)
    {
        $errors = [];
        $status = 200;

        /** @var Utilisateur $user */
        $user = $this->getUser();

        $data = [
            'nom' => $request->get('nom'),
            'prenom' => $request->get('prenom'),
            'email' => $request->get('email'),
            'telephone' => $request->get('telephone')
        ];

        $new = $this->getDoctrine()->getRepository('AppBundle:Utilisateur')->findOneBy(['email'=>$data['email']]);

        if($user !== $new and !empty($new)) {
            $status = 500;
            $errors['fields']['email'] = $this->get('translator')->trans("ERROR_EMAIL_EXISTS");
        }
        if(strlen($data['telephone']) != 10 or !is_numeric($data['telephone'])) {
            $status = 500;
            $errors['fields']['telephone'] = $this->get('translator')->trans("ERROR_TELEPHONE_FORMAT");
        }

        if(empty($data['email']))
        {
            $status = 500;
            $errors['fields']['email'] = $this->get('translator')->trans("ERROR_EMAIL_VALIDATION");
        }

        if(empty($data['nom']))
        {
            $status = 500;
            $errors['fields']['email'] = $this->get('translator')->trans("ERROR_NAME_FIRSTNAME_FILLED");
        }

        if(empty($data['prenom']))
        {
            $status = 500;
            $errors['fields']['email'] = $this->get('translator')->trans("ERROR_NAME_FIRSTNAME_FILLED");
        }


        if($status == 200) {
            $em = $this->getDoctrine()->getManager();

            $user->setNom($data['nom']);
            $user->setPrenom($data['prenom']);
            $user->setEmail($data['email']);
            $user->setTelephone($data['telephone']);
            $user->setDateModification(new DateTime());

            $em->persist($user);
            $em->flush();
        }

        return new JsonResponse($errors, $status);
    }

    /**
     * @param Request $request
     * @param UserPasswordEncoderInterface $encoder
     * @return JsonResponse
     * @Method("POST")
     * @Route("/user/password/update", name="password_update", options={"expose"=true})
     * @Security("is_granted(['ROLE_USER', 'ROLE_AGENT', 'ROLE_ADMIN'])")
     */
    public function passWordUpdateAction(Request $request, UserPasswordEncoderInterface $encoder)
    {
        $errors = [];
        $status = 200;

        /** @var Utilisateur $user */
        $user = $this->getUser();

        $data = [
            'current' => $request->get('current'),
            'new' => $request->get('new'),
            'confirmation' => $request->get('confirmation'),
        ];

        $uppercase = preg_match('@[A-Z]@', $data['new']);
        $lowercase = preg_match('@[a-z]@', $data['new']);
        $number    = preg_match('@[0-9]@', $data['new']);

        $encoded = $encoder->encodePassword($user, $data['current']);

        if($encoded != $user->getPassword()) {
            $status = 500;
            $errors['fields']['current'] = $this->get('translator')->trans("ERROR_PASSWORD_DONT_MATCH");
        }

        if(!$uppercase || !$lowercase || !$number || strlen($data['new']) < 8) {
            $status = 500;
            $errors['fields']['new'] = null;
            $errors['fields']['confirmation'] = $this->get('translator')->trans("ERROR_NEW_PASSWORD_STRENGTH");
        }

        if($data['new'] != $data['confirmation']) {
            $status = 500;
            $errors['fields']['new'] = null;
            $errors['fields']['confirmation'] = $this->get('translator')->trans("ERROR_PASSWORD_CONFIRMATION_FAIL");
        }

        if($status == 200) {
                $em = $this->getDoctrine()->getManager();

                $newPassword = $encoder->encodePassword($user, $data['new']);
                $user->setMdp($newPassword);

                $histo = new Historique('Modification', 'Utilisateur', $user->getUsername().' a modifié son mot de passe', $user);

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


                $this->get('aeap.mailer')->sendMail('AEAP : Mot de passe modifié', $user->getEmail(), '@App/Email/mdpChange.html.twig', [
                'date' => new DateTime()
            ]);
        }

        return new JsonResponse($errors, $status);
    }

    /**
     * @param Request $request
     * @Route("/user/thematique/update", name="thematique_update", options={"expose"=true})
     * @return JsonResponse
     * @Security("is_granted(['ROLE_USER', 'ROLE_AGENT', 'ROLE_ADMIN'])")
     */
    public function changeThematiqueAction(Request $request)
    {
        /** @var Utilisateur $user */
        $user = $this->getUser();
        $doc = $this->getDoctrine();
        $repo = $doc->getRepository("AppBundle:Thematique");
        $getThems = $request->get('thems');
        $status = 200;
        $user->emptyThematique();

        foreach($getThems as $them) {
            $user->addThematique($repo->find($them));
        }

        $histo = new Historique('Modification', 'Thematique', $user->getUsername()." a modifié ses thematique(s) ", $user);

        $em = $doc->getManager();
        $em->persist($user);
        $em->persist($histo);
        $em->flush();

        return new JsonResponse(null, $status);
    }

    /**
     * @param Request $request
     * @Route("/user/interlocuteur/add", name="add_user_interlocuteur", options={"expose"=true})
     * @return JsonResponse
     * @Security("is_granted(['ROLE_USER', 'ROLE_AGENT', 'ROLE_ADMIN'])")
     */
    public function addUserInterlocuteurAction(Request $request)
    {
        $data = $request->request->all();
        $doc = $this->getDoctrine();

        $interloc = $doc->getRepository('AppBundle:Interlocuteur')->findOneBy([
            'siret'=>$data['siret'],
            'identifiant'=>$data['identifiant']
        ]);

        /** @var Utilisateur $user */
        $user = $this->getUser();

        if(empty($interloc)) {
            return new JsonResponse("Interlocuteur inconnu", 500);
        } else if ($user->getInterlocuteurSiret()->contains($interloc)) {
            return new JsonResponse("L'interlocuteur est déjà lié à votre compte utilisateur", 500);
        } else {
            $user->addInterlocuteur($interloc);
            $em = $doc->getManager();
            $em->persist($user); 

            $histo = new Historique('Modification', 'Utilisateur', $user->getUsername().' a ajouté l\'interlocuteur '. $interloc->getSiret(). 'à sa liste d\'interlocuteurs', $user);
            $em->persist($histo);


            try {
                $em->flush();

                return new JsonResponse();
            } catch (\Exception $e) {
                return new JsonResponse($e->getMessage(), 500);
            }
        }
    }

    /**
     * @Route("/mesEncaissements", name="encaissements_usager",options={"expose" = true})
     * @Template("@App/Utilisateur/encaissementsUsager.html.twig")
     * @Security("is_granted(['ROLE_USER', 'ROLE_AGENT', 'ROLE_ADMIN'])")
     */
    public function encaissementsListAction(Request $request)
    {

        /** @var Utilisateur $user */
        $user = $this->getUser();
        $em = $this->getDoctrine()->getManager();
        $session = new Session();
        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'OperationComptable']);
        $interlocuteurs = $user->getInterlocuteurSiret();

        if($request->query->has('inter')){
            $inter = $request->query->get('inter');
            if ($inter != 'tous')
                $session->set('interlocuteurSelected',$inter);
            else
                $session->set('interlocuteurSelected','tous');
        }

        $now = new DateTime('now');
        $all = false;
        $optionSelectAll = false;

        if ($session->has('interlocuteurSelected') && ($session->get('interlocuteurSelected') != 'tous')){
            $interlocuteurSiret = $session->get('interlocuteurSelected');
            $siret = $interlocuteurSiret;
        }
        else{
            $interlocuteurSiret = $user->getInterlocuteurSiret()[0];
            $siret = $interlocuteurSiret->getSiret();
            $session->set('interlocuteurSelected','tous');
        }

        $encaissements = $this->getDoctrine()->getRepository('AppBundle:Encaissement')->findEncaissementsBySiret($siret);

        if(isset($_GET['all'])) {
            $all = true;
        }

        if(($all) && (!isset($_POST['inter']) ? null : $_POST['inter']) == 'tous'){
            $optionSelectAll = true;
            $encaissements=[];
            foreach ($interlocuteurs as $inter) {
                $encaissements = array_merge($encaissements, $this->getDoctrine()->getRepository('AppBundle:Encaissement')->findEncaissementsBySiret($inter->getSiret()));
            }
        } else if ($session->get('interlocuteurSelected') == 'tous') {
            $encaissements=[];
            foreach ($interlocuteurs as $inter) {
                $encaissements = array_merge($encaissements, $this->getDoctrine()->getRepository('AppBundle:Encaissement')->findEncaissementsBySiret($inter->getSiret()));
            }
        }

        $encaissementsArray = [];

        $index=0;
        foreach($encaissements as $e)
        {
            foreach($e as $key=>$value){
                $myKey = str_replace("_"," ",$key);
                $myKey = ucwords($myKey);
                $myKey = str_replace(" ","",$myKey);
                $myKey = lcfirst($myKey);
                $encaissementsArray[$index][$myKey] = $value;
            }
            $index++;
        }

        $encaissementsFinal =[];

        foreach ($encaissementsArray as $encaissement)
        {
            $dateEncaissement = new DateTime($encaissement['dateCreated']);

            $dateDiff = date_diff($now, $dateEncaissement);

            $diffMonth = $dateDiff->m + ($dateDiff->y)*12;

            if($diffMonth< 19)
                $encaissementsFinal[]=$encaissement ;

            if (count($encaissementsFinal)==5 and !($all))
                break;
        }

        return [
            'user' =>$user,
            'optionSelectAll' =>$optionSelectAll,
            'interlocuteurs' => $interlocuteurs,
            //'interlocuteurSelected' => $interlocuteurSiret,
            'encaissements' =>$encaissementsFinal,
            'entete'=>$entete,
            'allEncaissements'=>$all,
        ];
    }

    /**
     * @Route("/mesDecaissements", name="decaissements_usager",options={"expose" = true})
     * @Template("@App/Utilisateur/decaissementsUsager.html.twig")
     * @Security("is_granted(['ROLE_USER', 'ROLE_AGENT', 'ROLE_ADMIN'])")
     */
    public function decaissementsListAction(Request $request)
    {

        /** @var Utilisateur $user */
        $user = $this->getUser();
        $em = $this->getDoctrine()->getManager();
        $session = new Session();
        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'OperationComptable']);
        $interlocuteurs = $user->getInterlocuteurSiret();

        if($request->query->has('inter')){
            $inter = $request->query->get('inter');
            if ($inter != 'tous')
                $session->set('interlocuteurSelected',$inter);
            else
                $session->set('interlocuteurSelected','tous');
        }

        $now = new DateTime('now');
        $all = false;
        $optionSelectAll = false;

        if ($session->has('interlocuteurSelected') && ($session->get('interlocuteurSelected') != 'tous')){
            $interlocuteurSiret = $session->get('interlocuteurSelected');
            $siret = $interlocuteurSiret;
        }
        else{
            $interlocuteurSiret = $user->getInterlocuteurSiret()[0];
            $siret = $interlocuteurSiret->getSiret();
            $session->set('interlocuteurSelected','tous');
        }

        $decaissements = $this->getDoctrine()->getRepository('AppBundle:Decaissement')->findDecaissementsBySiret($siret);


        if(isset($_GET['all'])) {
            $all = true;
        }

        if(($all) && (!isset($_POST['inter']) ? null : $_POST['inter']) == 'tous'){
            $optionSelectAll = true;
            $decaissements=[];
            foreach ($interlocuteurs as $inter) {
                $decaissements = array_merge($decaissements, $this->getDoctrine()->getRepository('AppBundle:Decaissement')->findDecaissementsBySiret($inter->getSiret()));
            }
        } else if ($session->get('interlocuteurSelected') == 'tous') {
            $decaissements=[];
            foreach ($interlocuteurs as $inter) {
                $decaissements = array_merge($decaissements, $this->getDoctrine()->getRepository('AppBundle:Decaissement')->findDecaissementsBySiret($inter->getSiret()));
            }
        } 

        $decaissementsArray = [];

        $index=0;
        foreach($decaissements as $e)
        {
            foreach($e as $key=>$value){
                $myKey = str_replace("_"," ",$key);
                $myKey = ucwords($myKey);
                $myKey = str_replace(" ","",$myKey);
                $myKey = lcfirst($myKey);
                $decaissementsArray[$index][$myKey] = $value;
            }
            $index++;
        }

        $decaissementsFinal =[];

        foreach ($decaissementsArray as $decaissement)
        {
            $dateDecaissement = new DateTime($decaissement['dateCreated']);

            $dateDiff = date_diff($now, $dateDecaissement);

            $diffMonth = $dateDiff->m + ($dateDiff->y)*12;

            if($diffMonth< 19)
                $decaissementsFinal[]=$decaissement ;

            if (count($decaissementsFinal)==5 and !($all))
                break;
        }

        return [
            'user' =>$user,
            'optionSelectAll' =>$optionSelectAll,
            'interlocuteurs' => $interlocuteurs,
            //'interlocuteurSelected' => $interlocuteurSiret,
            'decaissements' =>$decaissementsFinal,
            'entete' => $entete,
            'allDecaissements' => $all,
        ];
    }

    /**
     * @Route("/echeances", name="global_echeances",options={"expose" = true})
     * @Template("@App/Utilisateur/listEcheanceGlobale.html.twig")
     * @Security("is_granted(['ROLE_USER', 'ROLE_AGENT', 'ROLE_ADMIN'])")
     */
    public function GlobalEcheancesListAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        /** @var Utilisateur $user */
        $user = $this->getUser();
        $interlocuteurs = $user->getInterlocuteurSiret();
        $annee = date('Y');
        $total = 0;

        $session = new Session();
        if (isset($_GET['annee'])){
            $annee = $_GET['annee'];
            $session->remove('interlocuteurSelectedEcheances');  
        }
        
        if ($request->query->has('inter')){
            $inter = $request->query->get('inter');
            $session->set('interlocuteurSelectedEcheances',$inter);
            $interlocuteurSiret = $em->getRepository('AppBundle:Interlocuteur')->findOneBy(['siret'=> $inter]);
            $echeances = $em->getRepository('AppBundle:Echeance')->getEcheancesFromSiret($interlocuteurSiret->getSiret(), $annee);
        }else{
            /*if($session->has('interlocuteurSelectedEcheances')){
                $session->remove('interlocuteurSelectedEcheances');  
            }*/
            $echeances = $em->getRepository('AppBundle:Echeance')->getEcheancesFromAnnee($annee);
        }
            //$interlocuteurSiret = $interlocuteurs[0] ;


        

        foreach ($echeances as $eche)
        {
            $total += $eche['montant'];
        }


        return [
            'echeances'=> $echeances,
            'interlocuteurs' => $interlocuteurs,
            'annee' => $annee,
            'total' => $total,
        ];
    }

    /**
     * @Route("echeances/{dossierID}", name="echeance_dossier")
     * @Template("@App/Utilisateur/listEcheanceDossier.html.twig")
     */
    public function DossierEcheancesAction($dossierID)
    {
        $em= $this->getDoctrine()->getManager();
        $ech = $em->getRepository('AppBundle:Echeance')->getEcheancesFromNumeroDossier($dossierID);
        $echeances = [];

        $index=0;
        foreach($ech as $e)
        {
            foreach($e as $key=>$value){
                    $myKey = str_replace("_"," ",$key);
                    $myKey = ucwords($myKey);
                    $myKey = str_replace(" ","",$myKey);
                    $myKey = lcfirst($myKey);
                    $echeances[$index][$myKey] = $value;
            }
            $index++;
        }

        $total = 0;
        /** @var Utilisateur $user */
        $user = $this->getUser();

        $dossiers=[];
        $interlocuteurs = $user->getInterlocuteurSiret();

        $previousDossierID = null;
        $nextDossierID = null;

        /** @var Interlocuteur $interlocuteur */
        foreach($interlocuteurs as $interlocuteur)
            $dossiers = array_merge($dossiers,  $em->getRepository('AppBundle:DossierAide')->findBy(["interlocuteurSiret"=>$interlocuteur->getSiret()]));

        for($i=0; $i<count($dossiers); $i++)
        {
            if ($dossiers[$i]->getNumero()==$dossierID)
            {
                if ($i>0)
                    $previousDossierID = $dossiers[$i-1]->getNumero();
                if ($i<(count($dossiers)-1))
                    $nextDossierID = $dossiers[$i+1]->getNumero();
            }
        }


        foreach ($echeances as $eche)
        {
            $total += $eche['montant'];
        }

        return [
            'echeances'=>$echeances,
            'dossier'=>$dossierID,
            'total' => $total,
            'nextDossier' => $nextDossierID,
            'previousDossier' => $previousDossierID,
        ]
            ;
    }

    /**
     * @Route("participations", name="participations_list",options={"expose" = true})
     * @Template("@App/Utilisateur/financialParticipations.html.twig")
     */
    public function listParticipationsFinancieresAction(Request $request)
    {
        /** @var Utilisateur $user */
        $user = $this->getUser();
        $thematiques = $user->getThematiqueCodes();
        if(in_array("DPF",$thematiques)){//check access
            $em = $this->getDoctrine()->getManager();
            $dossiers=[];
            $session = new Session();
            $interlocuteurs = $user->getInterlocuteurSiret();
            $interlocuteursFilter = $interlocuteurs;

            if($request->query->has('inter')){
                $inter = $request->query->get('inter');
                $session->set('interlocuteurSelected',$inter);
                if($inter != 'tous')
                    $interlocuteursFilter = $em->getRepository('AppBundle:Interlocuteur')->getInterlocuteurBySiret($inter,$user->getId());
                else
                    $session->set('interlocuteurSelected','tous');
            } elseif(!$session->has('interlocuteurSelected')){
                $session->set('interlocuteurSelected','tous');
            }
            
            $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'ParticipationFinanciere']);

            /** @var Interlocuteur $interlocuteur */
            foreach($interlocuteursFilter as $interlocuteur)
                $dossiers = array_merge($dossiers,  $em->getRepository('AppBundle:DossierAide')->findBy(["interlocuteurSiret"=>$interlocuteur->getSiret()]));

            $interlocuteursFinal = [];

            foreach($interlocuteurs as $interlocuteur)
            {
                $documents = $em->getRepository("AppBundle:Ppc")->findBy(['siret'=> $interlocuteur->getSiret()], ['dateUpdated'=>'DESC']);
                if (!empty($documents))
                    $interlocuteursFinal[] = $interlocuteur;
            }
            
            return [
                'dossiers'=>$dossiers,
                'interlocuteurs'=> $interlocuteursFinal,
                'entete'=>$entete,
            ]
                ;
        }else{
            //no access
            throw $this->createAccessDeniedException('Vous ne pouvez pas accéder à cette page.');
        }
    }

    /**
     * @Route("/consultation", name="switch_user")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     * @Security("is_granted('ROLE_ALLOWED_TO_SWITCH')")
     */
    public function switchAction(Request $request)
    {

        $em = $this->getDoctrine()->getManager();
        $switched = $request->get('u');

        $checkAdmin = $em->getRepository('AppBundle:Utilisateur')->findOneBy(['email'=>$switched])->IsIsAdmin();

        if ($checkAdmin and !$this->isGranted('ROLE_ADMIN'))
            return $this->redirectToRoute('non_autorise');

        $histo = new Historique("Consultation", "Utilisateur", $this->getUser()->getUsername() . " consulte l'utilisateur " . $switched, $this->getUser());
        $em->persist($histo);
        $em->flush();

        return $this->redirectToRoute('homepage', ['_switch_user'=>$switched]);
    }

    /**
     * @param Request $request
     * @Route("/ppc/{interSiret}/download", name="download_ppc")
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function downloadPPCAction(Request $request, $interSiret)
    {
        $doc = $this->getDoctrine();
        $em=$doc->getManager();

        $documents = $doc->getRepository("AppBundle:Ppc")->findBy(['siret'=> $interSiret], ['dateUpdated'=>'DESC']);

        if (empty($documents))
        {
            return $this->redirect($request->headers->get('referer'));
        }

        $document = $documents[0];

        $path = $this->getParameter('Kernel').$document->getDocumentEmplacement();

        if(empty($path)) {
            return $this->redirect($request->headers->get('referer'));
        }

        $response = new BinaryFileResponse($path);

        // To generate a file download, you need the mimetype of the file
        $mimeTypeGuesser = new FileinfoMimeTypeGuesser();

        // Set the mimetype with the guesser or manually
        if($mimeTypeGuesser->isSupported()){
            // Guess the mimetype of the file according to the extension of the file
            $response->headers->set('Content-Type', $mimeTypeGuesser->guess($path));
        }else{
            // Set the mimetype of the file manually, in this case for a text file is text/plain
            $response->headers->set('Content-Type', 'text/plain');
        }

        // Set content disposition inline of the file
        $response->setContentDisposition(
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            basename($document->getDocumentEmplacement())
        );

        $histo = new Historique('Téléchargement', 'PPC', $this->getUser()->getUsername().' a téléchargé le PPC de '.$interSiret, $this->getUser());
        $em->persist($histo);
        $em->flush();

        return $response;
    }

    /**
     * @param Request $request
     * @Route("")
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function downloadJustificatifsPaiementAction(Request $request, $interSiret)
    {

    }


    /**
     * @Route("/cgu/confirm", name="accept_cgu")
     * @Template("@App/Utilisateur/acceptNewCgu.html.twig")
     */
    public function acceptNewCguAction()
    {
        $em = $this->getDoctrine()->getManager();
        $currentCgu = $em->getRepository('AppBundle:Cgu')->findBy([], ['dateUpdated'=>'DESC'])[0];

        return [
            'cgu'=>$currentCgu
        ];
    }


    /**
     * @param $cguId
     * @Route("/api/cgu/{cguId}/validate", name="cgu_validate")
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function validatedCguAction($cguId)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $this->getUser();

        if (!empty($em->getRepository('AppBundle:CguUtilisateur')->findBy(['utilisateurID'=>$this->getUser()->getId(), 'cguId'=>$cguId]))) {
            return $this->redirectToRoute('homepage');
        } else {
            $cguUti = new CguUtilisateur();
            $cguUti->setUtilisateurID($this->getUser()->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();

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

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


}

