<?php


namespace Shop\Infrastructure\Repositories\CustomerOrder;


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\CustomerOrder\Contracts\CustomerOrderCriteriaInterface;
use Shop\Domain\CustomerOrder\Contracts\CustomerOrderEntityInterface;
use Shop\Domain\CustomerOrder\CustomerOrderCollection;
use Shop\Infrastructure\Models\Order\Order;
use Shop\Infrastructure\Models\Order\OrderQuery;
use Shop\Infrastructure\Models\OrderType\OrderType;
use Shop\Infrastructure\Models\PaymentTransaction\PaymentTransactionQuery;

class CustomerOrderRepository extends PropelAbstractRepository implements CrudRepositoryBuilderInterface
{
    /**
     * @return EntityInterface|Order
     */
    public static function createEntity(): EntityInterface
    {
        return (new Order())->setTypeId(OrderType::TYPE_CUSTOMER_ORDER);
    }

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

    /**
     * @param PaginationInterface|CustomerOrderCriteriaInterface $criteria
     * @param ModelCriteria|OrderQuery $dbCriteria
     */
    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {

        $dbCriteria
            
            ->_if($criteria->getFilterByCreateMonthDate() !== null)
            ->filterByDatetime(sprintf(
                '(YEAR(datetime) = %s AND MONTH(datetime) = %s)',
                preg_replace('~\-\d+~is','',$criteria->getFilterByCreateMonthDate()),
                preg_replace('~\d+\-~is','',$criteria->getFilterByCreateMonthDate()),
            ),Criteria::CUSTOM)
            ->_endif()
            ->_if($criteria->getFilterByCustomerId() !== null)
            ->filterByCustomerId($criteria->getFilterByCustomerId())
            ->_endif()
            ->_if($criteria->getFilterByStockId() !== null || $criteria->getFilterByStockIds() !== null)
            ->useContractorQuery()
            ->useShopQuery()
            ->filterById(
                array_unique(
                    array_merge(
                        (array)$criteria->getFilterByStockId(), (array)$criteria->getFilterByStockIds()
                    )
                )
            )
            ->endUse()
            ->endUse()
            ->_endif()
            ->_if($criteria->getFilterByStateId() !== null)
            ->filterByStateId($criteria->getFilterByStateId())
            ->_endif()
            ->_if($criteria->getFilterByOrderCode() !== null)
            ->filterById((int)preg_replace('~.*-(\d+)$~is', '$1', $criteria->getFilterByOrderCode()))
            ->_endif()
            //static filter
            ->filterByTypeId(OrderType::TYPE_CUSTOMER_ORDER);

    }

    public function findByCriteria(PaginationInterface $criteria): CollectionInterface
    {
        $query = $this->createQuery();
        self::modifyCriteriaForFilterSort($criteria, $query);

        $this->modifyCriteria($criteria, $query);

        $result = $query->paginate($criteria->getPage(), $criteria->getLimit());

        $collection = self::createCollection();

        /**
         * @var CustomerOrderEntityInterface $row
         * @todo отвязаться от транзакции паймастера
         */
        foreach ($result->getResults() as $row) {
            $tran = PaymentTransactionQuery::create()
                ->filterByOrderId($row->getId())
                ->filterByConfirmed("Y")
                ->findOne();

            if ($tran) {
                $row->setIsPayment(true);
            }
            $collection->push($row);
        }

        return $collection;
    }

    protected function createCollection(): CollectionInterface
    {
        return new CustomerOrderCollection();
    }


    public function delete(EntityInterface $entity): void
    {
        \Shop\Infrastructure\Models\SyncLog\SyncLogQuery::create()->filterByOrderId($entity->getId())->delete();
        parent::delete($entity);
    }

}
