<?php

/*
 * This file is part of the VitiCore 2.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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.
     *
     * @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', mb_strtoupper($cart->getPromo()))
            ->setParameter('now', new \DateTime())
            ->getQuery();

        return $qb->getOneOrNullResult();
    }
}
