<?php

namespace App\Location\Repository;

use App\Location\Entity\City;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    /** @return City[] */
    public function findActive(?int $provinceId = null): array
    {
        $qb = $this->createQueryBuilder('c')
            ->where('c.status = 1')
            ->orderBy('c.weight', 'ASC')
            ->addOrderBy('c.name', 'ASC');

        if ($provinceId !== null) {
            $qb->andWhere('c.province = :province')->setParameter('province', $provinceId);
        }

        return $qb->getQuery()->getResult();
    }

    public function findByDomain(string $domain): ?City
    {
        return $this->findOneBy(['domain' => $domain]);
    }

    public function save(City $city, bool $flush = true): void
    {
        $this->getEntityManager()->persist($city);
        if ($flush) $this->getEntityManager()->flush();
    }

    public function remove(City $city, bool $flush = true): void
    {
        $this->getEntityManager()->remove($city);
        if ($flush) $this->getEntityManager()->flush();
    }
}
