<?php

namespace Assist\Pay\Events;

use Assist\Exceptions\BadRequestException;
use Assist\Exceptions\ForbiddenException;
use Assist\Exceptions\HttpException;
use Assist\Exceptions\InternalServerErrorException;
use Assist\Exceptions\RequiredParameterDoesNotExistException;
use Assist\Exceptions\UnauthorizedException;
use Assist\Pay\ClientHelper;
use Assist\Pay\Helper;
use Bitrix\Main\ArgumentException;
use Bitrix\Main\ArgumentNullException;
use Bitrix\Sale\BusinessValue;
use GuzzleHttp\Exception\GuzzleException;

class SaleEvent
{
    /**
     * @param $event
     * @return void
     * @throws BadRequestException
     * @throws ForbiddenException
     * @throws HttpException
     * @throws InternalServerErrorException
     * @throws RequiredParameterDoesNotExistException
     * @throws UnauthorizedException
     * @throws ArgumentException
     * @throws ArgumentNullException
     * @throws GuzzleException
     */
    public static function confirmOrderPayment($event): void
    {
        $payment = $event->getParameter("ENTITY");
        $paySystem = $payment->getPaySystem();

        $isAutoConfirmPaymentEnabled = BusinessValue::get(Helper::PS_OPTION_AUTO_ORDER_CONFIRMATION, $paySystem->getConsumerName()) === 'Y';

        if(!$isAutoConfirmPaymentEnabled) {
            return;
        }

        $oldValues = $event->getParameter("VALUES");
        $paymentState = $payment->getField(Helper::PAYMENT_FIELD_PS_STATUS_CODE);
        $isPaid = $payment->isPaid();

        if ($paymentState === Helper::PAYMENT_STATE_DELAYED && $oldValues['PAID'] === 'N' && $isPaid) {
            $client = ClientHelper::initClient($payment);
            $confirmRequest = ClientHelper::getConfirmRequest($payment);
            $client->change($confirmRequest);
        }
    }
}
