<?php

namespace Shop\Repositories\ProviderOrder;

use Diamond\Repositories\PropelAbstractRepository;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Repo\CollectionInterface;
use Repo\CrudRepositoryBuilderInterface;
use Repo\EntityInterface;
use Repo\PaginationInterface;
use Shop\Domain\ProviderOrder\Contracts\ProviderOrderCriteriaInterface;
use Shop\Domain\ProviderOrder\ProviderOrderCollection;
use Shop\Models\Order\Order;
use Shop\Models\Order\OrderQuery;
use Shop\Models\OrderItem\OrderItemQuery;
use Shop\Models\OrderType\OrderType;
use Shop\Models\ProviderOrderItem\ProviderOrderItemQuery;

class ProviderOrderRepository extends PropelAbstractRepository implements CrudRepositoryBuilderInterface
{
//    public function delete(EntityInterface $entity): void
//    {
//
//        $res = OrderItemQuery::create()->filterByOrderId($entity->getId())->delete();
//
//        dd($res);
//
//        parent::delete($entity); // TODO: Change the autogenerated stub
//    }


    /**
     * @return EntityInterface|Order
     */
    public static function createEntity(): EntityInterface
    {
        return (new Order())->setTypeId(OrderType::TYPE_PROVIDER_ORDER);
    }

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

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

        $dbCriteria
            ->_if($criteria->getFilterByStateId()!==null)
            ->filterByStateId($criteria->getFilterByStateId())
            ->_endif()
            ->_if($criteria->getFilterByOrderCode()!==null)
            ->filterById((int)preg_replace('~.*-(\d+)$~is','$1',$criteria->getFilterByOrderCode()))
            ->_endif()

            ->filterByTypeId(OrderType::TYPE_PROVIDER_ORDER)
            ;
    }

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

        $collection = new ProviderOrderCollection();

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

        return $collection;
    }

}