<?php


namespace Shop\Repositories\Manager;


use Diamond\Repositories\PropelAbstractRepository;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Repo\CollectionInterface;
use Repo\CrudRepositoryBuilderInterface;
use Repo\EntityInterface;
use Repo\PaginationInterface;
use Shop\Domain\Manager\Contracts\ManagerCriteriaInterface;
use Shop\Domain\Manager\ManagerCollection;
use Shop\Models\Manager\Manager;
use Shop\Models\Manager\ManagerQuery;

class ManagerRepository extends PropelAbstractRepository implements CrudRepositoryBuilderInterface
{
    public static function createEntity(): EntityInterface
    {
        return new Manager();
    }

    protected function createQuery(): ModelCriteria
    {
        return ManagerQuery::create();
    }

    /**
     * @param PaginationInterface|ManagerCriteriaInterface $criteria
     * @param ModelCriteria|ManagerQuery $dbCriteria
     */
    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {
        $this->modifyCriteriaForFilterSort($criteria,$dbCriteria);

        $dbCriteria
            ->_if($criteria->getSearchByEmail()!==null)
            ->filterByEmail('%' . $criteria->getSearchByEmail() . '%', Criteria::LIKE)
            ->_endif()

            ->_if($criteria->getSearchByName()!==null)
            ->filterByName('%' . $criteria->getSearchByName() . '%', Criteria::LIKE)
            ->_endif()

            ->_if($criteria->getFilterByEmail()!==null)
            ->filterByEmail($criteria->getFilterByEmail())
            ->_endif()

            ->_if($criteria->getFilterByActiveStock()!==null)
            ->useShopQuery()
            ->filterByActive($criteria->getFilterByActiveStock()===true?'Y':'N')
            ->endUse()
            ->_endif()

            ->_if($criteria->getFilterByStockId()!==null)
            ->filterByShopId($criteria->getFilterByStockId())
            ->_endif()

            ->_if($criteria->getSortByName()!==null)
            ->orderByName($criteria->getSortByName())
            ->_endif()
            ;
    }

    public function findByCriteria(PaginationInterface $criteria): CollectionInterface
    {
        $query = $this->createQuery();
        $this->modifyCriteria($criteria, $query);
        $result = $query->paginate($criteria->getPage(), $criteria->getLimit());

        $collection = new ManagerCollection();

        foreach ($result->getResults() as $row) {
            $collection->push($row);
        }

        return $collection;
    }

}