<?php
/**
 * 2007-2019 PrestaShop SA and Contributors.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/AFL-3.0
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <contact@prestashop.com>
 * @copyright 2007-2019 PrestaShop SA and Contributors
 * @license   https://opensource.org/licenses/AFL-3.0  Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of PrestaShop SA
 */

namespace Sibs;

class SibsPaymentCore
{
    protected static $ackReturnCodes = ['000'];

    // CHECKOUT URLS

    private static function getCheckoutUrl($serverMode)
    {
        $environment_file   = \Sibs::getEnvironmentConfig();
        $checkout_endpoints = $environment_file['checkout_endpoints'];

        return $checkout_endpoints[$serverMode];
    }

    // BACKOFFICE URLS

    private static function getServerToServerUrl($serverMode)
    {
        $environment_file      = \Sibs::getEnvironmentConfig();
        $back_office_endpoints = $environment_file['back_office_endpoints'];

        return $back_office_endpoints[$serverMode];
    }

    private static function getPaymentUrl($serverMode, $referenceId)
    {
        return self::getServerToServerUrl($serverMode) . "/{$referenceId}";
    }

    private static function getPaymentStatusUrl($serverMode, $referenceId)
    {
        return self::getPaymentUrl($serverMode, $referenceId) . '/status';
    }

    private static function getCaptureUrl($serverMode, $referenceId)
    {
        return self::getPaymentUrl($serverMode, $referenceId) . '/capture';
    }

    private static function getRefundUrl($serverMode, $referenceId)
    {
        return self::getPaymentUrl($serverMode, $referenceId) . '/refund';
    }

    private static function getCancellationUrl($serverMode, $referenceId)
    {
        return self::getPaymentUrl($serverMode, $referenceId) . '/cancellation';
    }

    /**
     * Sets the ssl CURLOPT_SSL_VERIFYPEER.
     *
     * @param $ch
     * @param string $serverMode The server mode
     */
    public static function setSSLVerifyPeer($ch, $serverMode)
    {
        $verify_peer = true;

        if ($serverMode !== 'LIVE') {
            $verify_peer = false;
        }

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_peer);
        SibsLog::info('verify_peer: ' . var_export($verify_peer, true));
    }

    /**
     * Sets the Header.
     *
     * @param $ch
     * @param string
     */
    public static function setHeaders($ch, $format, $token)
    {
        $headers = [
            "Content-type: application/{$format};charset=UTF-8",
        ];

        if (! empty($token)) {
            $clientID = \Configuration::get('SIBS_GENERAL_CLIENTID');
            SibsLog::info("clientID: $clientID");

            $headers = array_merge_recursive($headers, [
                "Authorization: Bearer $token",
                "X-IBM-Client-ID: $clientID",
            ]);
        }

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        SibsLog::info('headers: ' . print_r($headers, true));
    }

    /**
     * Sets the Body.
     *
     * @param $ch
     * @param string $type
     * @param string $postFields
     */
    public static function setBody($ch, $type = 'GET', $postFields = '')
    {
        switch($type) {
            case 'POST':
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));
            default:
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
        }

        SibsLog::info("type: $type");
        SibsLog::info('postFields: ' . json_encode($postFields));
    }

    /**
     * get Curl error identifier translation.
     *
     * @param CurlHandle   $ch
     *
     * @return string
     */
    private static function getCurlErrorIdentifier($ch)
    {
        $pluginErrorIdentifier = [
            '60' => 'ERROR_MERCHANT_SSL_CERTIFICATE',
        ];

        $errorMessages = array_key_exists(curl_errno($ch), $pluginErrorIdentifier) ?
            $pluginErrorIdentifier[curl_errno($ch)] :
            curl_error($ch);

        return $errorMessages;
    }

    /**
     * Get a response from the gateway.
     *
     * @param string      $url
     * @param string      $serverMode
     * @param string      $type
     * @param string      $postFields
     * @param string      $format
     * @param null|string $token
     *
     * @return array
     */
    public static function getResponseData($url, $serverMode, $type = 'GET', $postFields = '', $format = 'text/plain', $token = null)
    {
        SibsLog::info('getResponseData()');

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        SibsLog::info("url: $url");

        self::setSSLVerifyPeer($ch, $serverMode);
        self::setHeaders($ch, $format, $token);
        self::setBody($ch, $type, $postFields);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $responseBody = curl_exec($ch);

        if (curl_errno($ch)) {
            $curlResponse = [
                'response' => self::getCurlErrorIdentifier($ch),
                'is_valid' => false,
            ];
        } else {
            $jsonResponse = json_decode($responseBody, true);
            $curlResponse = [
                'response' => ! empty($jsonResponse) ? $jsonResponse : $responseBody,
                'is_valid' => true,
            ];
        }
        curl_close($ch);

        SibsLog::info('curlResponse: ' . json_encode($curlResponse));

        return $curlResponse;
    }

    /**
     * OPP Post Parameter.
     */
    private static function getCredentialParameter($transactionData)
    {
        $parameters            = [];
        $parameters['channel'] = $transactionData['channel_id'];

        // test mode parameters (true)
        if (! empty($transactionData['test_mode'])) {
            $parameters['testMode'] = $transactionData['test_mode'];
        }

        return $parameters;
    }

    public static function setNumberFormat($number)
    {
        return number_format(str_replace(',', '.', $number), 2, '.', '');
    }

    public static function getCheckoutParameter($transactionData, $lang = 'en')
    {
        define('DATE_FORMAT', 'Y-m-d\TH:i:s.vP');

        $now = new \DateTime();

        $terminalID            = (int) \Configuration::get('SIBS_GENERAL_TERMINALID');
        $credentials           = self::getCredentialParameter($transactionData);
        $paymentType           = self::sibs_spg_get_payment_type($transactionData['payment_type']);
        $paymentMethod         = self::sibs_get_payment_method_for_spg($transactionData['payment_method']);
        $tansactionDescription = "Transaction for order number {$transactionData['id_transaction']} terminalId $terminalID";

        $parameters = [
            'merchant' => [
                'terminalId'             => $terminalID,
                'channel'                => $credentials['channel'],
                'merchantTransactionId'  => $transactionData['id_transaction'],
                'transactionDescription' => $tansactionDescription,
                'shopURL'                => _PS_BASE_URL_ . __PS_BASE_URI__,
            ],
            'transaction' => [
                'transactionTimestamp' => $now->format(DATE_FORMAT),
                'description'          => $tansactionDescription,
                'moto'                 => false,
                'paymentType'          => $paymentType,
                'paymentMethod'        => $paymentMethod,
                'amount'               => [
                    'value'    => floatval(self::setNumberFormat($transactionData['amount'])),
                    'currency' => $transactionData['currency'],
                ],
            ],
            'customer' => [
                'customerInfo' => [
                    'customerName'     => $transactionData['customer']['first_name'] . ' ' . $transactionData['customer']['last_name'],
                    'customerEmail'    => $transactionData['customer']['email'],
                    'customerLanguage' => $lang,
                    'shippingAddress'  => [
                        'street1'  => $transactionData['shipping']['street'],
                        'city'     => $transactionData['shipping']['city'],
                        'postcode' => $transactionData['shipping']['zip'],
                        'country'  => $transactionData['shipping']['country_code'],
                    ],
                    'billingAddress' => [
                        'street1'  => $transactionData['billing']['street'],
                        'city'     => $transactionData['billing']['city'],
                        'postcode' => $transactionData['billing']['zip'],
                        'country'  => $transactionData['billing']['country_code'],
                    ],
                ],
            ],
            'info' => [
                'deviceInfo' => [
                    'applicationName'    => 'prestashop',
                    'applicationVersion' => '1.7',
                ],
            ],
        ];

        if (in_array(SibsConstants::PAYMENT_METHOD_PAY_BY_LINK, $paymentMethod)) {
            $parameters['transaction'] = array_merge_recursive($parameters['transaction'], self::getCheckoutParameterPayByLink($now));
        }

        if (in_array(SibsConstants::PAYMENT_METHOD_CARD, $paymentMethod)) {
            $parameters = array_merge_recursive($parameters, self::getCheckoutParameterOneclick());
        }

        return $parameters;
    }

    public static function getCheckoutParameterPayByLink($now)
    {
        $paybylinkParameters = [];

        if (! is_null(\Configuration::get('SIBS_PAY_BY_LINK_EXPIRATION_PAYMENT_VALUE'))) {
            $varPtmntTime           = '+' . \Configuration::get('SIBS_PAY_BY_LINK_EXPIRATION_PAYMENT_VALUE');
            $varPtmntTimeTypeOffset = \Configuration::get('SIBS_PAY_BY_LINK_EXPIRATION_PAYMENT_TYPE');

            $abs_number         = abs(intval($varPtmntTime));
            $varPtmntTimeOffset = "+$abs_number $varPtmntTimeTypeOffset";

            $now->modify($varPtmntTimeOffset);
        }

        $paybylinkParameters = [
            'payByLink' => [
                'expirationDateTime'     => $now->format(DATE_FORMAT),
                'linkExpirationDateTime' => $now->format(DATE_FORMAT),
            ],
        ];

        return $paybylinkParameters;
    }

    public static function getCheckoutParameterOneclick()
    {
        $context  = \Context::getContext();
        $oneclick = $context->customer->isLogged() ? \Configuration::get('SIBS_CC_ONECLICK') : SibsConstants::SIBS_TOKEN_NONE;

        switch($oneclick) {
            case SibsConstants::SIBS_TOKEN_TOKENIZATION:
                $tokeniseCard       = true;
                $customerAcceptance = false;
                $paymentTokens      = self::getCardTokens();

                break;
            case SibsConstants::SIBS_TOKEN_ONECLICK:
                $tokeniseCard       = ! empty($_POST['sibsCustomerAcceptor']) ? true : false;
                $customerAcceptance = ! empty($_POST['sibsCustomerAcceptor']) ? true : false;
                $paymentTokens      = ! empty($_POST['sibsCustomerAcceptor']) ? self::getCardTokens() : [];

                break;
            case SibsConstants::SIBS_TOKEN_NONE:
            default:
                $tokeniseCard       = false;
                $customerAcceptance = false;
                $paymentTokens      = [];
        }

        $oneclickParameters = [
            'transaction' => [
                'oneClick' => [
                    'customerAcceptance' => $customerAcceptance,
                ],
            ],
            'tokenisation' => [
                'tokenisationRequest' => [
                    'tokeniseCard' => $tokeniseCard,
                ],
                'paymentTokens' => $paymentTokens,
            ],
        ];

        return $oneclickParameters;
    }

    public static function getCardTokens()
    {
        $context = \Context::getContext();

        if ($context->customer->isLogged()) {
            $customerId = $context->customer->id;
            $dbResponse = SibsModels::getCardTokensByCustomer($customerId);

            $tokenFunction = function (array $tokenDB) {
                return [
                    'tokenType' => $tokenDB['token_type'],
                    'value'     => $tokenDB['value'],
                ];
            };

            return array_map($tokenFunction, $dbResponse);
        }

        return [];
    }

    private static function getBackOfficeParameter($transactionData)
    {
        SibsLog::info('transactionData: ' . json_encode($transactionData));

        return $transactionData;
    }

    /**
     * OPP Main Operation.
     */

    // check payment status 3 times if no response.
    private static function isPaymentGetResponse($paymentStatusUrl, &$resultJson, $serverMode, $token)
    {
        for ($i = 0; $i < 3; $i++) {
            $response = true;

            try {
                $resultJson = self::getResponseData(
                    $paymentStatusUrl,
                    $serverMode,
                    'GET',
                    '',
                    'json',
                    $token
                );
            } catch (Exception $e) {
                $response = false;
            }

            if ($response && $resultJson) {
                return true;
            }
        }

        return false;
    }

    /**
     * Prepare the checkout & get checkout id (for create payment form).
     *
     * @param array $transactionData
     *
     * @return array $response
     */
    public static function getCheckoutResult($transactionData, $lang = 'en')
    {
        SibsLog::info('getCheckoutResult()');

        $checkoutUrl = self::getCheckoutUrl($transactionData['server_mode']);
        $postData    = self::getCheckoutParameter($transactionData, $lang);
        $token       = $transactionData['token'];

        $response = self::getResponseData(
            $checkoutUrl,
            $transactionData['server_mode'],
            'POST',
            $postData,
            'json',
            $token
        );

        return $response;
    }

    //Prepare The Checkout & Get Payment Widget Url (for Create Payment Form)
    public static function getPaymentWidgetUrl($transactionData, $checkoutId, $widget_endpoints)
    {
        $serverMode = $transactionData['server_mode'];

        return $widget_endpoints[$serverMode] . $checkoutId;
    }

    //Get the Payment Status
    public static function getPaymentStatus($checkoutId, $transactionData)
    {
        $paymentStatusUrl = self::getPaymentStatusUrl($transactionData['server_mode'], $checkoutId);
        $resultJson       = '';
        $token            = $transactionData['token'];
        $response         = self::isPaymentGetResponse($paymentStatusUrl, $resultJson, $transactionData['server_mode'], $token);

        if ($response && isset($resultJson['response']['returnStatus']['statusCode']) && $resultJson['response']['returnStatus']['statusCode'] == '000') {
            return $resultJson;
        }

        return false;
    }

    /**
     * Send an Initial Payment server to server.
     *
     * @param string $checkoutId
     * @param array  $transactionData
     *
     * @return array $resultJson
     * @return string|bool
     */
    public static function getPaymentServerToServerStatus($checkoutId, $transactionData)
    {
        $paymentStatusUrl = self::getPaymentUrl($transactionData['server_mode'], $checkoutId);
        $paymentStatusUrl .= '?' . http_build_query(self::getCredentialParameter($transactionData));
        $resultJson = '';
        $token      = $transactionData['token'];
        $response   = self::isPaymentGetResponse($paymentStatusUrl, $resultJson, $transactionData['server_mode'], $token);

        if ($response) {
            return $resultJson;
        }

        return false;
    }

    //Back Office Operation : Capture, Refund, Reversal
    public static function backOfficeOperation($referenceId, $transactionData)
    {
        SibsLog::info("referenceId: $referenceId");
        SibsLog::info('transactionData: ' . print_r($transactionData, true));

        $paymentType = $transactionData['paymentType'];

        if ($paymentType == SibsConstants::PAYMENT_MODE_CAPT) {
            $resultJson = self::backOfficeOperationCapture($referenceId, $transactionData);
        } elseif ($paymentType == SibsConstants::PAYMENT_MODE_RFND) {
            $resultJson = self::backOfficeOperationRefund($referenceId, $transactionData);
        } elseif ($paymentType == SibsConstants::PAYMENT_MODE_RVSL) {
            $resultJson = self::backOfficeOperationReversal($referenceId, $transactionData);
        } else {
            $resultJson = [];
        }

        SibsLog::info('backoffice response: ' . json_encode($resultJson));

        return $resultJson;
    }

    public static function backOfficeOperationCapture($referenceId, $transactionData)
    {
        $token         = $transactionData['token'];
        $servermode    =  $transactionData['server_mode'];
        $backOfficeUrl = self::getCaptureUrl($transactionData['server_mode'], $referenceId);

        unset($transactionData['paymentType']);
        unset($transactionData['token']);
        unset($transactionData['test_mode']);
        unset($transactionData['amount']);
        unset($transactionData['currency']);

        $postData = self::getBackOfficeParameter($transactionData);

        return self::getResponseData(
            $backOfficeUrl,
            $servermode,
            'POST',
            $postData,
            'json',
            $token
        );
    }

    public static function backOfficeOperationRefund($referenceId, $transactionData)
    {
        $refund_status = SibsModels::getRefundStatus($transactionData['originalTransaction']['id']);
        SibsLog::info("refund_status: $refund_status");

        if ($refund_status === SibsConstants::CAPTURE_REFUND_STATUS_PENDING) {
            $resultJson['refund_pending'] = true;

            return $resultJson;
        }

        $token         = $transactionData['token'];
        $servermode    = $transactionData['server_mode'];
        $backOfficeUrl = self::getRefundUrl($transactionData['server_mode'], $referenceId);

        unset($transactionData['paymentType']);
        unset($transactionData['token']);
        unset($transactionData['server_mode']);

        $postData = self::getBackOfficeParameter($transactionData);

        return self::getResponseData(
            $backOfficeUrl,
            $servermode,
            'POST',
            $postData,
            'json',
            $token
        );
    }

    public static function backOfficeOperationReversal($referenceId, $transactionData)
    {
        return [];
    }

    /**
     * Send request to payment gateway and get response data.
     *
     * @param array $transactionData
     *
     * @return string|bool
     */
    public static function getServerToServerResponse($transactionData)
    {
        $backOfficeUrl = self::getServerToServerUrl($transactionData['server_mode']);
        $postData      = self::getCheckoutParameter($transactionData);
        $token         = $transactionData['token'];

        return self::getResponseData(
            $backOfficeUrl,
            $transactionData['server_mode'],
            'POST',
            $postData,
            'json',
            $token
        );
    }

    public static function getTransactionResult($returnCode = false, $paymentStatus = false)
    {
        if ($returnCode && $paymentStatus) {
            $acceptPaymentStatus = self::sibs_accept_response_status($paymentStatus);

            if (in_array($returnCode, self::$ackReturnCodes) && $acceptPaymentStatus) {
                return SibsConstants::SIBS_ACK;
            }
        }

        return SibsConstants::SIBS_NOK;
    }

    public static function getErrorIdentifier()
    {
        return 'Unfortunately, your attempt failed.';
    }

    public static function getTranslationByLangIsoCode($identifier, $langIsoCode)
    {
        $_MODULE = [];

        $file = _PS_MODULE_DIR_ . "sibs/translations/{$langIsoCode}.php";
        include $file;

        $translation = $_MODULE['<{sibs}prestashop>sibs_' . md5($identifier)];

        if (isset($translation)) {
            return $translation;
        }

        return $identifier;
    }

    public static function sibs_spg_get_payment_type($payment_type)
    {
        switch ($payment_type) {
            case SibsConstants::PAYMENT_MODE_AUTH:
                $payment_type = SibsConstants::PAYMENT_TYPE_AUTH;

                break;
            case SibsConstants::PAYMENT_MODE_DEBIT:
            case SibsConstants::PAYMENT_MODE_PAY_BY_LINK:
                $payment_type = SibsConstants::PAYMENT_TYPE_PURS;

                break;
            case SibsConstants::PAYMENT_MODE_CAPT:
                $payment_type = SibsConstants::PAYMENT_TYPE_CAPT;

                break;
            case SibsConstants::PAYMENT_MODE_RFND:
                $payment_type = SibsConstants::PAYMENT_TYPE_RFND;

                break;
        }

        return $payment_type;
    }

    /**
     * Translate from Plugin payment identifier to SPG payment methods.
     *
     * @param string $payment_id payment identifier
     * @return array SPG payment method
     */
    public static function sibs_get_payment_method_for_spg($payment_id)
    {
        switch ($payment_id) {
            case SibsConstants::PAYMENT_METHOD_CREDIT_CARD:
                $payment_brand = [
                    SibsConstants::PAYMENT_METHOD_CARD,
                ];

                break;
            case SibsConstants::PAYMENT_METHOD_BLIK:
                $payment_brand = [
                    SibsConstants::PAYMENT_METHOD_BLIK,
                ];

                break;
            case SibsConstants::PAYMENT_METHOD_PAY_BY_LINK:
                $payment_brand = [
                    // SibsConstants::PAYMENT_METHOD_PAY_BY_LINK,
                    SibsConstants::PAYMENT_METHOD_PAY_BY_LINK_KEVIN,
                ];

                break;
            default:
                $payment_brand = [];

                break;
        }

        return $payment_brand;
    }

    /**
     * Convert SPG payment type to DPG payment type.
     *
     * @param string $spg_payment_type SPG payment type
     * @return string DPG payment type
     */
    public static function sibs_convert_spg_payment_type($spg_payment_type)
    {
        switch ($spg_payment_type) {
            case SibsConstants::PAYMENT_TYPE_AUTH:
                $payment_type = SibsConstants::PAYMENT_MODE_AUTH;

                break;
            case SibsConstants::PAYMENT_TYPE_PREF:
            case SibsConstants::PAYMENT_TYPE_PURS:
                $payment_type = SibsConstants::PAYMENT_MODE_DEBIT;

                break;
            case SibsConstants::PAYMENT_TYPE_CAPT:
                $payment_type = SibsConstants::PAYMENT_MODE_CAPT;

                break;
            case SibsConstants::PAYMENT_TYPE_RFND:
                $payment_type = SibsConstants::PAYMENT_MODE_RFND;

                break;
            case SibsConstants::PAYMENT_TYPE_RVSL:
                $payment_type = SibsConstants::PAYMENT_MODE_RVSL;

                break;
            case SibsConstants::PAYMENT_TYPE_PBL:
                $payment_type = SibsConstants::PAYMENT_MODE_PAY_BY_LINK;

                break;
            case SibsConstants::PAYMENT_TYPE_CAUT:
            case SibsConstants::PAYMENT_TYPE_CPRF:
            case SibsConstants::PAYMENT_TYPE_STIQ:
            case SibsConstants::PAYMENT_TYPE_RCON:
            default:
                $payment_type = '';

                break;
        }

        return $payment_type;
    }

    /**
     * Convert  payment status to Prestashop status.
     *
     * @param string $paymentMethod  payment method
     * @param string $paymentStatus  payment status
     * @return string Prestashop status
     */
    public static function sibs_convert_response_status_to_payment_status($paymentMethod, $paymentStatus)
    {
        $auth_or_debit_status = self::sibs_get_auth_or_debit_status($paymentMethod);
        SibsLog::info('auth_or_debit_status: ' . $auth_or_debit_status);
        SibsLog::info('paymentStatus: ' . $paymentStatus);

        switch ($paymentStatus) {
            case SibsConstants::PAYMENT_STATUS_SUCCESS:
            case SibsConstants::PAYMENT_STATUS_PARTIAL:
                $trnStatus = $auth_or_debit_status;

                break;
            case SibsConstants::PAYMENT_STATUS_INPROCESSING:
            case SibsConstants::PAYMENT_STATUS_PENDING:
                $trnStatus = \Configuration::get(SibsConstants::ORDER_STATUS_SIBS_PENDING);

                break;
            case SibsConstants::PAYMENT_STATUS_DECLINED:
            case SibsConstants::PAYMENT_STATUS_TIMEOUT:
            case SibsConstants::PAYMENT_STATUS_ERROR:
            default:
                $trnStatus = \Configuration::get(SibsConstants::ORDER_STATUS_CANCELED);

                break;
        }

        return $trnStatus;
    }

    public static function sibs_get_auth_or_debit_status($spg_payment_method)
    {
        switch($spg_payment_method) {
            case SibsConstants::PAYMENT_METHOD_CARD:
            case SibsConstants::PAYMENT_METHOD_TOKEN:
            case SibsConstants::PAYMENT_METHOD_CREDIT_CARD:
                return self::sibs_return_status_from_mode(\Configuration::get('SIBS_CC_MODE'));

                break;
            case SibsConstants::PAYMENT_METHOD_BLIK:
                return self::sibs_return_status_from_mode(\Configuration::get('SIBS_BLIK_MODE'));

                break;
            case SibsConstants::PAYMENT_METHOD_PAY_BY_LINK:
            case SibsConstants::PAYMENT_METHOD_PAY_BY_LINK_KEVIN:
                return self::sibs_return_status_from_mode(\Configuration::get('SIBS_PAY_BY_LINK_MODE'));

                break;
            default:
                return \Configuration::get(SibsConstants::ORDER_STATUS_ERROR);

                break;
        }
    }

    public static function sibs_return_status_from_mode($mode)
    {
        if ($mode === SibsConstants::PAYMENT_MODE_AUTH) {
            return \Configuration::get(SibsConstants::ORDER_STATUS_SIBS_AUTHORIZED);
        }

        return \Configuration::get(SibsConstants::ORDER_STATUS_PAYMENT);
    }

    /**
     * Accept SPG Status.
     *
     * @param string $paymentStatus payment status
     * @return bool Prestashop success
     */
    public static function sibs_accept_response_status($paymentStatus)
    {
        switch ($paymentStatus) {
            case SibsConstants::PAYMENT_STATUS_SUCCESS:
            case SibsConstants::PAYMENT_STATUS_PARTIAL:
            case SibsConstants::PAYMENT_STATUS_INPROCESSING:
            case SibsConstants::PAYMENT_STATUS_PENDING:
                $acptStatus = true;

                break;
            case SibsConstants::PAYMENT_STATUS_DECLINED:
            case SibsConstants::PAYMENT_STATUS_TIMEOUT:
            case SibsConstants::PAYMENT_STATUS_ERROR:
            default:
                $acptStatus = false;

                break;
        }

        return $acptStatus;
    }

    public static function sibs_convert_response_status_to_capture_payment_status($captureRefundStatus)
    {
        switch ($captureRefundStatus) {
            case SibsConstants::PAYMENT_STATUS_SUCCESS:
            case SibsConstants::PAYMENT_STATUS_PARTIAL:
                $trnStatus = SibsConstants::CAPTURE_REFUND_STATUS_SUCCESS;

                break;
            case SibsConstants::PAYMENT_STATUS_INPROCESSING:
            case SibsConstants::PAYMENT_STATUS_PENDING:
                $trnStatus = SibsConstants::CAPTURE_REFUND_STATUS_PENDING;

                break;
            case SibsConstants::PAYMENT_STATUS_DECLINED:
            case SibsConstants::PAYMENT_STATUS_TIMEOUT:
            case SibsConstants::PAYMENT_STATUS_ERROR:
            default:
                $trnStatus = SibsConstants::CAPTURE_REFUND_STATUS_FAILED;

                break;
        }

        return $trnStatus;
    }

    public static function getOrderRefundStatus($refundStatus)
    {
        switch($refundStatus) {
            case SibsConstants::PAYMENT_STATUS_INPROCESSING:
            case SibsConstants::PAYMENT_STATUS_PENDING:
                return SibsConstants::ORDER_STATUS_SIBS_REFUND_PENDING;

                break;
            case SibsConstants::PAYMENT_STATUS_SUCCESS:
            case SibsConstants::PAYMENT_STATUS_PARTIAL:
            default:
                return SibsConstants::ORDER_STATUS_REFUND;
        }
    }

    public static function saveOrderHistory($orderID, $orderStatus, $employeeID = null)
    {
        $order = new \Order($orderID);
        // payment accepted status code RF
        $id_order_status = \Configuration::get($orderStatus);
        // update order state to code RF
        $new_history = new \OrderHistory();

        if (is_null($employeeID)) {
            $new_history->id_employee = $employeeID;
        }

        $new_history->id_order = $orderID;
        $new_history->changeIdOrderState((int) $id_order_status, $order, true);
        $new_history->add();
    }
        //TODO: adicionar dados na nossa tabela

    public static function saveOrderHistoryWithEmail($orderID, $orderStatus, $employeeID = null)
    {
        $order = new \Order($orderID);
        // payment accepted status code RF
        $id_order_status = \Configuration::get($orderStatus);
        // update order state to code RF
        $new_history = new \OrderHistory();

        if (is_null($employeeID)) {
            $new_history->id_employee = $employeeID;
        }

        $new_history->id_order = $orderID;
        $new_history->changeIdOrderState((int) $id_order_status, $order, true);
        $new_history->add();
    }
}
