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

namespace CpCreation\VitiCore\Shop\Repository;

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

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

    /**
     * @param ShippingCountry     $country
     * @param ShippingCounty|null $county
     * @return int|mixed|string|null
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findByCountryAndByCounty(ShippingCountry $country, ?ShippingCounty $county)
    {
        $qb = $this
            ->createQueryBuilder('z')
            ->innerJoin('z.countries', 'country', Join::WITH, 'country.id = :country')
            ->setParameter('country', $country->getId()->toString());

        if ($country->isCounty() && $county) {
            $qb->innerJoin('z.counties', 'county', Join::WITH, 'county.id = :county')
               ->setParameter('county', $county->getId()->toString());
        }else{
            $qb->innerJoin('z.counties', 'county', Join::WITH, 'county.id is NULL');
        }

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