<?php


namespace AutoAdmin\Bundle\Content\Repository;


use AutoAdmin\Bundle\Content\Entity\Domain;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class DomainRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Domain::class);
    }

    public function findMatchingHostAnyLocale(string $domain): ?Domain
    {
        $qb = $this->createQueryBuilder('d');
        $qb->leftJoin('d.locales', 'dl');
        $qb->andWhere('d.domain = :domain')
            ->setParameter('domain', $domain);

        $qb->setMaxResults(1);

        $res = $qb->getQuery()->execute();
        if (!empty($res)) {
            return $res[0];
        }

        return null;
    }

    public function findMatchingHost(string $domain, string $locale): ?Domain
    {
        $qb = $this->createQueryBuilder('d');
        $qb->leftJoin('d.locales', 'dl');
        $qb->andWhere('d.domain = :domain')
            ->setParameter('domain', $domain);
        $qb->andWhere('dl.code = :locale')
            ->setParameter('locale', $locale);

        $qb->setMaxResults(1);

        $res = $qb->getQuery()->execute();
        if (!empty($res)) {
            return $res[0];
        }

        return null;
    }

    public function findMatchingSite(string $site, string $locale)
    {
        $qb = $this->createQueryBuilder('d');
        $qb->leftJoin('d.site', 'ds');
        $qb->andWhere('ds = :site')
            ->setParameter('site', $site);
        $qb->andWhere('dl.code = :locale')
            ->setParameter('locale', $locale);

        $qb->setMaxResults(1);

        $res = $qb->getQuery()->execute();
        if (!empty($res)) {
            return $res[0];
        }

        return null;
    }
}
