<?php
/**
 * 2018 Paysera
 *
 * 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:
 * http://opensource.org/licenses/afl-3.0.php
 * 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.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2018 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */
if (!defined('_PS_VERSION_')) {
    exit;
}

require_once __DIR__ . '/vendor/autoload.php';

use Evp\Component\Money\Money;
use Paysera\Helper\TabHelper;
use Paysera\Service\Provider\PaymentMethodCountryProvider;
use Paysera\Service\Provider\SpecificCountriesConfigurationProvider;
use Paysera\Service\Resolver\DesiredCountryResolver;
use PrestaShop\PrestaShop\Core\Payment\PaymentOption;
use Paysera\Scoped\Symfony\Component\Config\FileLocator;
use Paysera\Scoped\Symfony\Component\DependencyInjection\ContainerBuilder;
use Paysera\Scoped\Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use PrestaShop\ModuleLibServiceContainer\DependencyInjection\ServiceContainer;
use Paysera\Scoped\Symfony\Component\Dotenv\Dotenv;

/**
 * Class Paysera.
 */
class Paysera extends PaymentModule
{
    const PAYSERA_DELIVERY_MODULE_NAME = 'payseradelivery';

    /**
     * Default language code.
     */
    const DEFAULT_LANG = 'en';

    /**
     * Quality sign js link.
     */
    const QUALITY_SIGN_JS = 'https://bank.paysera.com/new/js/project/wtpQualitySigns.js';

    /**
     * @var array
     */
    protected $availableLang = ['lt', 'lv', 'ru', 'en', 'pl', 'bg', 'ee'];

    /**
     * @var TabHelper
     */
    private $tabHelper;
    /**
     * @var ServiceContainer
     */
    private $serviceContainer;

    /**
     * Paysera constructor.
     */
    public function __construct()
    {
        $this->name = 'paysera';
        $this->version = '3.0.0';
        $this->tab = 'payments_gateways';
        $this->compatibility = ['min' => '1.7.0', 'max' => _PS_VERSION_];
        $this->ps_versions_compliancy = ['min' => '1.7.0', 'max' => _PS_VERSION_];
        $this->module_key = 'b830e1e952dfce7551c31477a86221af';
        $this->author = 'Paysera';
        $this->controllers = ['redirect', 'callback', 'accept', 'cancel'];
        $this->bootstrap = true;
        parent::__construct();
        $this->loadEnvFiles();

        $this->displayName = $this->l('Paysera');
        $this->description = $this->l('Accept payments by Paysera system.');
        $this->tabHelper = new TabHelper();

        define('PAYSERA_PLUGIN_VERSION', $this->version);
        $this->initializeServices();
    }

    private function initializeServices(): void
    {
        $this->serviceContainer = new ServiceContainer(
            $this->name . str_replace(['.', '-', '+'], '', $this->version),
            $this->getLocalPath()
        );
    }

    /**
     * @return bool
     */
    public function install()
    {
        $this->warning = null;
        if (
            is_null($this->warning)
            && !(
                parent::install()
                && $this->registerHook('paymentOptions')
                && $this->registerHook('displayHeader')
                && $this->registerHook('displayBackOfficeHeader')
                && $this->registerHook('actionModuleInstallAfter')
                && $this->registerHook('actionModuleUninstallAfter')
                && $this->registerHook('payseraPaymentConfirmed')
                && $this->registerHook('actionFrontControllerInitBefore')
                && $this->registerHook('displayOrderConfirmation')

            )
        ) {
            if ('ERROR_MESSAGE_INSTALL_MODULE' == $this->l('ERROR_MESSAGE_INSTALL_MODULE')) {
                $this->warning = 'There was an Error installing the module.';
            } else {
                $this->warning = $this->l('ERROR_MESSAGE_INSTALL_MODULE');
            }
        }

        $defaultVal = $this->getDefaultValues();
        Configuration::updateValue('PAYSERA_GENERAL_PROJECT_ID', '');
        Configuration::updateValue('PAYSERA_GENERAL_SIGN_PASS', '');
        Configuration::updateValue('PAYSERA_GENERAL_TEST_MODE', '0');
        Configuration::updateValue('PAYSERA_EXTRA_TITLE', $defaultVal['title']);
        Configuration::updateValue('PAYSERA_EXTRA_DESCRIPTION', $defaultVal['desc']);
        Configuration::updateValue('PAYSERA_EXTRA_LIST_OF_PAYMENTS', $defaultVal['list_of_payments']);
        Configuration::updateValue('PAYSERA_EXTRA_SPECIFIC_COUNTRIES', '');
        Configuration::updateValue('PAYSERA_EXTRA_SPECIFIC_COUNTRIES_GROUP', $defaultVal['countries']);
        Configuration::updateValue('PAYSERA_EXTRA_GRIDVIEW', '0');
        Configuration::updateValue('PAYSERA_EXTRA_FORCE_LOGIN', '0');
        Configuration::updateValue('PAYSERA_EXTRA_BUYER_CONSENT', '0');
        Configuration::updateValue('PAYSERA_ADDITIONS_QUALITY_SIGN', '0');
        Configuration::updateValue('PAYSERA_ADDITIONS_OWNERSHIP', '0');
        Configuration::updateValue('PAYSERA_ADDITIONS_OWNERSHIP_CODE', '');

        $this->tabHelper->installTabs();

        if (is_null($this->warning) && !$this->addPayseraOrderStatuses()) {
            if ('ERROR_MESSAGE_CREATE_ORDER_STATUS' == $this->l('ERROR_MESSAGE_CREATE_ORDER_STATUS')) {
                $this->warning = 'There was an Error creating a custom order status.';
            } else {
                $this->warning = $this->l('ERROR_MESSAGE_CREATE_ORDER_STATUS');
            }
        }

        return is_null($this->warning);
    }

    /**
     * @return void
     */
    public function hookActionModuleInstallAfter(array $module)
    {
        if ($module['object']->name === self::PAYSERA_DELIVERY_MODULE_NAME) {
            $this->tabHelper->syncTabs();
        }
    }

    /**
     * @return void
     */
    public function hookActionModuleUninstallAfter(array $module)
    {
        if ($module['object']->name === self::PAYSERA_DELIVERY_MODULE_NAME) {
            $this->tabHelper->syncTabs();
        }
    }

    public function triggerPayseraPaymentConfirmedHook(Order $order)
    {
        Hook::exec('payseraPaymentConfirmed', [
            'order' => $order,
        ]);
    }

    /**
     * @return void
     */
    public function hookDisplayBackOfficeHeader()
    {
        if (!Module::isEnabled(self::PAYSERA_DELIVERY_MODULE_NAME)) {
            $this->context->controller->addCss($this->_path . 'views/css/tab.css');
        }
    }

    /**
     * method stub to avoid error during installation
     * needed to send payment confirmation to the delivery module
     *
     * @param array $params
     * @return void
     */
    public function hookPayseraPaymentConfirmed($params)
    {
    }

    /**
     * @return array
     */
    public function getDefaultValues()
    {
        $values = [];

        if ('PAYSERA_EXTRA_TITLE_DEFAULT' == $this->l('PAYSERA_EXTRA_TITLE_DEFAULT')) {
            $values['title'] = $this->l('Pay using Paysera');
        } else {
            $values['title'] = $this->l('PAYSERA_EXTRA_TITLE_DEFAULT');
        }
        if ('PAYSERA_EXTRA_DESCRIPTION_DEFAULT' == $this->l('PAYSERA_EXTRA_DESCRIPTION_DEFAULT')) {
            $values['desc'] = $this->l('Redirect to payment methods page');
        } else {
            $values['desc'] = $this->l('PAYSERA_EXTRA_DESCRIPTION_DEFAULT');
        }
        if ('PAYSERA_ORDER_STATUS_NEW' == $this->l('PAYSERA_ORDER_STATUS_NEW')) {
            $values['status_new'] = $this->l('Awaiting Paysera confirmation');
        } else {
            $values['status_new'] = $this->l('PAYSERA_ORDER_STATUS_NEW');
        }
        if ('PAYSERA_ORDER_STATUS_PAID' == $this->l('PAYSERA_ORDER_STATUS_PAID')) {
            $values['status_paid'] = $this->l('Paysera confirmed payment');
        } else {
            $values['status_paid'] = $this->l('PAYSERA_ORDER_STATUS_PAID');
        }
        if ('PAYSERA_ORDER_STATUS_PENDING' == $this->l('PAYSERA_ORDER_STATUS_PENDING')) {
            $values['status_pending'] = $this->l('Awaiting Paysera payment');
        } else {
            $values['status_pending'] = $this->l('PAYSERA_ORDER_STATUS_PENDING');
        }
        $values['countries'] = '[""]';
        $values['list_of_payments'] = 1;

        return $values;
    }

    /**
     * @return bool
     */
    public function uninstall()
    {
        Configuration::deleteByName('PAYSERA_GENERAL_PROJECT_ID');
        Configuration::deleteByName('PAYSERA_GENERAL_SIGN_PASS');
        Configuration::deleteByName('PAYSERA_GENERAL_TEST_MODE');
        Configuration::deleteByName('PAYSERA_EXTRA_TITLE');
        Configuration::deleteByName('PAYSERA_EXTRA_DESCRIPTION');
        Configuration::deleteByName('PAYSERA_EXTRA_LIST_OF_PAYMENTS');
        Configuration::deleteByName('PAYSERA_EXTRA_SPECIFIC_COUNTRIES');
        Configuration::deleteByName('PAYSERA_EXTRA_SPECIFIC_COUNTRIES_GROUP');
        Configuration::deleteByName('PAYSERA_EXTRA_GRIDVIEW');
        Configuration::deleteByName('PAYSERA_EXTRA_FORCE_LOGIN');
        Configuration::deleteByName('PAYSERA_EXTRA_BUYER_CONSENT');
        Configuration::deleteByName('PAYSERA_ADDITIONS_QUALITY_SIGN');
        Configuration::deleteByName('PAYSERA_ADDITIONS_OWNERSHIP');
        Configuration::deleteByName('PAYSERA_ADDITIONS_OWNERSHIP_CODE');
        $this->unregisterHook('paymentOptions');
        $this->unregisterHook('displayHeader');
        $this->unregisterHook('payseraPaymentConfirmed');
        $this->tabHelper->uninstallTabs();
        parent::uninstall();

        return true;
    }

    /**
     * @return bool
     */
    public function addPayseraOrderStatuses()
    {
        $stateConfig = [];
        try {
            $stateConfig['color'] = 'lightblue';
            $this->addOrderStatus(
                'PAYSERA_ORDER_STATUS_PENDING',
                $stateConfig,
                [
                    'lt' => 'Laukiama Paysera mokėjimo',
                    'lv' => 'Gaida maksājumu no Paysera',
                    'ru' => 'В ожидании платежа от Paysera',
                    'en' => 'Awaiting Paysera payment',
                    'pl' => 'Oczekiwanie na płatność z serwisu Paysera',
                    'et' => 'Paysera\'lt makse ootamine',
                    'es' => 'Esperando el pago de Paysera',
                ]
            );
            $stateConfig['color'] = 'cadetblue';
            $this->addOrderStatus(
                'PAYSERA_ORDER_STATUS_NEW',
                $stateConfig,
                [
                    'lt' => 'Laukiama Paysera patvirtinimo',
                    'lv' => 'Gaida apstiprinājumu no Paysera',
                    'ru' => 'В ожидании подтверждения от Paysera',
                    'en' => 'Awaiting Paysera confirmation',
                    'pl' => 'Oczekiwanie na potwierdzenie z serwisu Paysera',
                    'et' => 'Paysera\'lt kinnituse ootamine',
                    'es' => 'En espera de confirmación de Paysera',
                ]
            );
            $stateConfig['color'] = 'darkseagreen';
            $stateConfig['send_email'] = true;
            $stateConfig['template'] = 'payment';
            $this->addOrderStatus(
                'PAYSERA_ORDER_STATUS_PAID',
                $stateConfig,
                [
                    'lt' => 'Paysera patvirtinimo mokėjimą',
                    'lv' => 'Paysera apstiprināja maksājumu',
                    'ru' => 'Paysera подтвердила платёж',
                    'en' => 'Paysera confirmed payment',
                    'pl' => 'Serwis Paysera potwierdził płatność',
                    'et' => 'Paysera kinnitas makse',
                    'es' => 'Paysera ha confirmado el pago',
                ],
                true
            );

            PrestaShopLogger::addLog(
                'Paysera module: Custom order statuses were created.',
                1,
                null,
                'Paysera'
            );

            Tools::clearAllCache();

            return true;
        } catch (Exception $exception) {
            PrestaShopLogger::addLog(
                'Paysera module error:: Custom order statuses creation were failed.'
                    . ' Error: ' . $exception->getMessage(),
                3,
                null,
                'Paysera'
            );

            return false;
        }
    }

    /**
     * @param string $configKey
     * @param array $stateConfig
     * @param array $nameByLangIsoCode
     * @param bool $paid
     */
    public function addOrderStatus($configKey, $stateConfig, $nameByLangIsoCode, $paid = false)
    {
        if (Configuration::get($configKey)) {
            $orderState = new OrderState((int) Configuration::get($configKey));

            if (Validate::isLoadedObject($orderState) && !$orderState->deleted && $this->name === $orderState->module_name) {
                Configuration::updateValue($configKey, $orderState->id);
                return;
            }
        }

        $orderState = new OrderState();
        $orderState->name = [];
        $orderState->module_name = $this->name;
        $orderState->send_email = (int) (!empty($stateConfig['send_email']));
        $orderState->color = $stateConfig['color'];
        $orderState->hidden = false;
        $orderState->delivery = false;
        $orderState->logable = true;
        $orderState->paid = $paid;

        $fallbackName = $nameByLangIsoCode[$this::DEFAULT_LANG] ?? reset($nameByLangIsoCode);

        foreach (Language::getLanguages(false) as $lang) {
            $iso = Tools::strtolower($lang['iso_code']);
            $idLang = (int) $lang['id_lang'];

            $orderState->name[$idLang] = $nameByLangIsoCode[$iso] ?? $fallbackName;

            if ($orderState->send_email && !empty($stateConfig['template'])) {
                $orderState->template[$idLang] = $stateConfig['template'];
            }
        }

        $result = (bool) $orderState->add();

        if ($result === false) {
            $this->_errors[] = sprintf(
                'Failed to create OrderState %s',
                $configKey
            );

            return false;
        }

        Configuration::updateValue($configKey, $orderState->id);
    }

    /**
     * Redirect to configuration controller.
     */
    public function getContent()
    {
        Tools::redirectAdmin($this->context->link->getAdminLink('AdminPayseraConfiguration'));
    }

    /**
     * @return bool|string
     */
    public function hookDisplayHeader()
    {
        $controller = $this->context->controller->php_self;
        if ('order' == $controller) {
            $displayPaymentMethods = (bool) Configuration::get('PAYSERA_EXTRA_LIST_OF_PAYMENTS');

            if ($displayPaymentMethods) {
                $this->context->controller->registerStylesheet(
                    sha1('modules-paysera-order'),
                    'modules/paysera/views/css/payment-methods.css'
                );
            }

            $this->context->controller->registerJavascript(
                sha1('modules-paysera-order'),
                'modules/paysera/views/js/payment-methods.js'
            );
        }

        $configProjectID = Configuration::get('PAYSERA_GENERAL_PROJECT_ID');
        $configQuality = Configuration::get('PAYSERA_ADDITIONS_QUALITY_SIGN');
        $configOwnership = Configuration::get('PAYSERA_ADDITIONS_OWNERSHIP');
        $configOwnershipCode = Configuration::get('PAYSERA_ADDITIONS_OWNERSHIP_CODE');

        if ($configQuality) {
            $this->getQualitySign($configProjectID);
        }

        if ($configOwnership && $configOwnershipCode !== '') {
            $this->context->smarty->assign('ownershipCode', $configOwnershipCode);

            return $this->display(__FILE__, 'views/templates/hook/header.tpl');
        }

        return null;
    }

    /**
     * @param string $projectID
     */
    private function getQualitySign($projectID)
    {
        $langIso = $this->context->language->iso_code;

        $defaultLang = $this::DEFAULT_LANG;
        $availableLangs = $this->getAvailableLang();

        $jsParams = [
            'wtpQualitySign_projectId' => $projectID,
            'wtpQualitySign_language' => in_array($langIso, $availableLangs) ? $langIso : $defaultLang,
        ];

        Media::addJsDef($jsParams);

        $this->context->controller->registerJavascript(
            sha1('modules-paysera-widget'),
            $this::QUALITY_SIGN_JS,
            ['server' => 'remote']
        );
    }

    /**
     * @return array|PaymentOption[]
     * @throws Exception
     */
    public function hookPaymentOptions()
    {
        $container = $this->serviceContainer;

        /** @var SpecificCountriesConfigurationProvider $specificCountriesConfigurationProvider */
        $specificCountriesConfigurationProvider = $container->getService('paysera.provider.specific_countries_configuration');
        /** @var PaymentMethodCountryProvider $paymentMethodCountryProvider */
        $paymentMethodCountryProvider = $container->getService('paysera.provider.payment_method_country');
        /** @var DesiredCountryResolver $desiredCountryResolver */
        $desiredCountryResolver = $container->getService('paysera.resolver.desired_country');

        $translations = $this->getPaymentOptionsTranslations();

        $projectID = Configuration::get('PAYSERA_GENERAL_PROJECT_ID');
        $title = $translations['title'];
        $description = $translations['desc'];
        $gridView = Configuration::get('PAYSERA_EXTRA_GRIDVIEW');
        $buyerConsent = Configuration::get('PAYSERA_EXTRA_BUYER_CONSENT');
        $displayPaymentMethods = (bool) Configuration::get('PAYSERA_EXTRA_LIST_OF_PAYMENTS');

        $cartDetails = $this->context->cart;
        $addressObj = new Address($cartDetails->id_address_invoice);
        $countryObj = new Country($addressObj->id_country);
        $country = Tools::strtolower($countryObj->iso_code);
        $langISO = Tools::strtolower($this->context->language->iso_code);
        $currency = $this->context->currency->iso_code;

        $totalOrderCost = new Money($cartDetails->getOrderTotal() * 100, $currency);
        $totalShippingCost = new Money($cartDetails->getTotalShippingCost() * 100, $currency);
        $cartTotal = $totalOrderCost->sub($totalShippingCost);

        $payseraOption = new PaymentOption();
        $payseraOption->setCallToActionText($title);
        $payseraOption->setLogo(Media::getMediaPath(__DIR__ . '/views/img/paysera.svg'));
        $payseraOption->setAction($this->context->link->getModuleLink($this->name, 'redirect'));

        $templateVariables = [
            'title' => $title,
            'description' => $description,
            'buyerConsent' => $buyerConsent ? $this->getBuyerConsentTranslations() : null,
            'isGridView' => $gridView === '1' || $gridView === 1,
        ];

        if ($displayPaymentMethods) {
            $language = in_array($langISO, $this->getAvailableLang(), true) ? $langISO : 'en';

            $paymentMethodCountries = $paymentMethodCountryProvider->get(
                $projectID,
                $currency,
                $language,
                $cartTotal
            );
            $selectedCountries = $specificCountriesConfigurationProvider->get();
            $filteredPaymentMethodCountries = $selectedCountries !== null
                ? $paymentMethodCountryProvider->filterByCountryWhitelist($paymentMethodCountries, $selectedCountries)
                : $paymentMethodCountries
            ;

            $countryCodes = [];
            foreach ($filteredPaymentMethodCountries as $paymentMethodCountry) {
                $countryCodes[] = $paymentMethodCountry->getCode();
            }

            $templateVariables['defaultCountry'] = $desiredCountryResolver->resolve($country, $countryCodes);
            $templateVariables['paymentMethodCountries'] = $filteredPaymentMethodCountries;
        }

        $this->smarty->assign($templateVariables);

        $payseraOption->setInputs([
            'paysera_billing_country' => [
                'name' => 'paysera_billing_country',
                'type' => 'hidden',
                'value' => $country,
            ],
            'paysera_payment_method' => [
                'name' => 'paysera_payment_method',
                'type' => 'hidden',
                'value' => '',
            ],
        ]);

        $payseraOption->setAdditionalInformation($this->fetch('module:paysera/views/templates/hook/additional-information.tpl'));

        return [$payseraOption];
    }

    /**
     * @return ContainerBuilder
     * @throws Exception
     */
    private function getFallbackContainer()
    {
        $containerBuilder = new ContainerBuilder();
        $loader = new YamlFileLoader($containerBuilder, new FileLocator(__DIR__));

        $containerBuilder->set('prestashop.adapter.legacy.configuration', new Configuration());
        $loader->load('config/services.yml');

        return $containerBuilder;
    }

    /**
     * @return array
     */
    public function getBuyerConsentTranslations()
    {
        $translations = [];

        $description = $this->l(
            'Please be informed that the account information and payment initiation services will be provided to you
             by Paysera in accordance with these %s. By proceeding with this payment, you agree to receive this service
              and the service terms and conditions.'
        );
        $descriptionParts = explode('%s', $description);
        $translations['description']['partA'] = $descriptionParts[0];
        $translations['description']['partB'] = $descriptionParts[1];
        $translations['link'] = $this->l('https://www.paysera.lt/v2/en-LT/legal/pis-rules-2020');
        $translations['rules'] = $this->l('rules');

        return $translations;
    }

    /**
     * @return array
     */
    public function getPaymentOptionsTranslations()
    {
        $keys = ['title' => 'PAYSERA_EXTRA_TITLE', 'desc' => 'PAYSERA_EXTRA_DESCRIPTION'];
        $translations = [];

        foreach ($keys as $name => $key) {
            $translations[$name] = $this->l(Configuration::get($key));
        }

        return $translations;
    }

    /**
     * @return bool
     */
    public function checkCurrency()
    {
        $idCurrency = $this->context->cart->id_currency;

        $currency = new Currency($idCurrency);
        $moduleCurrencies = $this->getCurrency($idCurrency);

        if (is_array($moduleCurrencies)) {
            foreach ($moduleCurrencies as $moduleCurrency) {
                if ($currency->id == $moduleCurrency['id_currency']) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * @return array
     */
    public function getAvailableLang()
    {
        return $this->availableLang;
    }

    private function loadEnvFiles()
    {
        if (file_exists(__DIR__ . '/.env')) {
            $dotenv = new Dotenv();
            $dotenv->usePutenv();
            $dotenv->load(__DIR__ . '/.env');
        }
    }

    public function hookActionFrontControllerInitBefore($params)
    {
        $controllerName = $this->context->controller->php_self ?? '';
        if (!in_array($controllerName, ['cart', 'order'])) {
            return;
        }

        $lastId = $this->context->cookie->payseraRestoreCartId ?? null;
        $expiry = $this->context->cookie->payseraRestoreCartExpiry ?? null;

        if (!is_numeric($lastId) || !is_numeric($expiry)) {
            return;
        }

        if (time() > $expiry) {
            unset($this->context->cookie->payseraRestoreCartId);
            unset($this->context->cookie->payseraRestoreCartExpiry);
            $this->context->cookie->write();
            return;
        }

        unset($this->context->cookie->payseraRestoreCartId);
        unset($this->context->cookie->payseraRestoreCartExpiry);
        $this->context->cookie->write();

        $old = new Cart($lastId);
        if (!Validate::isLoadedObject($old)) {
            return;
        }
        if ($this->context->customer->id && (int)$old->id_customer !== (int)$this->context->customer->id) {
            return;
        }

        if (!$this->shouldRestoreCart($lastId)) {
            return;
        }

        $url = $this->context->link->getModuleLink(
            $this->name,
            'cancel',
            ['cartID' => $lastId, 'key' => $this->context->customer->secure_key],
            true
        );
        Tools::redirect($url);
    }

    public function hookDisplayOrderConfirmation($params)
    {
        unset($this->context->cookie->payseraRestoreCartId);
        unset($this->context->cookie->payseraRestoreCartExpiry);
        $this->context->cookie->write();
    }

    private function shouldRestoreCart($cartId)
    {
        $orderId = Order::getIdByCartId($cartId);
        if (!$orderId) {
            return true;
        }

        $order = new Order($orderId);
        if (!Validate::isLoadedObject($order)) {
            return true;
        }

        if ($order->module !== $this->name) {
            return false;
        }

        $pendingOrderStateId = (int) Configuration::get('PAYSERA_ORDER_STATUS_PENDING');
        $currentStateId = (int) $order->getCurrentOrderState()->id;

        return $currentStateId === $pendingOrderStateId;
    }
}
