<?php

namespace Bspb\Pay;

use BspbSDK\Entity\Request\GetOrderInfoRequest;
use BspbSDK\Entity\Request\Part\Receipt;
use BspbSDK\Entity\Request\Part\ReceiptCollection;
use BspbSDK\Entity\Request\RefundOrderFullRequest;
use BspbSDK\Entity\Response\GetOrderInfoResponse;
use BspbSDK\Other\FloatPrecisionSetSaver;

class BspbPayment extends \WC_Payment_Gateway
{
    use OverallTrait;
    use DBTrait;

    const PAID_STATUS = 'FullyPaid';

    public $supports = ['products', 'refunds'];

    /**
     * @var FloatPrecisionSetSaver
     */
    private $floatFixer;

    /** @var string */
    private $crtDir;

    public function __construct()
    {

        global $wpdb;

        $this->id = BspbPlugin::PAYSYSTEMCODE;
        $this->icon = '';
        $this->title = $this->get_option('title');
        $this->description = $this->get_option('description_site');
        $this->method_title = $this->get_option('title');
        $this->method_description = __('Оплаты при помощи эквайринга Банка Санкт-Петербург','woocommerce');

        $this->init_form_fields();
        $this->init_settings();

        $this->db = $wpdb;
        $this->tableFullName = $this->db->get_blog_prefix() . self::$tableName;

        $this->enabled = $this->get_option('enabled');
        $this->title = $this->get_option('title');
        $this->description = $this->get_option('description_site');
        $this->merchant = $this->get_option('merchant');
        $this->password = $this->get_option('password');
        $this->isTest = $this->get_option('isTest') === 'yes';
        $this->isOFD = $this->get_option('isOFD') === 'yes';
        $this->enLog = $this->get_option('IsLog') === 'yes';

        $this->crtDir = BspbPlugin::getPluginDir() . DIRECTORY_SEPARATOR . 'crt' . DIRECTORY_SEPARATOR;

        $this->certName1 = $this->crtDir . $this->get_option('cert1_path');
        $this->certName2 = $this->crtDir . $this->get_option('cert2_path');

        if (strlen($this->get_option('cert1_name')) > 0)
            $this->form_fields['cert1']['description'] = 'Файл ' . $this->get_option('cert1_name') . ' успешно загружен!';

        if (strlen($this->get_option('cert2_name')) > 0)
            $this->form_fields['cert2']['description'] = 'Файл ' . $this->get_option('cert2_name') . ' успешно загружен!';

        $this->floatFixer = new FloatPrecisionSetSaver();

        add_action('woocommerce_api_wc_' . $this->id, [$this, 'restFunctions']);
        add_action('woocommerce_update_options_payment_gateways_' . $this->id, [$this, 'process_admin_options']);

        $systemTimeZone = ini_get('date.timezone');
        if (!empty($systemTimeZone)) {
            date_default_timezone_set($systemTimeZone);
        }
    }
// woocommerce_woocommerce-bspb_cert1_name
    public function process_admin_options() {
        parent::process_admin_options();

        if (array_key_exists('woocommerce_woocommerce-bspb_cert1', $_FILES)
            && array_key_exists('tmp_name', $_FILES['woocommerce_woocommerce-bspb_cert1'])
            && array_key_exists('size', $_FILES['woocommerce_woocommerce-bspb_cert1'])
            && $_FILES['woocommerce_woocommerce-bspb_cert1']['size']
        ) {
            $this->update_option('cert1_name', $_FILES['woocommerce_woocommerce-bspb_cert1']['name']);
            $cert1Name = substr(md5(time()), 0, 16) . '.pem';
            move_uploaded_file($_FILES['woocommerce_woocommerce-bspb_cert1']['tmp_name'], $this->crtDir . $cert1Name);
            if (file_exists($_FILES['woocommerce_woocommerce-bspb_cert1']['tmp_name'])) unlink($_FILES['woocommerce_woocommerce-bspb_cert1']['tmp_name']);
            unset($_FILES['woocommerce_woocommerce-bspb_cert1']);
            $this->update_option('cert1_path', $cert1Name);
        }

        if (array_key_exists('woocommerce_woocommerce-bspb_cert2', $_FILES)
            && array_key_exists('tmp_name', $_FILES['woocommerce_woocommerce-bspb_cert2'])
            && array_key_exists('size', $_FILES['woocommerce_woocommerce-bspb_cert2'])
            && $_FILES['woocommerce_woocommerce-bspb_cert2']['size']
        ) {
            $this->update_option('cert2_name', $_FILES['woocommerce_woocommerce-bspb_cert2']['name']);
            $cert2Name = substr(md5(time()), 0, 16) . '.key';
            move_uploaded_file($_FILES['woocommerce_woocommerce-bspb_cert2']['tmp_name'], $this->crtDir . $cert2Name);
            if (file_exists($_FILES['woocommerce_woocommerce-bspb_cert2']['tmp_name'])) unlink($_FILES['woocommerce_woocommerce-bspb_cert2']['tmp_name']);
            unset($_FILES['woocommerce_woocommerce-bspb_cert2']);
            $this->update_option('cert2_path', $cert2Name);
        }
    }

    public function process_payment($order_id)
    {
        $order_id = intval($order_id);
        $order = new \WC_Order($order_id);
        $order->update_status('on-hold', 'Ожидается оплата');

        $this->floatFixer->changePrecisionForApiCall();

        $order_items = $order->get_items();
        $orderTotal = $order->get_total();
        $order_total = intval(round(floatval($order->get_total())*100, 0)) / 100;

        $basketItems = [];
        foreach ($order_items as $item) {
            $ord_item = new \WC_Order_Item_Product($item->get_id());

            $total = floatval($ord_item->get_total_tax())+floatval($ord_item->get_total());
            $qty = $ord_item->get_quantity();
            $price_for_one = $total / $qty;
            $price_for_one_norm = intval(round($price_for_one*100)) / 100;

            if ($price_for_one_norm == 0) continue;

            $taxCode = intval($this->settings['productTax']);
            $tax = new \WC_Tax();
            $variantId = $item['variation_id'];
            if ($variantId) $product = new \WC_Product_Variation($item['variation_id']);
            else $product = new \WC_Product($item['product_id']);
            if (get_option("woocommerce_calc_taxes") != "no") {
                $taxVal = $tax->get_base_tax_rates($product->get_tax_class(true));
                if (!empty($taxVal)) {
                    $rates = $tax->get_rates($product->get_tax_class());
                    if (!empty($rates)) {
                        $rateVal = intval(array_shift($rates)['rate']);
                        //$taxCode = $this->getTaxCode($rateVal) ?? $taxCode;
                    }
                }
            }

            $basketItems[$item->get_id()] = [
                'id' => $item->get_id(),
                'var_id'=>$variantId,
                'qty' => $ord_item->get_quantity(),
                'price' => $price_for_one_norm,
                'name'=>$item['name'],
                //'tax' => $taxCode,
            ];
        }

        //add Shipment Data
        $shippings = $order->get_shipping_methods();
        if (count($shippings) > 0) {
            $shipping = array_shift($shippings);
            $shipping_id = $shipping->get_id();
            $shipping_name = $shipping->get_name();
            $shipping_price = intval(round(( floatval($shipping->get_total()) + floatval($shipping->get_total_tax()) )*100, 0)) / 100;

            if ($shipping_price > 0) {
                /*$shippingTaxCode = intval($this->settings['deliveryTax']);
                $shippingTaxes = $shipping->get_taxes();
                if (is_array($shippingTaxes) && !empty($shippingTaxes) && !empty($shippingTaxes['total'])) {
                    foreach ($shippingTaxes['total'] as $tax_rate_id=>$val) {
                        if ($tax_rate_id > 0) {
                            $rateVal = $this->db->get_var($this->db->prepare("SELECT `tax_rate` FROM `{$this->db->base_prefix}woocommerce_tax_rates` WHERE `tax_rate_id` = %d;",$tax_rate_id));
                            if ($rateVal) {
                                //$shippingTaxCode = $this->getTaxCode(intval($rateVal)) ?? $shippingTaxCode;
                                break;
                            }
                        }
                    }
                }*/

                $basketItems['dlv'] = [
                    'id'=>$shipping_id,
                    'var_id'=>0,
                    'type'=>'dlv',
                    'qty'=>1,
                    'price'=>$shipping_price,
                    'name'=>$shipping_name,
                    //'tax'=>$shippingTaxCode,
                ];
            }
        }

        // Corrector
        $basketCorrector = new \BspbSDK\Other\CalcBasketFixer($basketItems,$order_total);
        if (!$basketCorrector->checkNoNeedRecalc())
            $basketItems = $basketCorrector->correctBasket();

        $receiptCollection = new \BspbSDK\Entity\Request\Part\ReceiptCollection();
        foreach ($basketItems as $bItem) {
            $receipt = (new \BspbSDK\Entity\Request\Part\Receipt())
                ->setDesc($bItem['name'])
                ->setPrice($bItem['price'])
                ->setQuantity($bItem['qty'])
                ->setMeasure(0);
            $receiptCollection->add($receipt);
        }

        $createOrderRequest = (new \BspbSDK\Entity\Request\CreateOrderRequest())
            ->setAmount($order_total)
            ->setDescription('Order N'.$order_id)
            ->setTitle('Order N'.$order_id)
            ->setHppRedirectUrl(site_url() . '/?wc-api=wc_' . $this->id . '&action=bspb_payreturn');

        if ($this->isOFD) {
            $clientMail = $order->get_billing_email();
            if (!empty($clientMail)) $createOrderRequest->setSrcEmail($clientMail);
            $createOrderRequest->setReceipt($receiptCollection);
        }

        $bspbApi = $this->createBspbSdk();
        $result = $bspbApi->createOrder($createOrderRequest);
        if (!$result->isSuccess()) {
            wc_add_notice('Ошибка создания оплаты. Сообщение платежной системы: ' . $result->getOrigin(),'error');
            $order->add_order_note('Ошибка создания оплаты. Сообщение платежной системы: ' . $result->getOrigin());
        } else {
            $this->correctWPOrder($order_id,$basketItems);

            $orderData = [
                'wp_order_id' => $order_id,
                'amount' => intval(round($order_total * 100)),
                'bank_order_id' => $result->getId(),
                'password' => $result->getPassword(),
                'hppUrl' => $result->getHppUrl(),
                'status' => 'Preparing',
                'basketdata' => serialize($basketItems),
            ];
            $this->createOrder($orderData);

            $order->add_order_note('Создана оплата БСПБ');

            $this->floatFixer->restoreUserSystemPrecision();

            return [
                'result' => 'success',
                'redirect' => $result->getHppUrlFull(),
            ];

        }
        $this->floatFixer->restoreUserSystemPrecision();
        return [
            'result' => 'fail',
            'redirect' => $this->get_return_url($order)
        ];
    }
    //Correct Order Items Data - delete TAX info && correct item Price
    private function correctWPOrder(int $order_id, array $basketItems)
    {
        $order = wc_get_order($order_id);
        foreach ($basketItems as $item) {
            //correctShipping
            if (!empty($item['type']) && ($item['type'] == 'dlv')) {
                $shipings = $order->get_shipping_methods();
                foreach ($shipings as $shipping) {
                    if (intval($shipping->get_id()) == $item['id']) {
                        $shipping->set_taxes([]);
                        $shipping->set_total($item['price']);
                        $shipping->save();
                        break;
                    }
                }
            } else {
                if (!empty($item['is_new']) && ($item['is_new'] == 'yes')) {
                    $currentProduct = new \WC_Order_Item_Product($item['id']);

                    $newProduct = new \WC_Order_Item_Product();
                    $newProduct->set_product($currentProduct->get_product());
                    $newProduct->set_variation_id($currentProduct->get_variation_id());
                    $newProduct->set_order_id($currentProduct->get_order_id());
                    $newProduct->set_quantity($item['qty']);
                    $newProduct->set_name($item['name']);
                    $newProduct->set_taxes([]);
                    $newProduct->set_total($item['price']);
                    $newProduct->save();
                } else {
                    $product = new \WC_Order_Item_Product($item['id']);
                    $product->set_taxes([]);
                    $product->set_quantity($item['qty']);
                    $product->set_total( ($item['price'] * $item['qty']) );
                    $product->set_subtotal( ($item['price'] * $item['qty']) );
                    $product->save();
                }
            }
        }
    }

// /?wc-api=wc_woocommerce-bspb&action=bspb_wh&ORDER_ID=2000000011539&ORDER_STATUS=FullyPaid
    public function restFunctions()
    {
        global $woocommerce;

        $action = '';
        if (isset($_REQUEST['action'])) $action = sanitize_text_field($_REQUEST['action']);
        $bankOrderId = sanitize_text_field($_REQUEST['ID'] ?? '');
        if (isset($_REQUEST['ORDER_ID'])) $bankOrderId = sanitize_text_field($_REQUEST['ORDER_ID']);
        //$bankOrderId = intval($bankOrderId);
        $orderStatus = sanitize_text_field($_REQUEST['STATUS']);
        if (isset($_REQUEST['ORDER_STATUS'])) $orderStatus = sanitize_text_field($_REQUEST['ORDER_STATUS']);

        switch ($action) {
            case 'bspb_payreturn':
                //check order
                if (empty($bankOrderId)) {
                    $this->generateErrorPage([ 'Ошибка. Заказ не определен.']);
                    exit();
                }

                $updatedOrderData = $this->getCurrentOrderStatus($bankOrderId);
                if ($updatedOrderData === null) {
                    $this->generateErrorPage(['Этот заказ не найден.'], 'Перейти на главную страницу');
                    exit();
                }
                if (!empty($updatedOrderData['error'])) {
                    $this->generateErrorPage(['В процессе обновления информации о заказе возникли ошибки.',$updatedOrderData['error']], 'Перейти на главную страницу');
                    exit();
                }
                if ($updatedOrderData['status'] != self::PAID_STATUS) {
                    $this->generateErrorPage(['Оплата заказа завершилась неудачей.'], 'Перейти на главную страницу');
                    exit();
                }

                $orderId = intval($updatedOrderData['wp_order_id']);
                $order = new \WC_Order($orderId);
                $woocommerce->cart->empty_cart();
                $order->update_status('processing', 'Заказ оплачен.');
                $order->payment_complete($bankOrderId);
                wp_redirect($this->get_return_url($order));
                break;
            case 'bspb_wh':
                //check order
                if (empty($bankOrderId)) exit();
                if (empty($orderStatus)) exit();
                if ($orderStatus != self::PAID_STATUS) exit();

                $updatedOrderData = $this->getCurrentOrderStatus($bankOrderId);
                if ($updatedOrderData === null) exit();
                if (!empty($updatedOrderData['error'])) exit();
                if ($updatedOrderData['status'] != self::PAID_STATUS) exit();

                $orderId = intval($updatedOrderData['wp_order_id']);
                $order = new \WC_Order($orderId);
                $woocommerce->cart->empty_cart();
                $order->update_status('processing', 'Заказ оплачен.');
                $order->payment_complete($bankOrderId);
                break;

        }

    }

    public function process_refund( $order_id, $amount = null, $reason = '' ) {
        $orderData = $this->getOrderByWPOrderId(intval($order_id));
        if (!$orderData) return new \WP_Error('1002', "Ошибка возврата: \nДанные заказа не найдены.");

        //get actual order info
        $currentOrderInfo = $this->getCurrentOrderStatus($orderData['bank_order_id']);
        if ($currentOrderInfo === null) return new \WP_Error('1002', "Ошибка возврата: \nНе удалось обновить информацию о заказе.");
        if (!empty($currentOrderInfo['error'])) return new \WP_Error('1002', "Ошибка возврата: \n{$currentOrderInfo['error']}.");
        if ($currentOrderInfo['status'] != self::PAID_STATUS) return new \WP_Error('1002', "Ошибка возврата: \nЗаказ не находится в статусе \"Оплачен\".");

        $this->floatFixer->changePrecisionForApiCall();

        $basketData = unserialize($orderData['basketdata']);
        $receiptCollection = new ReceiptCollection();
        foreach ($basketData as $bItem) {
            $receipt = (new Receipt())
                ->setMeasure(0)
                ->setDesc($bItem['name'])
                ->setPrice($bItem['price'])
                ->setQuantity($bItem['qty']);
            $receiptCollection->add($receipt);
        }

        $refundRequest = (new RefundOrderFullRequest())
            ->setAmount(intval($orderData['amount']) / 100)
            ->setOrderId($orderData['bank_order_id']);
        if ($this->isOFD) $refundRequest->setReceipt($receiptCollection);

        $createdDate = \DateTime::createFromFormat('Y-m-d H:i:s', $orderData['created']);

        $bspbApi = $this->createBspbSdk();
        $result = $bspbApi->cancelOrRefundOrder($refundRequest, $createdDate);
        $this->floatFixer->restoreUserSystemPrecision();
        if (!$result->isSuccess()) return new \WP_Error('1002', "Ошибка возврата: \n{$result->getOrigin()}.");

        $order = new \WC_Order(intval($orderData['wp_order_id']));
        $order->add_order_note( 'БСБП: Возврат произведен на сумму '.($orderData['amount']/100).' Р.' );
        $order->update_status('refunded', 'Оплата возвращена');

        return true;
    }

    private function generateErrorPage(array $errors, $linkText = '', $linkadr = '/')
    {
        $errorMessages = '';
        foreach ($errors as $er) $errorMessages .= "<li>{$er}</li>";

        $link = '';
        if ($linkText!='') $link = '<p><a href="'.$linkadr.'">'.$linkText.'</a></p>';

        get_header();
        echo wp_kses('<div class="woocommerce"><ul class="woocommerce-error" role="alert">'.$errorMessages.'</ul></div>
                        <div style="width:100%;height:100px;"></div>
                        '.$link.'
                        <div style="width:100%;height:100px;"></div>',[
            'div'=>[ 'class'=>[], 'style'=>[] ],
            'br'=>[],
            'ul'=>[ 'class'=>[], 'role'=>[] ],
            'li'=>[],
            'p'=>[],
            'a'=>['href'=>[]]
        ]);
        get_footer();
    }

    public function generate_template_html($key, $data)
    {
        $filePath = BspbPlugin::getPluginDir() . DIRECTORY_SEPARATOR .'assets' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $data['value'] . '.tpl';
        if (!file_exists($filePath) && !is_readable($filePath)) return '';
        $templateContent = file_get_contents($filePath);
        if (!empty($data['templatecontent']))
            foreach ($data['templatecontent'] as $key => $value)
                $templateContent = preg_replace('/#' . $key . '#/', $value, $templateContent);

        return $templateContent;
    }

    public function generate_text_html( $key, $data ) {
        $field_key = $this->get_field_key( $key );
        $defaults  = array(
            'title'             => '',
            'disabled'          => false,
            'class'             => '',
            'css'               => '',
            'placeholder'       => '',
            'type'              => 'text',
            'desc_tip'          => false,
            'description'       => '',
            'custom_attributes' => array(),
        );

        $data = wp_parse_args( $data, $defaults );

        ob_start();
        if ($data['type'] == 'hidden') {
            ?>
            <input class="input-text regular-input <?php echo esc_attr( $data['class'] ); ?>"<?php echo ( ($data['type'] == 'file') && ($data['ftype']=='key') )?' accept=".key"':''; ?><?php echo ( ($data['type'] == 'file') && ($data['ftype']=='pem') )?' accept=".pem"':''; ?> type="<?php echo esc_attr( $data['type'] ); ?>" name="<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" style="<?php echo esc_attr( $data['css'] ); ?>" value="<?php echo esc_attr( $this->get_option( $key ) ); ?>" placeholder="<?php echo esc_attr( $data['placeholder'] ); ?>" <?php disabled( $data['disabled'], true ); ?> <?php echo $this->get_custom_attribute_html( $data ); // WPCS: XSS ok. ?> />
            <?php
        } else {
            ?>
            <tr valign="top">
                <th scope="row" class="titledesc">
                    <label for="<?php echo esc_attr( $field_key ); ?>"><?php echo wp_kses_post( $data['title'] ); ?> <?php echo $this->get_tooltip_html( $data ); // WPCS: XSS ok. ?></label>
                </th>
                <td class="forminp">
                    <fieldset>
                        <legend class="screen-reader-text"><span><?php echo wp_kses_post( $data['title'] ); ?></span></legend>
                        <input class="input-text regular-input <?php echo esc_attr( $data['class'] ); ?>"<?php echo ( ($data['type'] == 'file') && ($data['ftype']=='key') )?' accept=".key"':''; ?><?php echo ( ($data['type'] == 'file') && ($data['ftype']=='pem') )?' accept=".pem"':''; ?> type="<?php echo esc_attr( $data['type'] ); ?>" name="<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" style="<?php echo esc_attr( $data['css'] ); ?>" value="<?php echo esc_attr( $this->get_option( $key ) ); ?>" placeholder="<?php echo esc_attr( $data['placeholder'] ); ?>" <?php disabled( $data['disabled'], true ); ?> <?php echo $this->get_custom_attribute_html( $data ); // WPCS: XSS ok. ?> />
                        <?php echo $this->get_description_html( $data ); // WPCS: XSS ok. ?>
                    </fieldset>
                </td>
            </tr>
            <?php
        }
        return ob_get_clean();
    }

    public function init_form_fields()
    {
        $this->form_fields = array(
            'enabled' => array(
                'title' => __('Активность', 'woocommerce'),
                'type' => 'checkbox',
                'label' => __('Включен', 'woocommerce'),
                'default' => 'yes',
            ),
            'title' => array(
                'title' => __('Название', 'woocommerce'),
                'type' => 'text',
                'description' => __('Название платежной системы на странице оплаты', 'woocommerce'),
                'default' => __('Оплата картой', 'woocommerce'),
            ),
            'description_site' => array(
                'title' => __('Описание заказа для сайта', 'woocommerce'),
                'type' => 'textarea',
                'description' => __('Описание платежной системы на странице оплаты', 'woocommerce'),
                'default' => 'Вы можете оплатить свой заказ',
            ),

            'isTest' => array(
                'title' => __('Тестовый режим', 'woocommerce'),
                'type' => 'checkbox',
                'label' => __('Включить тестовый режим', 'woocommerce'),
                'default' => 'yes',
            ),
            'merchant' => array(
                'title' => __('Merchant', 'woocommerce'),
                'type' => 'text',
                'description' => __('Идентификатор магазина, который выдается банком', 'woocommerce'),
                'default' => '',
            ),
            'password' => [
                'type' => 'password',
                'title' => __('Пароль','woocommerce'),
                'description' => __('Ваш пароль для авторизации при JSON схеме','woocommerce'),
                'default' => ''
            ],
            'cert1' => array(
                'title' => __('Файл *.pem', 'woocommerce'),
                'type' => 'file',
                'ftype' => 'pem',
                'default' => '',
            ),
            'cert2' => array(
                'title' => __('Файл *.key', 'woocommerce'),
                'type' => 'file',
                'ftype' => 'key',
                'default' => '',
            ),
            'isOFD' => array(
                'title' => __('Режим ОФД', 'woocommerce'),
                'type' => 'checkbox',
                'label' => __('Включить отправку чеков', 'woocommerce'),
                'default' => 'yes',
            ),
            'IsLog' => [
                'title' => __('Включить ведение лог-файла запросов', 'woocommerce'),
                'type' => 'checkbox',
                'label' => __('Включен', 'woocommerce'),
                'default' => 'yes',
            ],
            'return_url'=>[
                'type'=>'template',
                'value'=>'returnurl',
                'templatecontent'=>[
                    'returnurl'=>site_url() . '/?wc-api=wc_woocommerce-bspb&action=bspb_wh'
                ]
            ],
        );
    }

    private function createBspbSdk()
    {
        $fileRoute = new \BspbSDK\Logger\Routes\FileRoute(BspbPlugin::getPluginDir() . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . 'log.txt');
        $fileRoute->enable();
        $logger = new \BspbSDK\Logger\Logger([$fileRoute]);

        return new \BspbSDK\Bspb(
            $this->certName1,
            $this->certName2,
            $this->merchant,
            $this->password,
            $this->isTest,
            $this->enLog ? $logger : null
        );
    }

    private function getCurrentOrderStatus($bankOrderId): ?array
    {
        $orderData = $this->getOrderByBankOrderId($bankOrderId);

        if (!$orderData) return null; //error - no data

        $orderData['error'] = '';

        $bspbApi = $this->createBspbSdk();
        $getOrderInfoRequest = (new GetOrderInfoRequest())
            ->setOrderId($orderData['bank_order_id'])
            ->setOrderPassword($orderData['password']);

        $result = $bspbApi->getOrderInfo($getOrderInfoRequest);
        if (!$result->isSuccess()) {
            $orderData['error'] = $result->getOrigin();
        } else {
            /** @var GetOrderInfoResponse $result */
            $this->updateOrder([
                'status' => $result->getStatus(),
            ],intval($orderData['id']));

            $orderData['status'] = $result->getStatus();
        }
        return $orderData;
    }

}
