<?php

namespace Shop\Repositories\ProviderOrderItem;

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\ProviderOrderItem\ProviderOrderItemCollection;
use Shop\Models\OrderItem\OrderItem;
use Shop\Models\OrderItem\OrderItemQuery;
use Shop\Models\OrderType\OrderType;

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

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

    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {

        $this->modifyCriteriaForFilterSort($criteria,$dbCriteria);

        $dbCriteria
            ->_if($criteria->getFilterByOrderIds() !== null)
            ->filterByOrderId($criteria->getFilterByOrderIds())
            ->_endif()
            ->_if($criteria->getFilterByOrderCode()!==null)
            ->filterByOrderId((int)preg_replace('~.*-(\d+)$~is','$1',$criteria->getFilterByOrderCode()))
            ->_endif()
            ->_if($criteria->getSearchByName()!==null)
            ->filterByName('%' . $criteria->getSearchByName() . '%',Criteria::LIKE)
            ->_endif()
            ->_if($criteria->getSearchByArticle()!==null)
            ->filterByArticle('%' . $criteria->getSearchByArticle() . '%',Criteria::LIKE)
            ->_endif()
            ->_if($criteria->getSearchByBrand()!==null)
            ->filterByBrand('%' . $criteria->getSearchByBrand() . '%',Criteria::LIKE)
            ->_endif()
            ->_if($criteria->getFilterByProviderId()!==null)
            ->filterByProviderId($criteria->getFilterByProviderId())
            ->_endif()
            ->_if($criteria->getFilterByStateId()!==null)
            ->filterByStateId($criteria->getFilterByStateId())
            ->_endif()
            ->useOrderQuery()
            ->filterByTypeId(OrderType::TYPE_PROVIDER_ORDER)
            ->endUse()
            ;
    }

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

        $collection = new ProviderOrderItemCollection();

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

        return $collection;
    }

}