<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Product\Repository;

use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Product\Model\ProductGift;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\Persistence\ManagerRegistry;

class ProductGiftRepository extends BaseRepository
{
    /**
     * ProductCategoryRepository constructor.
     * @param ManagerRegistry $registry
     * @throws \ReflectionException
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ProductGift::class);
    }

    /**
     * @throws NonUniqueResultException
     */
    public function findGiftFromCart(Cart $cart): ?ProductGift
    {
        $qb = $this->createQueryBuilder('p')
                   ->andWhere('p.token = :code')
                   ->andWhere('p.usedAt IS NULL')
                   ->andWhere('p.validUntilDate >= :now')
                   ->setParameter('code', strtoupper($cart->getPromo()))
                   ->setParameter('now', new \DateTime())
                   ->getQuery();

        return $qb->getOneOrNullResult();
    }
}