<?php

namespace Assist\Pay;

use Bitrix\Main\Diag\FileLogger;
use Bitrix\Sale\Order;
use Bitrix\Sale\Payment;
use COption;

class Helper
{
    public const MODULE_ID = 'assist.pay';

    public const DEFAULT_API_URL = 'https://payments.paysecure.ru';
    public const TEST_API_URL = 'https://payments.demo.paysecure.ru';
    public const LOG_PATH = '/bitrix/modules/assist.pay/assist.log';
    public const DEFAULT_TEST_MODE = 'N';
    public const DEFAULT_RECURRENT_PERIOD = '30';
    public const DEFAULT_RECURRENT_MAX_DATE_FROM_CURRENT_DAY = '+1 year';

    public const PAYMENT_STATE_APPROVED = 'Approved';
    public const PAYMENT_STATE_CANCELED = 'Canceled';
    public const PAYMENT_STATE_DELAYED = 'Delayed';

    public const DELIVERY_SELF_DELIVERY_NAME = 'Самовывоз';
    public const DELIVERY_WITHOUT_DELIVERY_NAME = 'Без доставки';

    public const TAX_RATE_NO_VAT = 'novat';
    public const TAX_RATE_VAT_0 = 'vat0';
    public const TAX_RATE_VAT_10 = 'vat10';
    public const TAX_RATE_VAT_20 = 'vat20';
    public const TAX_RATE_VAT_110 = 'vat110';
    public const TAX_RATE_VAT_120 = 'vat120';

    public const TAX_SYSTEM_GENERAL = 0;
    public const TAX_SYSTEM_SIMPLIFIED_INCOME = 1;
    public const TAX_SYSTEM_SIMPLIFIED_INCOME_LESS_EXPENSE = 2;
    public const TAX_SYSTEM_SINGLE_IMPUTED_INCOME_TAX = 3;
    public const TAX_SYSTEM_SINGLE_AGRICULTURAL_TAX = 4;
    public const TAX_SYSTEM_PATENT_TAX_SYSTEM = 5;

    public const CALCULATION_METHOD_FULL_PREPAYMENT = 1;
    public const CALCULATION_METHOD_PREPAYMENT = 2;
    public const CALCULATION_METHOD_ADVANCE = 3;
    public const CALCULATION_METHOD_FULL_CALCULATION = 4;
    public const CALCULATION_METHOD_PARTIAL_PAYMENT_AND_CREDIT = 5;
    public const CALCULATION_METHOD_CREDIT_TRANSFER = 6;
    public const CALCULATION_METHOD_CREDIT_PAYMENT = 7;

    public const ITEM_ATTRIBUTE_PRODUCT = 1;
    public const ITEM_ATTRIBUTE_EXCISABLE_GOODS = 2;
    public const ITEM_ATTRIBUTE_WORK = 3;
    public const ITEM_ATTRIBUTE_SERVICE = 4;
    public const ITEM_ATTRIBUTE_GAMBLING_BET = 5;
    public const ITEM_ATTRIBUTE_GAMBLING_WINNING = 6;
    public const ITEM_ATTRIBUTE_LOTTERY_TICKET_OR_WAGER = 7;
    public const ITEM_ATTRIBUTE_LOTTERY_WINNING = 8;
    public const ITEM_ATTRIBUTE_PROVISION_RID = 9;
    public const ITEM_ATTRIBUTE_PAYMENT = 10;
    public const ITEM_ATTRIBUTE_AGENCY_FEE = 11;
    public const ITEM_ATTRIBUTE_COMPONENT_SUBJECT_OF_CALCULATION = 12;
    public const ITEM_ATTRIBUTE_OTHER_SUBJECT_OF_CALCULATION = 13;
    public const ITEM_ATTRIBUTE_PROPERTY_LAW = 14;
    public const ITEM_ATTRIBUTE_NONOPERATING_INCOME = 15;
    public const ITEM_ATTRIBUTE_INSURANCE_PREMIUMS = 16;
    public const ITEM_ATTRIBUTE_TRADE_TAX = 17;
    public const ITEM_ATTRIBUTE_RESORT_TAX = 18;
    public const ITEM_ATTRIBUTE_BAIL = 19;
    public const ITEM_ATTRIBUTE_EXPENDITURE = 20;
    public const ITEM_ATTRIBUTE_CONTRIBUTIONS_COMPULSORY_PENSION_INSURANCE_IE = 21;
    public const ITEM_ATTRIBUTE_CONTRIBUTIONS_COMPULSORY_PENSION_INSURANCE = 22;
    public const ITEM_ATTRIBUTE_CONTRIBUTIONS_COMPULSORY_MEDICAL_INSURANCE_IE = 23;
    public const ITEM_ATTRIBUTE_CONTRIBUTIONS_COMPULSORY_MEDICAL_INSURANCE = 24;
    public const ITEM_ATTRIBUTE_CONTRIBUTIONS_COMPULSORY_SOCIAL_INSURANCE = 25;
    public const ITEM_ATTRIBUTE_CASINO_PAYMENT = 26;
    public const ITEM_ATTRIBUTE_CASH_DISBURSEMENT = 27;
    public const ITEM_ATTRIBUTE_ATNM = 30;
    public const ITEM_ATTRIBUTE_ATM = 31;
    public const ITEM_ATTRIBUTE_TNM = 32;
    public const ITEM_ATTRIBUTE_TM = 33;

    public const C_OPTION_IS_LOGS_ENABLED_NAME = 'isLogsEnabled';

    public const PS_OPTION_PREPARE_ONLINE_CHEQUE = 'ASSIST_PREPARE_ONLINE_CHEQUE';
    public const PS_OPTION_SEND_CHEQUE_WITH_CONFIRM = 'ASSIST_SEND_CHEQUE_WITH_CONFIRM';
    public const PS_OPTION_ORDER_STATE_AFTER_PAYMENT_WITH_CONFIRM = 'ASSIST_ORDER_STATE_AFTER_PAYMENT_WITH_CONFIRM';
    public const PS_OPTION_TEST_MODE = 'ASSIST_TEST_MODE';
    public const PS_OPTION_MERCHANT_ID = 'ASSIST_MERCHANT_ID';
    public const PS_OPTION_LOGIN = 'ASSIST_LOGIN';
    public const PS_OPTION_PASSWORD = 'ASSIST_PASSWORD';
    public const PS_OPTION_API_URL = 'ASSIST_API_URL';
    public const PS_OPTION_SECRET = 'ASSIST_SECRET';
    public const PS_OPTION_SUCCESS_PAYMENT_URL = 'ASSIST_SUCCESS_PAYMENT_URL';
    public const PS_OPTION_ERROR_PAYMENT_URL = 'ASSIST_ERROR_PAYMENT_URL';
    public const PS_OPTION_RECURRENT_PAYMENT = 'ASSIST_RECURRENT_PAYMENT';
    public const PS_OPTION_SAVE_CARD_DATA = 'ASSIST_SAVE_CARD_DATA';
    public const PS_OPTION_ORDER_CONFIRMATION = 'ASSIST_ORDER_CONFIRMATION';
    public const PS_OPTION_AUTO_ORDER_CONFIRMATION = 'ASSIST_AUTO_ORDER_CONFIRMATION';
    public const PS_OPTION_PAYMENT_TYPE_CARD = 'ASSIST_PAYMENT_TYPE_CARD';
    public const PS_OPTION_PAYMENT_TYPE_UMONEY = 'ASSIST_PAYMENT_TYPE_UMONEY';
    public const PS_OPTION_PAYMENT_TYPE_WEBMONEY = 'ASSIST_PAYMENT_TYPE_WEBMONEY';
    public const PS_OPTION_PAYMENT_TYPE_QIWI = 'ASSIST_PAYMENT_TYPE_QIWI';
    public const PS_OPTION_PAYMENT_TYPE_APPLE_PAY = 'ASSIST_PAYMENT_TYPE_APPLE_PAY';
    public const PS_OPTION_PAYMENT_TYPE_GOOGLE_PAY = 'ASSIST_PAYMENT_TYPE_GOOGLE_PAY';
    public const PS_OPTION_PAYMENT_TYPE_MIR_PAY = 'ASSIST_PAYMENT_TYPE_MIR_PAY';
    public const PS_OPTION_PAYMENT_TYPE_SAMSUNG_PAY = 'ASSIST_PAYMENT_TYPE_SAMSUNG_PAY';
    public const PS_OPTION_PAYMENT_TYPE_SPB = 'ASSIST_PAYMENT_TYPE_SPB';
    public const PS_OPTION_PAYMENT_TYPE_ERIP = 'ASSIST_PAYMENT_TYPE_ERIP';
    public const PS_OPTION_TAX_RATE = 'ASSIST_TAX_RATE';
    public const PS_OPTION_TAX_RATE_FROM_PRODUCT_SETTINGS = 'ASSIST_TAX_RATE_FROM_PRODUCT_SETTINGS';
    public const PS_OPTION_TAX_SYSTEM = 'ASSIST_TAX_SYSTEM';
    public const PS_OPTION_PAYMENT_METHOD = 'ASSIST_PAYMENT_METHOD';
    public const PS_OPTION_SUBJECT_FEATURE = 'ASSIST_SUBJECT_FEATURE';

    public const API_PARAM_BILL_NUMBER = 'billnumber';
    public const API_PARAM_ORDER_NUMBER = 'ordernumber';
    public const API_PARAM_ORDER_STATE = 'orderstate';
    public const API_PARAM_CUSTOMER_MESSAGE = 'customermessage';
    public const API_PARAM_SIGNATURE = 'signature';
    public const API_PARAM_CHECKVALUE = 'checkvalue';
    public const API_PARAM_AMOUNT = 'amount';
    public const API_PARAM_CURRENCY = 'currency';

    public const API_PARAM_VALUE_RECURRENT_PAYMENT_ENABLED = 1;
    public const API_PARAM_VALUE_DELAY_ENABLED = 1;

    public const PAYMENT_FIELD_PS_INVOICE_ID = 'PS_INVOICE_ID';
    public const PAYMENT_FIELD_PS_STATUS = 'PS_STATUS';
    public const PAYMENT_FIELD_PS_STATUS_CODE = 'PS_STATUS_CODE';
    public const PAYMENT_FIELD_PS_STATUS_MESSAGE = 'PS_STATUS_MESSAGE';
    public const PAYMENT_FIELD_PS_RESPONSE_DATE = 'PS_RESPONSE_DATE';
    public const PAYMENT_FIELD_PS_SUM = 'PS_SUM';
    public const PAYMENT_FIELD_PS_CURRENCY = 'PS_CURRENCY';
    public const PAYMENT_FIELD_PS_STATUS_DESCRIPTION = 'PS_STATUS_DESCRIPTION';
    public const PAYMENT_FIELD_PAY_SYSTEM_ID = 'PAY_SYSTEM_ID';
    public const PAYMENT_FIELD_CURRENCY = 'CURRENCY';
    public const PAYMENT_FIELD_STATUS_MESSAGE = 'STATUS_MESSAGE';

    public const ORDER_FIELD_ACCOUNT_NUMBER = 'ACCOUNT_NUMBER';

    public const BASKET_FIELD_ITEM_NAME = 'NAME';

    private const BITRIX_NO_VAT_VALUE = null;
    private const BITRIX_VAT_0_VALUE = 0.0;
    private const BITRIX_VAT_10_VALUE = 10.0;
    private const BITRIX_VAT_20_VALUE = 20.0;

    /**
     * @param int $orderId
     * @param int $paymentId
     * @return Payment|null
     */
    public static function getPayment(int $orderId, int $paymentId): ?Payment
    {
        try {
            $order = Order::load($orderId);
            $payments = $order->getPaymentCollection();

            foreach ($payments as $payment) {
                if ($payment->getId() == $paymentId) {
                    return $payment;
                }
            }
        } catch (\Exception $exception) {
            return null;
        }

        return null;
    }

    /**
     * @param float|null $bitrixTaxValue
     * @return string|false
     */
    public static function getTaxRateFor(?float $bitrixTaxValue): string|false
    {
        return match ($bitrixTaxValue) {
            self::BITRIX_NO_VAT_VALUE => self::TAX_RATE_NO_VAT,
            self::BITRIX_VAT_0_VALUE => self::TAX_RATE_VAT_0,
            self::BITRIX_VAT_10_VALUE => self::TAX_RATE_VAT_10,
            self::BITRIX_VAT_20_VALUE => self::TAX_RATE_VAT_20,
            default => false
        };
    }

    /**
     * @param Payment $payment
     * @return bool
     */
    public static function isPaymentDelayed(Payment $payment): bool
    {
        return $payment->getField(self::PAYMENT_FIELD_PS_STATUS_CODE) === self::PAYMENT_STATE_DELAYED;
    }

    /**
     * @return bool
     */
    public static function isLogsEnabled(): bool
    {
        return COption::getOptionString(self::MODULE_ID, self::C_OPTION_IS_LOGS_ENABLED_NAME) === 'Y';
    }

    /**
     * @return FileLogger
     */
    public static function initLogger(): FileLogger
    {
        $loggerPath = $_SERVER['DOCUMENT_ROOT'] . Helper::LOG_PATH;
        $logger = new FileLogger($loggerPath);
        $logFormater = new LogFormatter();
        $logger->setFormatter($logFormater);

        return $logger;
    }
}
