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

namespace CpCreation\VitiCore\Shop\Repository;

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

class DeliveryMethodRepository extends BaseRepository
{
    /**
     * @throws \ReflectionException
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, DeliveryMethod::class);
    }

    public function findPublishQueryBuilder(mixed $groupId = null): QueryBuilder
    {
        $qb = $this
            ->createQueryBuilder('dm')
            ->addSelect('category', 'dmTranslations', 'categoryTranslations', 'shippingPrices')
            ->innerJoin('dm.category', 'category')
            ->leftJoin('dm.translations', 'dmTranslations')
            ->leftJoin('category.translations', 'categoryTranslations')
            ->leftJoin('dm.shippingPrices', 'shippingPrices')
            ->andWhere('dm.publishedAt <= :datetime')
            ->andWhere('dm.unPublishedAt >= :datetime OR dm.unPublishedAt is NULL')
            ->andWhere('dm.disabled = false')
            ->andWhere('dm.deletedAt is NULL')
            ->andWhere('category.disabled = false')
            ->addOrderBy('category.position', 'ASC')
            ->addOrderBy('dm.position', 'ASC')
            ->setParameter('datetime', new \DateTime('now'));

        if ($groupId) {
            $qb
                ->join('dm.groups', 'groups', Join::WITH, 'groups.id = :groupId')
                ->setParameter('groupId', $groupId);
        }

        return $qb;
    }

    public function findPublishByCountyByCategory(string $county): array
    {
        return $this
            ->createQueryBuilder('dm')
            ->andWhere('dm.publishedAt <= :datetime')
            ->andWhere('dm.unPublishedAt >= :datetime')
            ->andWhere('dm.disabled = false')
            ->andWhere('dm.deletedAt is NULL')
            ->innerJoin('dm.category', 'category')
            ->innerJoin('dm.counties', 'counties', Join::WITH, 'counties.code = :county')
            ->addOrderBy('category.position', 'ASC')
            ->addOrderBy('dm.position', 'ASC')
            ->setParameter('datetime', new \DateTime('now'))
            ->setParameter('county', $county)
            ->getQuery()
            ->getResult();
    }
}
