<?php

/**
 * Created by PhpStorm.
 * User: Arthur Touzard
 * Date: 19/04/2018
 * Time: 15:28
 */

namespace AppBundle\Entity\Repositories;

use AppBundle\Entity\Interlocuteur;
use AppBundle\Entity\Utilisateur;
use Doctrine\ORM\EntityRepository;

class DocumentDispositionRepository extends EntityRepository {

    public function getDocumentsSQL(Utilisateur $user, $limit = null) {

        $t_list = $user->getThematiqueCodes();
        $i_list = $user->getInterlocuteurSiretList();

        $docs = $this->getEntityManager()->createQueryBuilder()
                ->select('dd')->distinct()
                ->from('AppBundle:DocumentDisposition', 'dd')
                ->leftJoin('dd.interlocuteurSiret', 'i')
                ->where("dd.thematiqueCode IN (:t_list)")
                ->andWhere("(dd.interlocuteurSiret IN (:i_list) OR dd.interlocuteurSiret IS NULL OR dd.interlocuteurSiret = '')")
                ->andWhere("(dd.dateFinPublication IS NULL OR dd.dateFinPublication >= :today)")
                ->setParameter(':t_list', $t_list)
                ->setParameter(':i_list', $i_list)
                ->setParameter(':today', new \DateTime())
                ->setMaxResults($limit)
                ->getQuery()
                ->getResult();

        $docsPonderes = array();
        $docsTelecharges = $this->getEntityManager()->getRepository('AppBundle:TelechargementDocumentDisposition')->findTelechargerInterlocuteur($i_list);
        foreach ($docs as $doc) {
            $found = 0;
            foreach ($docsTelecharges as $dt) {
                if ($doc == $dt->getDocumentDisposition()) {
                    $docsPonderes[] = [1, $doc];
                    $found = 1;
                    break;
                }
            }
            if($found == 0) $docsPonderes[] = [0, $doc];
        }

        return $docsPonderes;
    }

}
