<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Cgu;
use AppBundle\Entity\Historique;
use AppBundle\Entity\Interlocuteur;
use AppBundle\Entity\Notification;
use AppBundle\Entity\Thematique;
use AppBundle\Entity\Utilisateur;
use AppBundle\Form\Document\DepotDocumentType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage", options={"expose"=true})
     * @Template("@App/Default/index.html.twig")
     */
    public function indexAction(Request $request)
    {
        /** @var Utilisateur $user */
        $user = $this->getUser();

        if ((!$this->hasValidatedCGU($user)) and !($this->isGranted('ROLE_PREVIOUS_ADMIN')))
            return $this->redirectToRoute('accept_cgu');

        $doc = $this->getDoctrine();
        $em = $doc->getManager();
        $agence = $doc->getRepository('AppBundle:Agence')->findAll()[0];
        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'Accueil']);

        $documents = $doc->getRepository('AppBundle:DocumentDisposition')->getDocumentsSQL($this->getUser(), 5);

        $thems = $user->getThematique();
        $interloc = $user->getInterlocuteurSiret();

        $form = $this->createForm(DepotDocumentType::class);

        $notifications = $em->getRepository('AppBundle:Notification')->findBy([],['date'=>'desc'],6);
        $notificationsFinales = [];

        $thematiqueCodes = [];
        $interSirets = [];

        foreach($thems as $th)
            $thematiqueCodes[] = $th->getCode();
        foreach ($interloc as $inter)
            $interSirets[] = $inter->getSiret();



        /** @var Notification $notif */
        foreach ($notifications as $notif)
        {
            if (!is_null($notif->getThematiqueCode()) and !is_null($notif->getInterlocuteurSiret()))
                {
                    if (in_array($notif->getThematiqueCode(), $thematiqueCodes) and in_array($notif->getInterlocuteurSiret(), $interSirets))
                        $notificationsFinales[] = $notif;
                }
                elseif (is_null($notif->getThematiqueCode()) and !is_null($notif->getInterlocuteurSiret()))
                {
                    if (in_array($notif->getInterlocuteurSiret(),$interSirets ))
                        $notificationsFinales[] = $notif;
                }
                elseif (!is_null($notif->getThematiqueCode()) and is_null($notif->getInterlocuteurSiret()))
                {
                    if (in_array($notif->getThematiqueCode(),$thematiqueCodes ))
                         $notificationsFinales[] = $notif;
                }
                else
                    $notificationsFinales[] = $notif;
        }


        return [
            'documents' => $documents,
            'agence' => $agence,
            'thems' => $thems,
            'interloc' => $interloc,
            'form' => $form,
            'notifications' => $notificationsFinales,
            'entete'=>$entete
        ];
    }

    /**
     * @Route("/saveSearchValue", name="save_search_value", options={"expose"=true})
     */
    public function saveSearhValueAction(Request $request)
    {
        if($request->query->has('searchValue') && $request->query->has('pageNumber')){
            $pageNumber = $request->query->get('pageNumber');
            $searchedValue = $request->query->get('searchValue');
            /* session search value saving */
            $session = new Session();
            $session->set('searchDocument',$searchedValue);
            $session->set('pageNumber',$pageNumber);
            return new JsonResponse(['data' => true]);
        }
        return new JsonResponse(['data' => false]);
    }

    /**
     * @Route("/panel", name="panel")
     */
    public function indexPanelAction()
    {
        return $this->redirectToRoute("users_list");
    }

    /**
     * @Route("/cgu", name="cgu")
     * @Template("@App/Default/cgu.html.twig")
     */
    public function cguAction()
    {
        $cgus = $this->getDoctrine()->getRepository("AppBundle:Cgu")->findBy([], ['dateUpdated'=>'desc']);
        if (!empty($cgus))
            $cgu = $cgus[0];
        else
            $cgu = new Cgu();


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



    private function hasValidatedCGU(Utilisateur $user)
    {
        $em = $this->getDoctrine()->getManager();
        /** @var Utilisateur $user */
        $Cgus = $em->getRepository('AppBundle:Cgu')->findBy([], ['dateUpdated'=>'DESC']);
        $hasValidated = true;

        if (!empty($Cgus))
        {
            /** @var Cgu $currentCgu */
            $currentCgu = $Cgus[0];
        }
        else
            return true;

        $check = $em->getRepository('AppBundle:CguUtilisateur')->findBy(['utilisateurID'=>$user->getId(), 'cguId'=>$currentCgu->getId()]);

        if (empty($check))
        {
            $hasValidated = false;
        }

        return $hasValidated;
    }

}
