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

namespace CpCreation\VitiCore\Shop\Repository;

use CpCreation\VitiCore\Repository\BaseRepository;
use CpCreation\VitiCore\Shop\Model\ShippingAdditionalManual;
use CpCreation\VitiCore\Shop\Model\ShippingZone;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;

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


    /**
     * @param int                 $qty
     * @param string              $type
     * @param ShippingZone        $zone
     * @param                     $group
     * @return int|mixed|string|null
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findByQuantityAndByTypeAndByZoneAndByGroup(int $qty,
        string $type,
        ShippingZone $zone,
        $group
    ) {

        $datetime = new \DateTime();
        $dateInt = date("nd", $datetime->getTimestamp());
        $qb = $this
            ->createQueryBuilder('a')
            ->innerJoin('a.types', 't')
            ->innerJoin('t.translations', 'tr', Join::WITH, 'tr.slug = :type')
            ->innerJoin('a.zones', 'z', Join::WITH, 'z.id = :zone')
            ->innerJoin('a.groups', 'g', Join::WITH, 'g.id = :group')
            ->andwhere('a.qtyOf < :qty')
            ->andwhere('a.qtyAt >= :qty')
            ->andwhere('a.dateOf <= :dateInt')
            ->andwhere('a.dateAt >= :dateInt')
            ->setParameter('dateInt', $dateInt)
            ->setParameter('qty', $qty)
            ->setParameter('type', $type)
            ->setParameter('group', $group)
            ->setParameter('zone', $zone->getId()->toString())
            ->addOrderBy('a.qtyAt', 'DESC');


        return $qb->getQuery()->setMaxResults(1)->getOneOrNullResult();
    }
}
