<?php

namespace App\Repository\Campaign\Hours;

use App\Entity\Campaign;
use App\Entity\Campaign\Hours;
use App\Service\Campaign\HoursRepositoryInterface;
use DateTime;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Doctrine\ORM\Query\ResultSetMappingBuilder;
use Symfony\Bridge\Doctrine\RegistryInterface;

final class DoctrineHoursRepository extends ServiceEntityRepository implements HoursRepositoryInterface
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, Hours::class);
    }

    public function findById(int $id): ?Hours
    {
        return $this->findOneBy(['id' => $id]);
    }

    /**
     * @param Hours $hours
     *
     * @throws ORMException
     * @throws OptimisticLockException
     */
    public function save(Hours $hours): void
    {
        $this->_em->persist($hours);
        $this->_em->flush();
    }

    /**
     * @param Hours $hours
     *
     * @throws ORMException
     * @throws OptimisticLockException
     */
    public function delete(Hours $hours): void
    {
        $this->_em->remove($hours);
        $this->_em->flush();
    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        $result = $this->queryByGrid($criteria, $orderBy, $limit, $offset);

        return $result->toArray();
    }

    /**
     * @param array|null $orderBy
     * @param int|null $limit
     * @param int|null $offset
     */
    private function queryByGrid(array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null): Collection
    {
        $newCriteria = Criteria::create()
            ->setFirstResult($offset)
            ->setMaxResults($limit);

        if ($orderBy) {
            $newCriteria->orderBy($orderBy);
        }

        if (array_key_exists('q', $criteria)) {
            $newCriteria->where(Criteria::expr()->contains('title', $criteria['q']))
                ->orWhere(Criteria::expr()->contains('description', $criteria['q']));
        }

        if (array_key_exists('campaign', $criteria)) {
            $newCriteria->andWhere(Criteria::expr()->in('campaign', $criteria['campaign']));
        }

        if (array_key_exists('category', $criteria)) {
            $newCriteria->andWhere(Criteria::expr()->in('category', $criteria['category']));
        }

        if (array_key_exists('startOfTheMonth', $criteria)) {
            $newCriteria->andWhere(Criteria::expr()->lte('startOfTheMonth', DateTime::createFromFormat('Y-m-d',
                $criteria['startOfTheMonth'][0])));
        }

        return $this->matching($newCriteria);
    }

    public function count(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        $result = $this->queryByGrid($criteria);

        return $result->count();
    }

    public function getHours(Campaign $campaign, string $startOfTheMonth)
    {
        $rsm = new ResultSetMappingBuilder($this->_em);
        $rsm->addRootEntityFromClassMetadata('App\Entity\Campaign\Hours', 'a');
        $query = $this->_em->createNativeQuery('select a.* from campaign_hours a inner join (select campaign_id, category_id, max(start_of_the_month) as start_of_the_month, max(id) as id from campaign_hours where start_of_the_month <= :startOfTheMonth group by category_id, campaign_id) as b on a.campaign_id = b.campaign_id and a.category_id = b.category_id and a.`start_of_the_month` = b.`start_of_the_month`and a.id = b.id where a.campaign_id = :campaignId', $rsm);
        $query->setParameter('startOfTheMonth', $startOfTheMonth);
        $query->setParameter('campaignId', $campaign->getId());

        return $query->getResult();
    }
}
