<?php

use Assist\Pay\Helper;
use Assist\Pay\ClientHelper;
use Bitrix\Sale\Order;
use Bitrix\Sale\Payment;

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");

CModule::IncludeModule("sale");

$paymentId = $_GET['payment_id'];
$orderId = $_GET['order_id'];
$order = Order::load($orderId);
$payment = Helper::getPayment($orderId, $paymentId);

if ($payment instanceof Payment) {
    $client = ClientHelper::initClient($payment);
    $confirmRequest = ClientHelper::getConfirmRequest($payment);
    $result = $client->change($confirmRequest);
    $orderState = $result->getOrderState();

    if ($orderState === Helper::PAYMENT_STATE_APPROVED) {
        $payment->setField(Helper::PAYMENT_FIELD_PS_STATUS_CODE, $orderState);
        $payment->setPaid('Y');
        $order = $payment->getOrder();
        $price = $order->getPrice();
        $paymentSum = $result->getAmount();

        if ($price == $paymentSum) {
            $order->setField('STATUS_ID', 'P');
        }

        $order->save();
    }
}

LocalRedirect($_SERVER['HTTP_REFERER']);
