<?php
/**
 * Created by PhpStorm.
 * User: remy.bages
 * Date: 25/05/2018
 * Time: 14:11
 */

namespace AppBundle\Controller;


use AppBundle\Entity\DemandePaiement;
use AppBundle\Entity\DemandePaiementComplementaire;
use AppBundle\Entity\DocumentDossier;
use AppBundle\Entity\DossierAide;
use AppBundle\Entity\Echeance;
use AppBundle\Entity\Encaissement;
use AppBundle\Entity\Historique;
use AppBundle\Entity\ModaliteAide;
use AppBundle\Entity\Utilisateur;
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Spipu\Html2Pdf\Html2Pdf;
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\Request;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * Class DossierAideController
 * @package AppBundle\Controller
 * @Route("/dossier/{dossierID}")
 */
class DossierAideController extends Controller
{
    /**
     * @Route("/informations", name="dossier_aide_informations")
     * @Template("@App/DossierAide/informations.html.twig")
     */
    public function infoDossierAction(Request $request, $dossierID)
    {
        $em = $this->getDoctrine()->getManager();
        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'DossierAide']);

        /** @var DossierAide $dossier */
        $dossier = $em->getRepository('AppBundle:DossierAide')->findOneBy(['numero'=>$dossierID]);
        $searchedValue = null;
        if($request->query->has('searchedValue')){
            $searchedValue = $request->query->get('searchedValue');
        }
        return [
            'dossier' => $dossier,
            'nextDossier' => $this->findNextDossier($dossierID,$searchedValue),
            'previousDossier'=> $this->findPreviousDossier($dossierID,$searchedValue),
            'entete' => $entete,
        ];
    }

    /**
     * @Route("/modalites", name="dossier_aide_modalites")
     * @Template("@App/DossierAide/modalites.html.twig")
     */
    public function modalitesDossierAction(Request $request,$dossierID)
    {
        $em = $this->getDoctrine()->getManager();
        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'DossierAide']);

        /** @var DossierAide $dossier */
        $dossier = $em->getRepository('AppBundle:DossierAide')->findOneBy(['numero'=>$dossierID]);
        /** @var ModaliteAide $modalites */
        $modalites = $em->getRepository('AppBundle:ModaliteAide')->findBy(['dossierAideNumero'=>$dossierID]);
        $searchedValue = null;
        if($request->query->has('searchedValue')){
            $searchedValue = $request->query->get('searchedValue');
        }
        return [
            'dossier' => $dossier,
            'modalites' => $modalites,
            'nextDossier' => $this->findNextDossier($dossierID,$searchedValue),
            'previousDossier'=> $this->findPreviousDossier($dossierID,$searchedValue),
            'entete' => $entete,
        ];

    }

    /**
     * @Route("/demandes", name="dossier_aide_demandes")
     * @Template("@App/DossierAide/demandes.html.twig")
     */
    public function demandesPaiementAction(Request $request,$dossierID)
    {
        $em = $this->getDoctrine()->getManager();
        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'DossierAide']);

        /** @var DossierAide $dossier */
        $dossier = $em->getRepository('AppBundle:DossierAide')->findOneBy(['numero'=>$dossierID]);
        /** @var DemandePaiement $demandes */
        $demandes = $em->getRepository('AppBundle:DemandePaiement')->findBy(['dossierAideNumero'=>$dossierID], ['date' => 'asc']);
        $searchedValue = null;
        if($request->query->has('searchedValue')){
            $searchedValue = $request->query->get('searchedValue');
        }
        return [
            'dossier' => $dossier,
            'demandes' => $demandes,
            'nextDossier' => $this->findNextDossier($dossierID,$searchedValue),
            'previousDossier'=> $this->findPreviousDossier($dossierID,$searchedValue),
            'entete' => $entete,
        ];

    }

    /**
     * @Route("/encaissements", name="dossier_aide_encaissements")
     * @Template("@App/DossierAide/encaissements.html.twig")
     */
    public function encaissementsDossierAction(Request $request,$dossierID)
    {
        $em = $this->getDoctrine()->getManager();
        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'DossierAide']);

        /** @var DossierAide $dossier */
        $dossier = $em->getRepository('AppBundle:DossierAide')->findOneBy(['numero'=>$dossierID]);
        /** @var Encaissement $demandes */
        $encaissements = $em->getRepository('AppBundle:Encaissement')->findByDossierAideNumero($dossierID);
        $total = 0;

        /** @var Encaissement $echeance */
        foreach($encaissements as $encaissement)
        {
            $total += $encaissement['montant'];
        }
        $searchedValue = null;
        if($request->query->has('searchedValue')){
            $searchedValue = $request->query->get('searchedValue');
        }
        return [
            'dossier' => $dossier,
            'encaissements' => $encaissements,
            'total' => $total,
            'nextDossier' => $this->findNextDossier($dossierID,$searchedValue),
            'previousDossier'=> $this->findPreviousDossier($dossierID,$searchedValue),
            'entete' => $entete,
        ];

    }


    /**
     * @Route("/documents", name="dossier_aide_documents")
     * @Template("@App/DossierAide/documents.html.twig")
     */
    public function documentsDossierAction(Request $request,$dossierID)
    {
        $em = $this->getDoctrine()->getManager();
        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'DossierAide']);

        /** @var DossierAide $dossier */
        $dossier = $em->getRepository('AppBundle:DossierAide')->findOneBy(['numero'=>$dossierID]);
        /** @var DocumentDossier $demandes */
        $documents = $em->getRepository('AppBundle:DocumentDossier')->findBy(['dossierAideNumero'=>$dossierID]);
        $searchedValue = null;
        if($request->query->has('searchedValue')){
            $searchedValue = $request->query->get('searchedValue');
        }
        return [
            'dossier' => $dossier,
            'documents' => $documents,
            'nextDossier' => $this->findNextDossier($dossierID,$searchedValue),
            'previousDossier'=> $this->findPreviousDossier($dossierID,$searchedValue),
            'entete' => $entete,

        ];

    }

    /**
     * @param Request $request
     * @Route("/documents/download/{documentID}", name="download_doc_dossier_aide")
     * @return BinaryFileResponse
     */
    public function downloadDossierAideAction(Request $request,$documentID, $dossierID)
    {
        $em = $this->getDoctrine()->getManager();
        $document = $em->getRepository('AppBundle:DocumentDossier')->findOneBy(['id'=>$documentID]);

        $kernelPath = rtrim($this->getParameter('Kernel'),'/');

        $path = $kernelPath.$document->getDocumentEmplacement();
        $path = substr($path, 0, strpos($path, ".pdf")) . ".pdf";
        if(empty($path)) {
            return $this->redirect($request->headers->get('referer'));
        }

        try{
        $response = new BinaryFileResponse($path);
        }
        catch(\Exception $e)
        {
            $this->get('session')->getFlashBag()->add('Echec', $this->get('translator')->trans('ERROR_FILE_NOT_FOUND'));
            return $this->redirect($request->headers->get('referer'));

        }


        // 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));
            $response->headers->set('Content-Disposition', 'attachment; filename="'.urlencode($document->getDocumentNom()).'";');

        }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,
            $document->getDocumentNom()
        );*/
        //return $this->file($path);
        return $response;
    }

    /**
     * @Route("/demande/{demandeID}", name="new_demande")
     * @Template("@App/DossierAide/DemandePaiement/new.html.twig")
     * @Security("is_granted('IS_AUTHENTICATED_FULLY')")
     */
    public function createDemandeAction(Request $request ,$dossierID, $demandeID)
    {
        $user = $this->getUser();
        $em = $this->getDoctrine()->getManager();

        $dossier = $em->getRepository('AppBundle:DossierAide')->findOneBy(['numero'=>$dossierID]);
        $isAllowed = false;

        foreach($user->getInterlocuteurSiret() as $inter)
        {
            if ($inter->getSiret() == $dossier->getInterlocuteurSiret()->getSiret())
                $isAllowed = true;
        }

            if (!$isAllowed)
                return $this->redirectToRoute('non_autorise');

        if ($demandeID != 'new')
        {
            $demandeToEdit = $em->getRepository('AppBundle:DemandePaiement')->findOneBy(['id'=>$demandeID]);


            $path = 'documents/demandes_de_paiement/utilisateur_'.$user->getEmail().'/dossier_'.$dossierID.'/demande_'.$demandeToEdit->getDateCreated()->format('d-m-Y').'_'.$demandeID;
            $lettre = null;
            if (file_exists($path.'/lettre_demande.pdf'))
                $lettre = new File($path.'/lettre_demande.pdf');
                $demandeForm = $this->createForm('AppBundle\Form\DemandePaiementType', null, ['data'=>[
                    'lettre' => $lettre,
                    'commentaire' => $demandeToEdit->getCommentaire(),
                    'typeDecompte'=>$demandeToEdit->getTypeDecompte(),
                    'montant'=>$demandeToEdit->getMontant(),
                    'taux'=>$demandeToEdit->getTaux(),
                    'distinction' => null
                ]]);
        }
        else
        {
            $demandeForm = $this->createForm('AppBundle\Form\DemandePaiementType');
        }

        $dossier = $em->getRepository('AppBundle:DossierAide')->findOneBy(['numero'=>$dossierID]);
        $fileManager = new Filesystem();



        $demandeForm->handleRequest($request);
        $data = $demandeForm->getData();

        if($data['distinction'] == 'genererModele'){
            $status = 200;

            if(!empty($data['taux']) and !empty($data['montant']))
            {
                $status=500;
                $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_BOTH_SELECTED'));
            }

            /*if((!is_numeric($data['taux']) or $data['taux']<0 or $data['taux']>100) and !empty($data['taux']))
            {
                $status=500;
                $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_RATE'));
            }
            if((!is_numeric($data['montant']) or $data['montant']<0) and !empty($data['montant']))
            {
                $status=500;
                $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_AMOUNT'));
            }*/

            $fileManager = new Filesystem();
            if (!$fileManager->exists('documents/excel_models'))
            {
                $status=500;
                $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_DIR_NOT_EXIST'));
            }


                if ($status==200)
            {
                $interlocuteur = $em->getRepository('AppBundle:Interlocuteur')->findOneBy(['siret'=>$dossier->getInterlocuteurSiret()]);
                $name = '';
                if($data['typeDecompte']=='Acompte')
                {
                    $name='Acompte_'.$dossier->getNumero().'.xls';
                    $spreadsheet = IOFactory::load('documents/excel_models/AcompteModel.xls');

                    $spreadsheet->setActiveSheetIndex(0)
                        ->setCellValue('B1',$interlocuteur->getRaisonSociale())
                        ->setCellValue('B2',$dossier->getNumero())
                        ->setCellValue('D3',$dossier->getMontantPrevisionnel().' €')
                    ;
                }

                else{
                    $name='Solde_'.$dossier->getNumero().'.xls';
                    $spreadsheet = IOFactory::load('documents/excel_models/SoldeModel.xls');

                    $spreadsheet->setActiveSheetIndex(0)
                        ->setCellValue('B1',$interlocuteur->getRaisonSociale())
                        ->setCellValue('B3',$dossier->getNumero())
                        ->setCellValue('B4',$dossier->getObjet().' - '.$dossier->getLocalisation())
                    ;
                }

                $writer = new Xls($spreadsheet);

                $writer->save($name);

                try{
                    $response = new BinaryFileResponse($name);
                }
                catch  (Exception $e)
                {
                    $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('FILE_NOT_FOUND'));

                    return $this->redirect($request->headers->get('referer'));
                }

                $response->deleteFileAfterSend(true);
                $response->setContentDisposition(
                ResponseHeaderBag::DISPOSITION_ATTACHMENT,
                $name
                );

                return $response;
            }

        }
        $old = null;
        if ($demandeID != 'new')
        {
            $demande = $em->getRepository('AppBundle:DemandePaiement')->findOneBy(['id'=>$demandeID]);
            $etatOld = $em->getRepository('AppBundle:DemandePaiementComplementaire')->findOneBy(['demandePaiement'=>$demande, 'nom'=>'Etat d\'avancement']);
            $justiOld = $em->getRepository('AppBundle:DemandePaiementComplementaire')->findOneBy(['demandePaiement'=>$demande, 'nom'=>'Justificatifs de travaux']);
            $lettreOld = $em->getRepository('AppBundle:DemandePaiementComplementaire')->findOneBy(['demandePaiement'=>$demande, 'nom'=>'Lettre de demande de paiement']);
            $old = [$etatOld, $justiOld, $lettreOld];

        }

        if($data['distinction'] == 'validerDepot'){
            $dataDemande = $demandeForm->getData();
            $status = 200;

            $typeJusti = '';
            $typeDemande = '';
            $typeLettre = ''; 

            $brouillon = [];

            if (!empty($dataDemande['etat'])) {
                $seg = explode('.', $dataDemande['etat']->getClientOriginalName());
                $typeDemande = $seg[count($seg)-1];
            }
            if (!empty($dataDemande['justificatifs'])) {
                $seg = explode('.', $dataDemande['justificatifs']->getClientOriginalName());
                $typeJusti = $seg[count($seg) - 1];
            }
            if (!empty($dataDemande['lettre'])) {
                $seg = explode('.', $dataDemande['lettre']->getClientOriginalName());
                $typeLettre = $seg[count($seg)-1];
            }

            if(!empty($data['taux']) and !empty($data['montant']))
            {
                $status=500;
                $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_BOTH_SELECTED'));
            }

            /*if((!is_numeric($data['taux']) or $data['taux']<0 or $data['taux']>100) and !empty($data['taux']))
            {
                $status=500;
                $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_RATE'));
            }
            if((!is_numeric($data['montant']) or $data['montant']<0) and !empty($data['montant']))
            {
                $status=500;
                $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_AMOUNT'));
            }*/


            if ($typeDemande!='xls' and $typeDemande!='xlsx' and $typeDemande!='csv' and $typeDemande != '')
            {
                $status=500;
                $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_TYPE_STATUS'));
            }

            
                if ($typeJusti!='zip' and $typeJusti != '')
                {
                    $status=500;
                    $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_TYPE_JUSTIFICATIFS'));
                }
            

            
            if ($typeLettre!='pdf' and $typeLettre!='')
            {
                $status=500;
                $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_TYPE_MAIL'));
            }

            if($status==200)
            {

                if (!$fileManager->exists('documents/demandes_de_paiement'))
                    $fileManager->mkdir('documents/demandes_de_paiement');

                if ($demandeID == 'new')
                    $demande = new DemandePaiement();

                $demandeEtat = new DemandePaiementComplementaire();
                $demandeJusti = new DemandePaiementComplementaire();
                $demandeLettre = new DemandePaiementComplementaire();
                $date = new \DateTime('now');


                $etatOld = $em->getRepository('AppBundle:DemandePaiementComplementaire')->findOneBy(['demandePaiement'=>$demande, 'nom'=>'Etat d\'avancement']);
                $justiOld = $em->getRepository('AppBundle:DemandePaiementComplementaire')->findOneBy(['demandePaiement'=>$demande, 'nom'=>'Justificatifs de travaux']);
                $lettreOld = $em->getRepository('AppBundle:DemandePaiementComplementaire')->findOneBy(['demandePaiement'=>$demande, 'nom'=>'Lettre de demande de paiement']);
                if (empty($dataDemande['etat']) and ($etatOld == null))
                    $brouillon[] = 'fichier etat d\'avancement manquant';

                if ($data['typeDecompte']=='Solde' and empty($dataDemande['justificatifs']) and ($justiOld == null))
                    $brouillon[] = 'fichier zip des justificatifs manquant';

                if (empty($dataDemande['lettre']) and ($lettreOld == null))
                    $brouillon[] = 'lettre de demande de paiement manquante';
            
                $demande->setMontant((empty($data['montant']) ? null : $data['montant']));
                $demande->setTaux((empty($data['taux']) ? null : $data['taux']));
                $demande->setTypeDecompte($data['typeDecompte']);
                $demande->setCommentaire($dataDemande['commentaire']);

                if ($demandeID == 'new')
                {
                    $demande->setUtilisateurCreated($user->getId());
                    $demande->setDateCreated($date);
                }
                else
                {
                    $demande->setUtilisateurUpdated($user->getId());
                    $demande->setDateUpdated($date);
                }
                $demande->setDossierAideNumero($dossier);
                if (count($brouillon)>0)
                    $demande->setEtat('Brouillon');
                else
                    $demande->setEtat('Déposé'); //En traitement 


                if ($demandeID != 'new')
                    $histo = new Historique('Modification', 'Demande de paiement', 'l\'utilisateur '.$user->getUsername().
                    ' a modifié la demande de paiement '. $demandeID .' pour le dossier '.$dossier->getNumero(), $user);

                else
                    $histo = new Historique('Creation', 'Demande de paiement', 'l\'utilisateur '.$user->getUsername().
                    ' a crée une demande de paiement pour le dossier '.$dossier->getNumero(), $user);
                
                $em->persist($demande);
                $em->persist($histo);
                $em->flush();

                    $idForPath = $em->getRepository('AppBundle:DemandePaiement')->findOneBy(['dateCreated'=>$demande->getDateCreated()])->getId();


                $path = $this->getParameter('DirDemandePaiement').$dossier->getNumero().'_'.$idForPath;

                if (!$fileManager->exists($path))
                    $fileManager->mkdir($path);

                if (!empty($dataDemande['etat']))
                    $dataDemande['etat']->move($path, 'etat_avancement.'.$typeDemande);
                if (!empty($dataDemande['justificatifs']))
                    $dataDemande['justificatifs']->move($path, 'justificatifs_travaux.zip');
                if (!empty($dataDemande['lettre']))
                    $dataDemande['lettre']->move($path, 'lettre_demande.pdf');


                if (!empty($dataDemande['etat']))
                {
                    if ($etatOld != null)
                    {
                        $demandeEtat = $etatOld;
                        $demandeEtat->setDateUpdated($date);
                    }
                    else
                        $demandeEtat->setDateCreated($date);
                    $demandeEtat->setNom('Etat d\'avancement');
                    $demandeEtat->setEmplacement($path.'/etat_avancement.xls');
                    $demandeEtat->setDemandePaiement($demande);
                }

                if (!empty($dataDemande['justificatifs'])) {
                    if ($justiOld != null)
                    {
                        $demandeJusti = $justiOld;
                        $demandeJusti->setDateUpdated($date);
                    }
                    else
                        $demandeJusti->setDateCreated($date);
                    $demandeJusti->setNom('Justificatifs de travaux');
                    $demandeJusti->setEmplacement($path . '/justificatifs_travaux.zip');
                    $demandeJusti->setDemandePaiement($demande);
                }

                if (!empty($dataDemande['lettre']))
                {
                    if ($lettreOld != null)
                    {
                        $demandeLettre = $lettreOld;
                        $demandeLettre->setDateUpdated($date);
                    }
                    else
                        $demandeLettre->setDateCreated($date);
                    $demandeLettre->setNom('Lettre de demande de paiement');
                    $demandeLettre->setEmplacement($path.'/lettre_demande.pdf');
                    $demandeLettre->setDemandePaiement($demande);
                }

                if (!empty($dataDemande['etat']))
                    $em->persist($demandeEtat);
                if (!empty($dataDemande['justificatifs']))
                    $em->persist($demandeJusti);
                if (!empty($dataDemande['lettre']))
                    $em->persist($demandeLettre);
                $em->flush();


                if (count($brouillon)>0)
                {
                    foreach ($brouillon as $txt) {
                        $this->get('session')->getFlashBag()->add('warning', $txt);
                    }

                     $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('SUCCES_BROUILLON_DEMANDE'));
                }
                else
                    $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('SUCCESS_DEMANDE'));

                return $this->redirectToRoute('dossier_aide_demandes', ['dossierID'=>$dossierID]);

            }

        }

        return [
            'demandeForm' => $demandeForm->createView(),
            'dossier'=>$dossier,
            'old'=>$old,
        ];

    }



    /**
    *@Route("/justificatifs", name="download_justificatifs")
    *
    */
    public function downloadJustificatifsAction(Request $request ,$dossierID)
    {

        $em = $this->getDoctrine()->getManager();
         $dossier = $em->getRepository('AppBundle:DossierAide')->findOneBy(['numero'=>$dossierID]);
         $html = $dossier->getJustificatifsPaiement();

         if (!$html=='')
         {
             $pdf = new Html2Pdf();
             $pdf->writeHTML($html);
             $pdf->output();

         }
         else{
             $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('FILE_NOT_FOUND'));

             return $this->redirectToRoute('dossier_aide_demandes', ['dossierID'=>$dossierID]);
         }

    }



    private function getAllDossiers($searchedValue)
    {
        /** @var Utilisateur $user */
        $user = $this->getUser();
        $em= $this->getDoctrine()->getManager();
        $interlocuteurs = $user->getInterlocuteurSiret();
        $dossiers = [];
        $session = new Session();
        if($session->has('interlocuteurSelected') ){
            $interlocuteurSiretSelected = $session->get('interlocuteurSelected');
        }else{
            $interlocuteurSiretSelected = 'tous';
        }

        if($searchedValue != null){
            if($interlocuteurSiretSelected == 'tous'){
                foreach ($interlocuteurs as $interlocuteur)
                $dossiers = array_merge($dossiers,  $em->getRepository('AppBundle:DossierAide')->findByFilter($interlocuteur->getSiret(),$searchedValue));
            }else{
                $dossiers = array_merge($dossiers,  $em->getRepository('AppBundle:DossierAide')->findByFilter($interlocuteurSiretSelected,$searchedValue));

            }
        }else{
            if($interlocuteurSiretSelected == 'tous'){
                foreach ($interlocuteurs as $interlocuteur){
                    $dossiers = array_merge($dossiers,  $em->getRepository('AppBundle:DossierAide')->findBy(['interlocuteurSiret' => $interlocuteur->getSiret()],['dateNotification' => 'DESC']));
                }
            }else{
                $dossiers = array_merge($dossiers,  $em->getRepository('AppBundle:DossierAide')->findBy(['interlocuteurSiret' => $interlocuteurSiretSelected],['dateNotification' => 'DESC']));
            }
        }


        return $dossiers;
    }


    private function findNextDossier($dossierID,$searchedValue)
    {
        $dossiers = $this->getAllDossiers($searchedValue);

        for($i=0; $i<count($dossiers); $i++)
        {
            if(gettype($dossiers[$i]) == 'object'){
                $number = $dossiers[$i]->getNumero();
                if ($i<(count($dossiers)-1))
                $nextNumber = $dossiers[$i+1]->getNumero();
            }else{
                $number = $dossiers[$i]['numero'];
                if ($i<(count($dossiers)-1))
                    $nextNumber = $dossiers[$i+1]['numero'];
            }

            if ($number==$dossierID)
            {
                if ($i<(count($dossiers)-1))
                   return $nextNumber;
            }
        }

        return null;
    }

    private function findPreviousDossier($dossierID,$searchedValue)
    {
        $dossiers= $this->getAllDossiers($searchedValue);

        for($i=0; $i<count($dossiers); $i++)
        {
            if(gettype($dossiers[$i]) == 'object'){
                $number = $dossiers[$i]->getNumero();
                if ($i>0)
                $prevNumber = $dossiers[$i-1]->getNumero();
            }else{
                $number = $dossiers[$i]['numero'];
                if ($i>0)
                    $prevNumber = $dossiers[$i-1]['numero'];
            }
            if ($number==$dossierID)
            {
                if ($i>0)
                    return $prevNumber;
            }
        }

        return null;
    }


}