<?php


namespace Shop\Application\Payment\CreateTransaction;


use Shop\Presentation\Config\Payment;

class CreateTransactionHandler
{
    protected $conf;

    public function __construct(Payment $conf)
    {
        $this->conf = $conf;
    }

    /**
     * @param CreateTransactionCommand $command
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function handle(CreateTransactionCommand $command): void
    {
        $order = $command->getOrder();

        $commission = $this->conf->getCommission();

        $config = (new \Payment\Config)
            ->setCommistion($commission)
            ->setCurrency('RUB')
            ->setMerchantId($this->conf->getMerchantId());

        $paymaster = new \Payment\Paymaster($config);

        //установим ключ
        $final_summ = $paymaster->getPaySumm($order->getOrderFinalSumm());

        //отправка в шаблон
        $data['LMI_MERCHANT_ID'] = $this->conf->getMerchantId();
        $data['LMI_PAYMENT_AMOUNT'] = $final_summ;
        $data['LMI_PAYMENT_DESC'] = 'Оплата заказа ' . $order->getOrderCode();
        $data['commission_notice'] = $commission > 0 ? 'Внимание! Сумма заказа с учетом коммисии ' . $commission . '%' : '';
        $data['order_code'] = $order->getOrderCode();

        $code = $paymaster->getTransactionId(array(
            'LMI_PAYMENT_AMOUNT' => $data['LMI_PAYMENT_AMOUNT'],
            'order_code' => $order->getOrderCode(),
            'LMI_MERCHANT_ID' => $data['LMI_MERCHANT_ID']
        ));

        $transFind = \Shop\Infrastructure\Models\PaymentTransaction\PaymentTransactionQuery::create()
            ->filterByCode($code)
            ->findOne();

        if (!$transFind){
            $trans = new \Shop\Infrastructure\Models\PaymentTransaction\PaymentTransaction;
            $trans
                ->setCommission($commission)
                ->setPayedSumm($data['LMI_PAYMENT_AMOUNT'])
                ->setOrderSumm($order->getOrderFinalSumm())
                ->setDesc($data['LMI_PAYMENT_DESC'])
                ->setOrderId($order->getId())
                ->setCurrency($config->getCurrency())
                ->setCode($code);
            $trans->save();
        }

        if ($transFind && $transFind->getConfirmed() === 'Y') {
            throw new TransactionExistAndConfirmedException('transaction exist by code ' . $code . ' and confirmed');
        }

        $command->getResultCode()->setCode($code);
    }
}