<?php


namespace Shop\Repositories\PaymentTransaction;


use Diamond\Repositories\PropelAbstractRepository;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Repo\CollectionInterface;
use Repo\CrudRepositoryBuilderInterface;
use Repo\EntityInterface;
use Repo\PaginationInterface;
use Shop\Domain\PaymentTransaction\Contracts\PaymentTransactionCriteriaInterface;
use Shop\Domain\PaymentTransaction\PaymentTransactionCollection;
use Shop\Models\PaymentTransaction\PaymentTransaction;
use Shop\Models\PaymentTransaction\PaymentTransactionQuery;

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

    /**
     * @return ModelCriteria
     */
    protected function createQuery(): ModelCriteria
    {
        return PaymentTransactionQuery::create();
    }

    /**
     * @param PaginationInterface $criteria
     * @param ModelCriteria $dbCriteria
     */
    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {
        $this->modifyCriteriaForFilterSort($criteria, $dbCriteria);
        $dbCriteria
            ->_if($criteria->getFilterByCode() !== null)
            ->filterByCode($criteria->getFilterByCode())
            ->_endif()
            ->_if($criteria->getFilterByOrderId()!==null)
            ->filterByOrderId($criteria->getFilterByOrderId())
            ->_endif()
        ;
    }

    /**
     * @param PaginationInterface $criteria
     * @return CollectionInterface
     * @throws \Repo\Concrete\Exceptions\Collection
     */
    public function findByCriteria(PaginationInterface $criteria): CollectionInterface
    {
        $query = $this->createQuery();
        $this->modifyCriteria($criteria, $query);
        $result = $query->paginate($criteria->getPage(), $criteria->getLimit());

        $collection = new PaymentTransactionCollection();

        /**
         * @var CustomerOrderEntityInterface $row
         * @todo отвязаться от транзакции паймастера
         */
        foreach ($result->getResults() as $row) {
            $collection->push($row);
        }

        return $collection;
    }

}