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

namespace CpCreation\VitiCore\Cart\Repository;

use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Cart\Model\Promo;
use CpCreation\VitiCore\Product\Model\ProductVariant;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;

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

    public function countPromoByUser(Promo $promo, Cart $cart)
    {
        $qb = $this->createQueryBuilder('c');
        $qb
            ->andWhere('c.promoId = :promo')
            ->andWhere('cart_checkout.payedAt IS NOT NULL');
        $qb->andWhere(
            $qb->expr()->orX(
                $qb->expr()->eq(
                    $qb->expr()->substring('invoice_address.phone', -8),
                    $qb->expr()->literal(substr($cart->getInvoiceAddress()->getPhone(), -8))
                ),
                $qb->expr()->eq('invoice_address.email', $qb->expr()->literal($cart->getInvoiceAddress()->getEmail()))
            ));
        $qb
            ->innerJoin('c.cartCheckout', 'cart_checkout', Join::WITH, 'cart_checkout.cart = c.id')
            ->innerJoin('c.invoiceAddress', 'invoice_address')
            ->setParameter('promo', $promo->getId()->toString());

        $query = $qb->getQuery();

        return $query->getResult();
    }

    public function stockSaleSinceStockAt(ProductVariant $variant)
    {
        $qb = $this->createQueryBuilder('c');
        $qb->innerJoin('c.items', 'item', Join::WITH, 'item.variant = :variant')
            ->setParameter('variant', $variant->getId()->toString())
            ->innerJoin('c.cartCheckout', 'checkout')
            ->andWhere('checkout.payedAt is NOT NULL')
            ->andWhere('c.createdAt > :stockAt')
            ->setParameter('stockAt', $variant->getStockAt())
            ->select('SUM (item.quantity) as quantitySale');

        $query = $qb->getQuery();

        return $query->execute();
    }
}
