<?php

define('WITHOUT_VAT', 1);
define('VAT_0', 2);
define('VAT_10', 3);
define('VAT_20', 4);
define('VAT_110', 5);
define('VAT_120', 6);
define('VAT_5', 7);
define('VAT_7', 8);
define('VAT_105', 9);
define('VAT_107', 10);
define('VAT_22', 11);
define('VAT_122', 12);

/**
 * @return array
 */
function getTaxRate()
{
    return array(
        WITHOUT_VAT => t('Without VAT'),
        VAT_0 => t('0%'),
        VAT_5 => t('5%'),
        VAT_7 => t('7%'),
        VAT_10 => t('10%'),
        VAT_20 => t('20%'),
        VAT_22 => t('22%'),
        VAT_105 => t('Applicable rate 5/105'),
        VAT_107 => t('Applicable rate 7/107'),
        VAT_110 => t('Applicable rate 10/110'),
        VAT_120 => t('Applicable rate 20/120'),
        VAT_122 => t('Applicable rate 22/122'),
    );
}

/**
 * Генерация формы настроек модуля
 * @return array
 */
function yoomoney_api_admin_settings()
{
    global $base_url;
    $module_path = drupal_get_path('module', 'yoomoney_api');
    $pathInfo = $module_path . '/yoomoney_api.info';
    $info = drupal_parse_info_file($pathInfo);
    $shopInfo = yoomoney_api_get_shop_info();

    $isOauthTokenGotten = variable_get('yoomoney_api_access_token', false);

    yoomoney_api_admin_remove_duplicate_messages('warning');
    $form['#attached']['js'] = array(
        $module_path . '/assets/js/yoomoney_api.admin.js'
    );
    $form['#attached']['css'] = array(
        $module_path . '/assets/css/yoomoney_api.admin.css',
    );

    $form['yoomoney_api_all'] = array(
        '#type' => 'fieldset',
        '#description' => '<span class="qa-info-label">'
            . t('By starting to work with the module, you automatically accept its <a href=\'https://yoomoney.ru/doc.xml?id=527132\' target=\'_blank\'>terms of use</a>.') . '</span>',
        '#weight' => 10,
    );
    $form['yoomoney_api_all']['lbl_version'] = array(
        '#markup' => '<span class="qa-module-version">' . t('Module version: ') . $info['version'] . '</span>',
    );
    $form['yoomoney_api_all']['yoomoney_api_ip'] = array(
        '#type' => 'hidden',
        '#title' => t('Allowed IPs for callbacks'),
        '#default_value' => variable_get('yoomoney_api_ip', '0.0.0.0'),
        '#description' => t(
            'The list of IP addresses which has access to payment callbacks. One per line.<br/>0.0.0.0 means allow from all.'
        ),
    );

    $form['vertical_tabs'] = array(
        '#type' => 'vertical_tabs',
        '#weight' => 20,
    );
    $form['yoomoney_api_kassa_tab'] = array(
        '#type' => 'fieldset',
        '#title' => t('YooMoney'),
        '#group' => 'vertical_tabs',
        '#weight' => 10,
    );
    $form['yoomoney_api_kassa_tab']['lbl_setting'] = array(
        '#markup' => '<h3 class="qa-title">' . t('Store settings') . '</h3>',
    );
    $form['yoomoney_api_kassa_tab']['intro'] = array(
        '#markup' => '<span class="qa-text-info">' . t('To make the module work, you need first <a target="_blank" href="https://yookassa.ru/yooid/signup/step/phone?origin=Checkout&returnUrl=https%3A%2F%2Fyookassa.ru%2Fjoinups">sign up for YooMoney</a>') . '</span>',
    );


    $form['yoomoney_api_kassa_tab']['yoomoney_api_shop'] = array(
        '#type' => 'checkbox',
        '#title' => '<span class="qa-enable-yookassa-label">' . t('Enable payment acceptance via YooKassa') . '</span>',
        '#default_value' => variable_get('yoomoney_api_shop', 0),
        '#attributes' => array(
            'class' => array('qa-enable-yookassa-checkbox'),
        ),
    );

    $form['yoomoney_api_kassa_tab']['oauth_setting'] = array(
        '#markup' => '<h5 class="qa-oauth-setting-title">' . t('Link your website on Drupal to the YooMoney Merchant Profile') . '</h5>',
    );

    yoomoney_api_create_authorization_fields($form, $isOauthTokenGotten, $shopInfo);

    yoomoney_api_check_hide_fields($form);

    $form['yoomoney_api_kassa_tab']['yoomoney_api_paymode'] = array(
        '#markup' => '<br><span><b>' . t('The payment process: ') . '</b>'
            . t('customers will go from your store to the YooMoney page and pay using any methods you have enabled.') . '<br>'
            . t('<a target="_blank" href="https://yookassa.ru/developers/payment-acceptance/integration-scenarios/smart-payment">More about the payment scenario</a>')
            . '</span>',
    );

    /*********** Transaction data ***********/
    if (module_exists('commerce')) {
        $form['yoomoney_api_kassa_tab']['yoomoney_api_description_template'] = array(
            '#type' => 'textfield',
            '#title' => '<span class="qa-description-template-label">' . t('Transaction data') . '</span>',
            '#description' => '<span class="qa-description-template-info">' . t("Full description of the transaction that the user will see during the checkout process. You can find it in your YooKassa Merchant Profile. For example, \"Payment for order No. 72 by user@yoomoney.ru\". Limitations: no more than 128 symbols.") . '</span>',
            '#default_value' => variable_get('yoomoney_api_description_template', t('Payment for order No. %order_number%')),
            '#attributes' => array(
                'class' => array('qa-description-template-input'),
            )
        );
    }

    if (module_exists('uc_payment')) {
        $form['yoomoney_api_kassa_tab']['yoomoney_api_description_template'] = array(
            '#type' => 'textfield',
            '#title' => '<span class="qa-description-template-label">' . t('Transaction data') . '</span>',
            '#description' => '<span class="qa-description-template-info">' . t("Full description of the transaction that the user will see during the checkout process. You can find it in your YooKassa Merchant Profile. For example, \"Payment for order No. 72 by user@yoomoney.ru\". Limitations: no more than 128 symbols") . '</span>',
            '#default_value' => variable_get('yoomoney_api_description_template', t('Payment for order No. %order_id%')),
            '#size' => 60,
            '#attributes' => array(
                'class' => array('qa-description-template-input'),
            )
        );
    }

    /*********** Hold mode ***********/
    $form['yoomoney_api_kassa_tab']['yoomoney_api_enable_hold_mode'] = array(
        '#type' => 'checkbox',
        '#title' => '<span class="qa-enable-hold-label">' . t('Enable deferred payment') . '</span>',
        '#description' => '<span class="qa-enable-hold-info">' . t('If this feature is enabled, payments via cards are processed in 2 stages: the amount on customer\'s side is put on hold, and you need to confirm manually via the administrator\'s panel that it needs to be debited.') . ' <a href="https://yookassa.ru/features/" target="_blank">'.t('Learn more about Holding.').'</a> </span>',
        '#default_value' => variable_get('yoomoney_api_enable_hold_mode', 0),
        '#attributes' => array(
            'class' => array('qa-enable-hold-control'),
        )
    );

    /*********** tax edit ****************/

    if (module_exists('commerce_tax') && module_exists('commerce_tax_ui')) {
        yoomoney_api_create_send_check_message($form, $shopInfo);

        $form['yoomoney_api_kassa_tab']['yoomoney_api_send_check'] = array(
            '#type' => 'checkbox',
            '#title' => '<span class="qa-enable-receipt-label">' . t('Send data for receipts to YooMoney (54-FZ)') . '</span>',
            '#default_value' => variable_get('yoomoney_api_send_check', 0),
            '#attributes' => array(
                'class' => array('qa-enable-receipt-control'),
            )
        );

        $taxes = commerce_tax_ui_commerce_tax_rate_info();

        if ($taxes && variable_get('yoomoney_api_send_check')) {

            $show_tax_warning = false;
            $taxRatesToShow = [VAT_20, VAT_120];

            $default_tax_rate = variable_get('yoomoney_api_kassa_tax_default', YOOMONEY_API_DEFAULT_TAX_RATE_ID);
            if (in_array((int)$default_tax_rate, $taxRatesToShow)) {
                $show_tax_warning = true;
            }

            foreach ($taxes as $tax) {
                $tax_value = variable_get('yoomoney_api_kassa_tax_' . $tax['name'], YOOMONEY_API_DEFAULT_TAX_RATE_ID);
                if (in_array((int)$tax_value, $taxRatesToShow)) {
                    $show_tax_warning = true;
                    break;
                }
            }

            $form['yoomoney_api_kassa_tab'] = array(
                '#type' => 'fieldset',
                '#title' => t('YooMoney Kassa Settings'),
                '#collapsible' => TRUE,
                '#collapsed' => FALSE,
            );

            if ($show_tax_warning) {
                $form['yoomoney_api_kassa_tab']['tax_warning'] = array(
                    '#markup' => '<div class="messages warning qa-tax-warning" style="clear: both; margin-bottom: 15px;">'
                        . t('In order to comply with the Federal Law No. 54-FZ, the VAT rate and estimate rate will be changed from 20% and 20/120 to 22% and 22/122 starting from January 1, and the new rates will be applied to all new payments.<br>If you don\'t change the rates, you might get questions and fines from the Federal Tax Service, and you will have to manually correct the transactions.')
                        . '</div>',
                );
            }

            $form['yoomoney_api_kassa_tab']['lbl_yoomoney_api_kassa_tax_default'] = array(
                '#markup' => '<div> <label class="qa-tax-rate-label" style="width: 200px;float: left;padding-top: 10px;">' . t('Default tax rate') . '</label>',
            );
            $form['yoomoney_api_kassa_tab']['yoomoney_api_kassa_tax_default'] = array(
                '#type' => 'select',
                '#title_display' => false,
                '#options' => getTaxRate(),
                '#default_value' => variable_get('yoomoney_api_kassa_tax_default', YOOMONEY_API_DEFAULT_TAX_RATE_ID),
                '#attributes' => array(
                    'class' => array('qa-kassa-tax-select'),
                )
            );

            $form['yoomoney_api_kassa_tab']['lbl_yoomoney_api_kassa_tax_default_end'] = array(
                '#markup' => '</div>',
            );

            $form['yoomoney_api_kassa_tab']['lbl_wrapper_tax'] = array(
                '#markup' => '<label class="qa-tax-label">' . t('Compare the receipts') . '</label>',
            );

            $form['yoomoney_api_kassa_tab']['lbl_wrapper_tax_start'] = array(
                '#markup' => '<div>',
            );
            $form['yoomoney_api_kassa_tab']['lbl_shop_tax'] = array(
                '#markup' => '<div class="qa-shop-tax-label" style="float: left;width: 200px;">' . t('Rate at your store') . '</div>',
            );
            $form['yoomoney_api_kassa_tab']['lbl_kassa_tax'] = array(
                '#markup' => '<div class="qa-kassa-tax-label">' . t('Rate for the receipt sent to the tax service') . '</div>',
            );
            $form['yoomoney_api_kassa_tab']['lbl_wrapper_tax_end'] = array(
                '#markup' => '</div>',
            );

            foreach ($taxes as $tax) {
                $form['yoomoney_api_kassa_tab']['lbl_yoomoney_api_kassa_tax_' . $tax['name']] = array(
                    '#markup' => '<div> <label class="qa-kassa-tax-title" data-qa-kassa-tax="' . $tax['title'] . '" style="width: 200px;float: left;padding-top: 10px;">' . $tax['title'] . '</label>',
                );
                $form['yoomoney_api_kassa_tab']['yoomoney_api_kassa_tax_' . $tax['name']] = array(
                    '#type' => 'select',
                    '#title_display' => false,
                    '#options' => getTaxRate(),
                    '#default_value' => variable_get('yoomoney_api_kassa_tax_' . $tax['name'], YOOMONEY_API_DEFAULT_TAX_RATE_ID),
                    '#attributes' => array(
                        'class' => array('qa-kassa-tax-select'),
                        'data-qa-kassa-tax' => array($tax['name'])
                    )
                );

                $form['yoomoney_api_kassa_tab']['lbl_yoomoney_api_kassa_tax_' . $tax['name'] . '_end'] = array(
                    '#markup' => '</div>',
                );
            }

            $form['yoomoney_api_kassa_tab']['yoomoney_kassa_payment_mode'] = array(
                '#type' => 'select',
                '#title' => '<span class="qa-payment-mode-label">' . t('Payment method') . '</span>',
                '#options' => array(
                    'full_prepayment' => t('Full prepayment (full_prepayment)'),
                    'partial_prepayment' => t('Partial prepayment (partial_prepayment)'),
                    'advance' => t('Advance payment (advance)'),
                    'full_payment' => t('Full payment (full_payment)'),
                    'partial_payment' => t('Partial payment and loan (partial_payment)'),
                    'credit' => t('Loan (credit)'),
                    'credit_payment' => t('Loan repayment (credit_payment)'),
                ),
                '#default_value' => variable_get('yoomoney_kassa_payment_mode'),
                '#states' => array(
                    'invisible' => array(
                        ':input[name="yoomoney_send_check"]' => array('value' => '0'),
                    ),
                ),
                '#attributes' => array(
                    'class' => array('qa-payment-mode-select')
                )
            );

            $form['yoomoney_api_kassa_tab']['yoomoney_kassa_payment_subject'] = array(
                '#type' => 'select',
                '#title' => '<span class="qa-payment-subject-label">' . t('Delivery payment mode') . '</span>',
                '#options' => array(
                    'commodity' => t('Product (commodity)'),
                    'excise' => t('Excisable goods (excise)'),
                    'job' => t('Job (job)'),
                    'service' => t('Service (service)'),
                    'gambling_bet' => t('Gambling bet (gambling_bet)'),
                    'gambling_prize' => t('Gambling winnings (gambling_prize)'),
                    'lottery' => t('Lottery ticket (lottery)'),
                    'lottery_prize' => t('Lottery winnings (lottery_prize)'),
                    'intellectual_activity' => t('Intellectual property (intellectual_activity)'),
                    'payment' => t('Payment (payment)'),
                    'agent_commission' => t('Agent’s commission (agent_commission)'),
                    'composite' => t('Several subjects (composite)'),
                    'another' => t('Another (another)'),
                ),
                '#default_value' => variable_get('yoomoney_kassa_payment_subject'),
                '#states' => array(
                    'invisible' => array(
                        ':input[name="yoomoney_send_check"]' => array('value' => '0'),
                    ),
                ),
                '#attributes' => array(
                    'class' => array('qa-payment-subject-select')
                )
            );

            $form['yoomoney_api_kassa_tab']['yoomoney_kassa_delivery_payment_mode'] = array(
                '#type' => 'select',
                '#title' => '<span class="qa-delivery-payment-label">' . t('Delivery payment mode') . '</span>',
                '#options' => array(
                    'full_prepayment' => t('Full prepayment (full_prepayment)'),
                    'partial_prepayment' => t('Partial prepayment (partial_prepayment)'),
                    'advance' => t('Advance payment (advance)'),
                    'full_payment' => t('Full payment (full_payment)'),
                    'partial_payment' => t('Partial payment and loan (partial_payment)'),
                    'credit' => t('Loan (credit)'),
                    'credit_payment' => t('Loan repayment (credit_payment)'),
                ),
                '#default_value' => variable_get('yoomoney_kassa_delivery_payment_mode'),
                '#states' => array(
                    'invisible' => array(
                        ':input[name="yoomoney_send_check"]' => array('value' => '0'),
                    ),
                ),
                '#attributes' => array(
                    'class' => array('qa-delivery-payment-select')
                )
            );

            $form['yoomoney_api_kassa_tab']['yoomoney_kassa_delivery_payment_subject'] = array(
                '#type' => 'select',
                '#title' => '<span class="qa-delivery-payment-subject-label">' . t('Delivery payment subject') . '</span>',
                '#options' => array(
                    'commodity' => t('Product (commodity)'),
                    'excise' => t('Excisable goods (excise)'),
                    'job' => t('Job (job)'),
                    'service' => t('Service (service)'),
                    'gambling_bet' => t('Gambling bet (gambling_bet)'),
                    'gambling_prize' => t('Gambling winnings (gambling_prize)'),
                    'lottery' => t('Lottery ticket (lottery)'),
                    'lottery_prize' => t('Lottery winnings (lottery_prize)'),
                    'intellectual_activity' => t('Intellectual property (intellectual_activity)'),
                    'payment' => t('Payment (payment)'),
                    'agent_commission' => t('Agent’s commission (agent_commission)'),
                    'composite' => t('Several subjects (composite)'),
                    'another' => t('Another (another)'),
                ),
                '#default_value' => variable_get('yoomoney_kassa_delivery_payment_subject'),
                '#states' => array(
                    'invisible' => array(
                        ':input[name="yoomoney_send_check"]' => array('value' => '0'),
                    ),
                ),
                '#attributes' => array(
                    'class' => array('qa-delivery-payment-subject-select')
                )
            );

            $form['yoomoney_api_kassa_tab']['yoomoney_api_send_second_receipt'] = array(
                '#type' => 'checkbox',
                '#title' => '<span class="qa-second-receipt-label">' . t('Second receipt') . '</span>',
                '#default_value' => variable_get('yoomoney_api_send_second_receipt', 0),
                '#attributes' => array(
                    'class' => array('qa-second-receipt-control'),
                )
            );

            $statuses = array();

            foreach (commerce_order_state_get_title() as $name => $title) {
                foreach (commerce_order_statuses(array('state' => $name)) as $order_status) {
                    // Only include enabled statues and the current order status.
                    if (!empty($order_status['status'])) {
                        $statuses[check_plain($title)][$order_status['name']] = check_plain($order_status['title']);
                    }
                }
            }

            $form['yoomoney_api_kassa_tab']['yoomoney_api_second_receipt_status'] = array(
                '#type' => 'select',
                '#title' => '<span class="qa-second-receipt-status-label">' . t('Generate a second check when the order goes into status') . '</span>',
                '#options' => $statuses,
                '#default_value' => variable_get('yoomoney_api_second_receipt_status'),
                '#states' => array(
                    'invisible' => array(
                        ':input[name="yoomoney_send_check"]' => array('value' => '0'),
                        ':input[name="yoomoney_api_send_second_receipt"]' => array('value' => '0'),
                    ),
                ),
                '#attributes' => array(
                    'class' => array('qa-second-receipt-status-select')
                )
            );
        }
    }

    /*********** tax edit****************/

    if (module_exists('uc_taxes')) {
        yoomoney_api_create_send_check_message($form, $shopInfo);

        $form['yoomoney_api_kassa_tab']['yoomoney_api_send_check'] = array(
            '#type' => 'checkbox',
            '#title' => '<span class="qa-enable-receipt-label">' . t('Send data for receipts to YooMoney (54-FZ)') . '</span>',
            '#default_value' => variable_get('yoomoney_api_send_check', 0),
            '#attributes' => array(
                'class' => array('qa-enable-receipt-control'),
            )
        );

        $taxes = uc_taxes_rate_load();

        if ($taxes && variable_get('yoomoney_api_send_check')) {

            $show_tax_warning = false;
            $taxRatesToShow = [VAT_20, VAT_120];

            foreach ($taxes as $tax) {
                $tax_value = variable_get('yoomoney_api_kassa_tax_' . $tax->id, 1);
                if (in_array((int)$tax_value, $taxRatesToShow)) {
                    $show_tax_warning = true;
                    break;
                }
            }

            if ($show_tax_warning) {
                $form['yoomoney_api_kassa_tab']['tax_warning'] = array(
                    '#markup' => '<div class="messages warning qa-tax-warning" style="clear: both; margin-bottom: 15px;">'
                        . t('In order to comply with the Federal Law No. 54-FZ, the VAT rate and estimate rate will be changed from 20% and 20/120 to 22% and 22/122 starting from January 1, and the new rates will be applied to all new payments.<br>If you don\'t change the rates, you might get questions and fines from the Federal Tax Service, and you will have to manually correct the transactions.')
                        . '</div>',
                );
            }

            $form['yoomoney_api_kassa_tab']['lbl_wrapper_tax'] = array(
                '#markup' => '<label class="qa-tax-rate-label">' . t('Compare the receipts') . '</label>',
            );

            $form['yoomoney_api_kassa_tab']['lbl_wrapper_tax_start'] = array(
                '#markup' => '<div>',
            );
            $form['yoomoney_api_kassa_tab']['lbl_shop_tax'] = array(
                '#markup' => '<div class="qa-shop-tax-label" style="float: left;width: 200px;">' . t('Rate at your store') . '</div>',
            );
            $form['yoomoney_api_kassa_tab']['lbl_kassa_tax'] = array(
                '#markup' => '<div class="qa-kassa-tax-label">' . t('Rate for the receipt sent to the tax service') . '</div>',
            );
            $form['yoomoney_api_kassa_tab']['lbl_wrapper_tax_end'] = array(
                '#markup' => '</div>',
            );

            foreach ($taxes as $tax) {

                $form['yoomoney_api_kassa_tab']['lbl_yoomoney_api_kassa_tax_' . $tax->id] = array(
                    '#markup' => '<div> <label class="qa-kassa-tax-title" data-qa-kassa-tax="' . $tax->name . '" style="width: 200px;float: left;padding-top: 10px;">' . $tax->name . '</label>',
                );

                $form['yoomoney_api_kassa_tab']['yoomoney_api_kassa_tax_' . $tax->id] = array(
                    '#type' => 'select',
                    '#label' => false,
                    '#options' => getTaxRate(),
                    '#default_value' => variable_get('yoomoney_api_kassa_tax_' . $tax->id, 1),
                    '#description' => '',
                    '#attributes' => array(
                        'class' => array('qa-kassa-tax-select'),
                        'data-qa-kassa-tax' => array($tax->id)
                    )
                );

                $form['yoomoney_api_kassa_tab']['lbl_yoomoney_api_kassa_tax_' . $tax->id . '_end'] = array(
                    '#markup' => '</div>',
                );
            }

            $form['yoomoney_api_kassa_tab']['yoomoney_kassa_payment_mode'] = array(
                '#type' => 'select',
                '#title' => '<span class="qa-payment-mode-label">' . t('Payment method') . '</span>',
                '#options' => array(
                    'full_prepayment' => t('Full prepayment (full_prepayment)'),
                    'partial_prepayment' => t('Partial prepayment (partial_prepayment)'),
                    'advance' => t('Advance payment (advance)'),
                    'full_payment' => t('Full payment (full_payment)'),
                    'partial_payment' => t('Partial payment and loan (partial_payment)'),
                    'credit' => t('Loan (credit)'),
                    'credit_payment' => t('Loan repayment (credit_payment)'),
                ),
                '#default_value' => variable_get('yoomoney_kassa_payment_mode'),
                '#states' => array(
                    'invisible' => array(
                        ':input[name="yoomoney_send_check"]' => array('value' => '0'),
                    ),
                ),
                '#attributes' => array(
                    'class' => array('qa-payment-mode-select')
                )
            );

            $form['yoomoney_api_kassa_tab']['yoomoney_kassa_payment_subject'] = array(
                '#type' => 'select',
                '#title' => '<span class="qa-payment-subject-label">' . t('Payment subject') . '</span>',
                '#options' => array(
                    'commodity' => t('Product (commodity)'),
                    'excise' => t('Excisable goods (excise)'),
                    'job' => t('Job (job)'),
                    'service' => t('Service (service)'),
                    'gambling_bet' => t('Gambling bet (gambling_bet)'),
                    'gambling_prize' => t('Gambling winnings (gambling_prize)'),
                    'lottery' => t('Lottery ticket (lottery)'),
                    'lottery_prize' => t('Lottery winnings (lottery_prize)'),
                    'intellectual_activity' => t('Intellectual property (intellectual_activity)'),
                    'payment' => t('Payment (payment)'),
                    'agent_commission' => t('Agent’s commission (agent_commission)'),
                    'composite' => t('Several subjects (composite)'),
                    'another' => t('Another (another)'),
                ),
                '#default_value' => variable_get('yoomoney_kassa_payment_subject'),
                '#states' => array(
                    'invisible' => array(
                        ':input[name="yoomoney_send_check"]' => array('value' => '0'),
                    ),
                ),
                '#attributes' => array(
                    'class' => array('qa-payment-subject-select')
                )
            );

            $form['yoomoney_api_kassa_tab']['yoomoney_kassa_delivery_payment_mode'] = array(
                '#type' => 'select',
                '#title' => '<span class="qa-delivery-payment-label">' . t('Delivery payment mode') . '</span>',
                '#options' => array(
                    'full_prepayment' => t('Full prepayment (full_prepayment)'),
                    'partial_prepayment' => t('Partial prepayment (partial_prepayment)'),
                    'advance' => t('Advance payment (advance)'),
                    'full_payment' => t('Full payment (full_payment)'),
                    'partial_payment' => t('Partial payment and loan (partial_payment)'),
                    'credit' => t('Loan (credit)'),
                    'credit_payment' => t('Loan repayment (credit_payment)'),
                ),
                '#default_value' => variable_get('yoomoney_kassa_delivery_payment_mode'),
                '#states' => array(
                    'invisible' => array(
                        ':input[name="yoomoney_send_check"]' => array('value' => '0'),
                    ),
                ),
                '#attributes' => array(
                    'class' => array('qa-delivery-payment-select')
                )
            );

            $form['yoomoney_api_kassa_tab']['yoomoney_kassa_delivery_payment_subject'] = array(
                '#type' => 'select',
                '#title' => '<span class="qa-delivery-payment-subject-label">' . t('Delivery payment subject') . '</span>',
                '#options' => array(
                    'commodity' => t('Product (commodity)'),
                    'excise' => t('Excisable goods (excise)'),
                    'job' => t('Job (job)'),
                    'service' => t('Service (service)'),
                    'gambling_bet' => t('Gambling bet (gambling_bet)'),
                    'gambling_prize' => t('Gambling winnings (gambling_prize)'),
                    'lottery' => t('Lottery ticket (lottery)'),
                    'lottery_prize' => t('Lottery winnings (lottery_prize)'),
                    'intellectual_activity' => t('Intellectual property (intellectual_activity)'),
                    'payment' => t('Payment (payment)'),
                    'agent_commission' => t('Agent’s commission (agent_commission)'),
                    'composite' => t('Several subjects (composite)'),
                    'another' => t('Another (another)'),
                ),
                '#default_value' => variable_get('yoomoney_kassa_delivery_payment_subject'),
                '#states' => array(
                    'invisible' => array(
                        ':input[name="yoomoney_send_check"]' => array('value' => '0'),
                    ),
                ),
                '#attributes' => array(
                    'class' => array('qa-delivery-payment-subject-select')
                )
            );

            $form['yoomoney_api_kassa_tab']['yoomoney_api_send_second_receipt'] = array(
                '#type' => 'checkbox',
                '#title' => '<span class="qa-second-receipt-label">' . t('Second receipt') . '</span>',
                '#default_value' => variable_get('yoomoney_api_send_second_receipt', 0),
                '#attributes' => array(
                    'class' => array('qa-second-receipt-control'),
                )
            );

            $statuses = array();
            foreach (uc_order_status_list() as $status) {
                $statuses[$status['id']] = $status['title'];
            }

            $form['yoomoney_api_kassa_tab']['yoomoney_api_second_receipt_status'] = array(
                '#type' => 'select',
                '#title' => '<span class="qa-second-receipt-status-label">' . t('Generate a second check when the order goes into status') . '</span>',
                '#options' => $statuses,
                '#default_value' => variable_get('yoomoney_api_second_receipt_status'),
                '#states' => array(
                    'invisible' => array(
                        ':input[name="yoomoney_send_check"]' => array('value' => '0'),
                        ':input[name="yoomoney_api_send_second_receipt"]' => array('value' => '0'),
                    ),
                ),
                '#attributes' => array(
                    'class' => array('qa-second-receipt-status-select')
                )
            );
        }
    }

    /*********** tax edit****************/
    if (module_exists('commerce')) {
        $form['yoomoney_api_kassa_tab']['notifyUrl'] = array(
            '#type' => 'textfield',
            '#title' => '<span class="qa-notify-url-label">' . t('Address for notifications') . '</span>',
            '#attributes' => array(
                'disabled' => 'disabled',
                'class' => array('qa-notify-url-input')
            ),
            '#description' => t('Only required if YooKassa\'s specialists ask for it'),
            '#default_value' => url('yoomoney_api/commerce/notify', array('absolute' => true)),
        );
    }

    if (module_exists('uc_payment')) {
        $form['yoomoney_api_kassa_tab']['notifyUrl'] = array(
            '#type' => 'textfield',
            '#title' => '<span class="qa-notify-url-label">' . t('Address for notifications') . '</span>',
            '#attributes' => array(
                'disabled' => 'disabled',
                'class' => array('qa-notify-url-input')
            ),
            '#description' => t('Only required if YooKassa\'s specialists ask for it'),
            '#default_value' => url('yoomoney_api/ubercart/notify', array('absolute' => true)),
        );
    }

    $form['yoomoney_api_kassa_tab']['yoomoney_api_debug'] = array(
        '#type' => 'checkbox',
        '#title' => '<span class="qa-debug-label">' . t('Record of debugging information') . '</span>',
        '#description' => '<span class="qa-debug-info">' . t('Only required if YooKassa\'s specialists ask for it') . '</span>',
        '#default_value' => variable_get('yoomoney_api_debug', 0),
        '#attributes' => array(
            'class' => array('qa-debug-checkbox')
        )
    );

    if (variable_get('yoomoney_api_debug')) {
        $form['yoomoney_api_kassa_tab']['my_button']['#type'] = 'button';
        $form['yoomoney_api_kassa_tab']['my_button']['#value'] = t('Download the log');
        $form['yoomoney_api_kassa_tab']['my_button']['#submit'] = array('yoomoney_api_log_handler');
        $form['yoomoney_api_kassa_tab']['my_button']['#executes_submit_callback'] = true;
        $form['yoomoney_api_kassa_tab']['my_button']['#attributes'] = array('class' => array('qa-download-log-button'));
    }

    // footer settings
    $form['yoomoney_api_texts'] = array(
        '#type' => 'fieldset',
        '#title' => '<span class="qa-text-success-title">' . t('Text for success and fail payment pages') . '</span>',
        '#weight' => 40,
    );
    $success = variable_get(
        'yoomoney_api_success_text',
        array('value' => '', 'format' => '')
    );
    $form['yoomoney_api_texts']['yoomoney_api_success_text'] = array(
        '#type' => 'text_format',
        '#title' => '<span class="qa-text-success-label">' . t('Text for success page') . '</span>',
        '#default_value' => $success['value'] ? $success['value'] : '',
        '#format' => $success['format'] ? $success['format'] : '',
        '#attributes' => array(
            'class' => array('qa-text-success-input')
        )
    );
    $fail = variable_get(
        'yoomoney_api_fail_text',
        array('value' => '', 'format' => '')
    );
    $form['yoomoney_api_texts']['yoomoney_api_fail_text'] = array(
        '#type' => 'text_format',
        '#title' => '<span class="qa-text-fail-label">' . t('Text for fail page') . '</span>',
        '#default_value' => $fail['value'] ? $fail['value'] : '',
        '#format' => $fail['format'] ? $fail['format'] : '',
        '#attributes' => array(
            'class' => array('qa-text-fail-input')
        )
    );
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save configuration'),
        '#submit' => array('yoomoney_api_form_submit'),
    );

    return $form;
}

/**
 * Сохранение настроек
 * @param array $form
 * @param array $form_state
 * @return array
 */
function yoomoney_api_form_submit(&$form, &$form_state)
{
    require_once MODULE_PATH.DIRECTORY_SEPARATOR.'YooMoneyKassaLogger.php';
    $kassaLogger = new YooMoneyKassaLogger(variable_get('yoomoney_api_shop_id', 'null'));
    try {
        $kassaLogger->sendHeka(array("settings.save.init"));
        system_settings_form_submit($form, $form_state);
        $kassaLogger->sendHeka(array("settings.save.success"));
    } catch (Exception $e) {
        $kassaLogger->sendAlertLog(
            'Save settings exception',
            array('exception' => $e),
            array('settings.save.fail')
        );
    }

    return $form;
}

/**
 * Валидация полей формы настроек
 * @param array $form
 * @param array $form_state
 */
function yoomoney_api_admin_settings_validate($form, &$form_state)
{
    if ($form_state['values']['yoomoney_api_shop'] == 1) {

        $valid = true;

        if (!variable_get('yoomoney_api_access_token')) {
            if (!empty($form_state['values']['yoomoney_api_shop_id']) && !preg_match('/^\d+$/i', $form_state['values']['yoomoney_api_shop_id'])) {
                form_set_error(
                    'yoomoney_api_shop_id',
                    t('Such shopId does not exist. Please copy this parameter under your <a href=\"https://yoomoney.ru/joinups\">YooKassa\'s Merchant Profile</a> (at the top of any page)')
                );
                $valid = false;
            }

            if (!empty($form_state['values']['yoomoney_api_secret']) && !preg_match('/^test_.*|live_.*$/i', $form_state['values']['yoomoney_api_secret'])) {
                form_set_error(
                    'yoomoney_api_secret',
                    t('Such secret key does not exist. If you are sure you copied the key correctly, this means it does not work for some reason. Issue and activate the key again—under your <a href=\"https://yoomoney.ru/joinups\">Merchant Profile</a>')
                );
                $valid = false;
            }
        }

        if (
            $valid
            && !empty($form_state['values']['yoomoney_api_shop_id'])
            && !empty($form_state['values']['yoomoney_api_secret'])
            && !variable_get('yoomoney_api_access_token')
            && !preg_match('/^test_.*|live_.*$/i', $form_state['values']['yoomoney_api_secret'])
        ) {
            drupal_set_message(
                t('Looks like there\'s a mistake in the ShopID or secret key. Please change the store using the button below to load the correct sign-in data into the form automatically.'),
                'error'
            );
            form_set_error('yoomoney_api_shop_id', '');
            form_set_error('yoomoney_api_secret', '');
        }
    }
}

/**
 * Запись и скачивание лога модуля
 *
 * @return void
 */
function yoomoney_api_log_handler()
{
    $path = variable_get('file_public_path', conf_path() . '/files');
    $filePath = $path . '/ym-checkout-debug.log';
    $file = fopen($filePath, 'r');
    $file_size = filesize($filePath);

    header("Expires: 0");
    header("Cache-Control: no-cache, no-store, must-revalidate");
    header('Cache-Control: pre-check=0, post-check=0, max-age=0', false);
    header("Pragma: no-cache");
    header("Content-Disposition:attachment; filename=debug.log");
    header("Content-Type: application/force-download");
    while (!feof($file)) {
        $buffer = fread($file, 2048);
        echo $buffer;
        flush();
    }
    fclose($file);
    die();
}

/**
 * Удаление повторяющихся сообщений
 *
 * @param string $type
 * @return void
 */
function yoomoney_api_admin_remove_duplicate_messages($type)
{
    $stack = array();
    if (isset($_SESSION['messages'][$type])) {
        foreach ($_SESSION['messages'][$type] as $k => $msg) {
            if (in_array($msg, $stack)) {
                // Message is already set - remove it
                unset($_SESSION['messages'][$type][$k]);
            } else {
                // Add message to stack
                $stack[] = $msg;
            }
        }
    }
}

/**
 * Создание полей до и после прохождения oauth авторизации
 *
 * @param array $form
 * @param string $isOauthTokenGotten
 * @param array $shopInfo
 * @return array
 */
function yoomoney_api_create_authorization_fields(&$form, $isOauthTokenGotten, $shopInfo)
{
    $form['yoomoney_api_kassa_tab']['wrapper_begin'] = array(
        '#markup' => '<div class="inline-oauth qa-oauth-info">',
    );

    $form['yoomoney_api_kassa_tab']['wrapper_left_begin'] = array(
        '#markup' => '<div style="width: 50%">',
    );

    $form['yoomoney_api_kassa_tab']['oauth_tab']['wrapper_begin'] = array(
        '#markup' => t('<div class="oauth-tab connect-oauth" style="display: @display">', array('@display' => $isOauthTokenGotten ? "block" : "none")),
    );

    yoomoney_api_create_oauth_error_and_fields($form, $shopInfo, $isOauthTokenGotten);

    $form['yoomoney_api_kassa_tab']['oauth_tab']['wrapper_end'] = array(
        '#markup' => '</div>',
    );

    $form['yoomoney_api_kassa_tab']['shop_tab']['wrapper_begin'] = array(
        '#markup' => t('<div class="oauth-tab connect-shop" style="display: @display">', array('@display' => $isOauthTokenGotten ? "none" : "block")),
    );

    yoomoney_api_create_shop_error_and_fields($form, $shopInfo, $isOauthTokenGotten);

    $form['yoomoney_api_kassa_tab']['shop_tab']['wrapper_end'] = array(
        '#markup' => '</div>',
    );

    if (isset($shopInfo['test']) && $shopInfo['test']) {
        $form['yoomoney_api_kassa_tab']['test_shop_text'] = array(
            '#markup' => '<div class="field_oauth" style="margin-top: 18px;"><strong>' . t('To switch from the test store to the real store, click "Switch store"') . '</strong><br> '
                . t('In the pop-up window, sign in to your account, give YooMoney access, and select the required store.') . '</div>',
        );
    }

    $buttonConfig = yoomoney_api_button_config($shopInfo);

    $form['yoomoney_api_kassa_tab']['change_shop'] = array(
        '#prefix' => t('<button class="btn_oauth_connect @class">@text</button>',
            array(
                '@text' => $buttonConfig['text'],
                '@class' => $buttonConfig['qa']
            )
        )
    );

    $form['yoomoney_api_kassa_tab']['wrapper_left_end'] = array(
        '#markup' => '</div>',
    );

    if (!$isOauthTokenGotten && $shopInfo) {
        $form['yoomoney_api_kassa_tab']['wrapper_right_begin'] = array(
            '#markup' => '<div style="width: 50%" class="qa-text-info">',
        );

        $form['yoomoney_api_kassa_tab']['wrapper_text'] = array(
            '#markup' => '<strong>' . t('Where to find the ShopID and secret key') . '</strong>
                  <div>' . t('The sign-in data will be automatically loaded here from the Merchant Profile. Click ') . '<strong>' . t('Change store:') . '</strong></div>
                  <div>' . t('— sign in to YooMoney in the pop-up window,') . '</div><div>' . t('— allow Drupal to access your data') . '</div>',
        );

        $form['yoomoney_api_kassa_tab']['wrapper_right_end'] = array(
            '#markup' => '</div>',
        );
    }

    $form['yoomoney_api_kassa_tab']['wrapper_end'] = array(
        '#markup' => '</div>',
    );

    return $form;
}

/**
 * Проверка и сокрытие ненужных полей
 *
 * @param array $form
 * @return void
 */
function yoomoney_api_check_hide_fields(&$form)
{
    if (!variable_get('yoomoney_api_shop_id', '') && !variable_get('yoomoney_api_secret', '')) {
        hide($form['yoomoney_api_kassa_tab']['shop_tab']['yoomoney_api_shop_id']);
        hide($form['yoomoney_api_kassa_tab']['shop_tab']['yoomoney_api_secret']);
    }
}

/**
 * Генерация поля с ошибкой или данных магазина после oauth
 *
 * @param array $form
 * @param array $shopInfo
 * @param bool $isOauthTokenGotten
 * @return array
 */
function yoomoney_api_create_oauth_error_and_fields(&$form, $shopInfo, $isOauthTokenGotten)
{
    if (!$shopInfo && $isOauthTokenGotten) {
        yoomoney_api_create_error($form, 'oauth_tab');
    }

    if (isset($shopInfo['test'], $shopInfo['fiscalization_enabled'])) {
        $form['yoomoney_api_kassa_tab']['oauth_tab']['wrapper_oauth_info_begin'] = array(
            '#markup' => '<div class="oauth-info">',
        );

        $form['yoomoney_api_kassa_tab']['oauth_tab']['check_shop'] = array(
            '#markup' => t('<div class="field_oauth test qa-shop-type" data-qa-shop-type="@data-qa">@shop</div>',
                array(
                    '@shop' => $shopInfo['test'] ? t('Test store') : t('Real store'),
                    '@data-qa' => $shopInfo['test'] ? 'test' : 'prod'
                )
            )
        );

        $form['yoomoney_api_kassa_tab']['oauth_tab']['shop_id'] = array(
            '#markup' => t('<div class="field_oauth shop-id qa-shop-id" data-qa-shop-id="@shopId">Shop ID: @shopId</div>', array('@shopId' => variable_get('yoomoney_api_shop_id', '') ?: '')),
        );

        $form['yoomoney_api_kassa_tab']['oauth_tab']['wrapper_oauth_info_end'] = array(
            '#markup' => '</div>',
        );
    }

    return $form;
}

/**
 * Генерация поля с ошибкой или данных магазина после
 * авторизации по shopId и секретному ключу
 *
 * @param array $form
 * @param array $shopInfo
 * @param bool $isOauthTokenGotten
 * @return array
 */
function yoomoney_api_create_shop_error_and_fields(&$form, $shopInfo, $isOauthTokenGotten)
{
    if (
        !$shopInfo
        && variable_get('yoomoney_api_shop_id', '')
        && variable_get('yoomoney_api_secret', '')
    ) {
        yoomoney_api_create_error($form, 'shop_tab');
    }

    if ($shopInfo && !$isOauthTokenGotten) {
        $form['yoomoney_api_kassa_tab']['shop_tab']['yoomoney_api_shop_id'] = array(
            '#type' => 'textfield',
            '#title' => t('shopId'),
            '#description' => t('Copy shopId from your YooKassa\'s Merchant Profile'),
            '#default_value' => variable_get('yoomoney_api_shop_id', ''),
            '#size' => 60,
        );
        $form['yoomoney_api_kassa_tab']['shop_tab']['yoomoney_api_secret'] = array(
            '#type' => 'textfield',
            '#title' => t('Secret key'),
            '#description' => t(
                'Issue and activate a secret key under your YooKassa\'s Merchant Profile. Then copy it here.'
            ),
            '#default_value' => variable_get('yoomoney_api_secret', ''),
            '#size' => 60,
        );
    }

    return $form;
}

/**
 * Проверка на подключение и получение информации о магазине
 *
 * @return array|void|null
 */
function yoomoney_api_get_shop_info()
{
    try {
        $apiClient = YooMoneyClientFactory::getYooKassaClient();
        $shopInfo = $apiClient->me();
    } catch (Exception $e) {
        YooMoneyLogger::error('Get shop info error: ' . $e->getMessage());
        return;
    }

    return $shopInfo;
}

/**
 * Вывод текста и qa селектора на кнопке
 *
 * @param array $shopInfo
 * @return array
 */
function yoomoney_api_button_config($shopInfo)
{
    if (yoomoney_api_is_authorization()) {
        $text = t('Change store');
        $qa = 'qa-change-shop-button';
    }

    if (!$shopInfo && yoomoney_api_is_authorization()) {
        $text = t('Connect store to YooMoney again');
        $qa = 'qa-yookassa-entrance';
    }

    return array(
        'text' => isset($text) ? $text : t('Connect your store'),
        'qa' => isset($qa) ? $qa : 'qa-connect-shop-button'
    );
}

/**
 * Генерация сообщения об ошибке
 *
 * @param array $form
 * @param string $tabName
 * @return array
 */
function yoomoney_api_create_error(&$form, $tabName)
{
    $form['yoomoney_api_kassa_tab'][$tabName]['wrapper_text_error'] = array(
        '#markup' => '<div class="oauth-error error-token"><h5>'
            . t('Couldn\'t link the website to your Merchant Profile') . '</h5> '
            . t('Connect your store to YooMoney again or ') . '<a href="' . $GLOBALS['base_url'] . '/admin/config/development/performance' . '" target="_blank">'
            . t('clear cache.') . '</a>'
            . t(' If it doesn\'t work, contact tech support.') . '</div>',
    );

    return $form;
}

/**
 * Проверка, есть ли данные по одной из авторизаций
 *
 * @return bool
 */
function yoomoney_api_is_authorization()
{
    return variable_get('yoomoney_api_access_token', false) || (variable_get('yoomoney_api_shop_id', false) && variable_get('yoomoney_api_secret', false));
}

/**
 * Проверка на включенность фискализации со стороны магазина и модуля
 * и вывод сообщения о необходимости включения, если требуется
 *
 * @param array $form
 * @param array|null $shopInfo
 * @return array|void
 */
function yoomoney_api_create_send_check_message(&$form, $shopInfo)
{
    if (!$shopInfo) {
        return;
    }

    if (
        isset($shopInfo['fiscalization_enabled'])
        && $shopInfo['fiscalization_enabled']
        && !variable_get('yoomoney_api_send_check')
    ) {
        $form['yoomoney_api_kassa_tab']['lbl_yoomoney_api_send_check_text'] = array(
            '#markup' => '<div><strong>' . t('To activate your online sales register, enable sending data for receipts to YooMoney') . '</strong></div>
            <strong>' . t('Important: ') . '</strong>' . t('if you selected not to link the payment to the receipt, then you don\'t need to enable this feature.'),
        );
    }

    return $form;
}
