<?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);
    $orderStateRequest = ClientHelper::getStatusRequest($payment);
    $result = $client->orderState($orderStateRequest);
    $orderState = $result->getOrderState();
    $payment->setField(Helper::PAYMENT_FIELD_PS_STATUS_CODE, $orderState);
    $order = $payment->getOrder();

    if ($orderState === Helper::PAYMENT_STATE_APPROVED || $orderState === Helper::PAYMENT_STATE_DELAYED) {
        $payment->setPaid('Y');
    }

    if ($orderState === Helper::PAYMENT_STATE_CANCELED) {
        $payment->setPaid('N');
        $payment->setReturn('Y');
    }

    $order->save();
}

LocalRedirect($_SERVER['HTTP_REFERER']);
