<?php
/**
 * 2016 Eengine Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * @author     Eengine Sp. z o.o.
 * @copyright  InPost
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 *
 *
 */
if (!defined('_PS_VERSION_')) {
    exit;
}

require_once(dirname(__FILE__) . '/controllers/InpostConnector.php');
require_once(dirname(__FILE__) . '/controllers/InpostModel.php'); //AR
require_once(dirname(__FILE__) . '/controllers/InpostFormCreator.php');
require_once(dirname(__FILE__) . '/controllers/InpostPackages.php');
require_once(dirname(__FILE__) . '/controllers/InpostLabels.php');
require_once(dirname(__FILE__) . '/controllers/InpostDispatchPoints.php');
require_once(dirname(__FILE__) . '/controllers/InpostCouriers.php');
require_once(dirname(__FILE__) . '/classes/Carrier.php');
require_once(dirname(__FILE__) . '/Helper.php');
require_once(dirname(__FILE__) . '/controllers/CrossBorderConnector.php');


if (!defined('INPOST_TPL_DIR')) {
    define('INPOST_TPL_DIR', dirname(__FILE__) . '/views/templates/');
}
if (!defined('INPOST_IMG_DIR')) {
    define('INPOST_IMG_DIR', _PS_MODULE_DIR_ . 'inpost/views/img');
}
if (!defined('_INPOST_MODULE_DIR_')) {
    define('_INPOST_MODULE_DIR_', _MODULE_DIR_ . 'inpost/');
}
if (!defined('_INPOST_TOOLS_DIR_')) {
    define('_INPOST_TOOLS_DIR_', dirname(__FILE__) . '/libraries/');
}


class Inpost extends CarrierModule
{
    protected $html = '';
    protected $postErrors = array();
    private $inpost_form_creator;
    public $module_url;
    public $action;
    public $id_carrier; //automatically set by front
    public static $carriers = array();
    public $packagesController;
    public $api;
    public $customer;
    public $token;
    public $errors;
    public $context;
    const INPOST_COUNTRY_1 = 'PL';
    const INPOST_COUNTRY_2 = 'FR';
    const INPOST_COUNTRY_3 = 'IT';
    const ZWROTY_URL = 'https://szybkiezwroty.pl/';
    const POLAND_PHONE = '/^[1-9]\d{8}$/';
    const FRANCE_PHONE = '/^(06|07)\d{8}$/';
    const ITALY_PHONE = '/^3\d{8,9}$/';
    public function __construct()
    {
        $this->name = 'inpost';
        $this->tab = 'shipping_logistics';
        $this->version = '1.2.1';
        $this->author = 'InPost PrestaShop powered by eEngine.co';
        $this->description = $this->l('InPost PrestaShop powered by eEngine.co');
        $this->need_instance = 0;

        $this->bootstrap = true;
        parent::__construct();

        $this->displayName = $this->l('InPost');
        $this->confirmUninstall = $this->l('Are you sure you want to uninstall?');


        if (!Configuration::get('inpost')) {
            $this->warning = $this->l('No name provided');
        }
		//fixes conflict with other InPost modules
		if (($oldConfigValue = Configuration::get('INPOST_API_URL')) && !Configuration::get('EE_INPOST_API_URL')) {
			Configuration::updateValue('EE_INPOST_API_URL', $oldConfigValue);
		}
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            $this->module_url = 'index.php?controller=adminmodules&token=' . Tools::getValue('token') . '&configure=' .
                $this->name;
        } else {
            $this->module_url = 'index.php?controller=AdminModules&token=' . Tools::getValue('token') . '&configure=' .
                $this->name;
        }
        $this->inpost_form_creator = new InpostFormCreator();
        $this->packagesController = new InpostPackages();
        $this->labelsController = new InpostLabels();
        $this->dispatchController = new InpostDispatchPoints();
        $this->couriers = new InpostCouriers();
        $this->api = new InpostConnector();
        $this->x_api = new CrossBorderConnector();

        $this->token = sha1(_COOKIE_KEY_ . $this->name);
        $this->setGlobalVariables();

		if(Tools::getValue('adminAjax'))
		{
			require_once 'inpost.ajax.php';
		}
    }

    public function getBaseURL($addURI = true)
    {
        $domainSSL = Tools::getShopDomainSsl(true);
        $domainNOSSL = Tools::getShopDomain(true);

        if(Configuration::get('PS_SSL_ENABLED') && $domainSSL) {
            $domain = $domainSSL;
        } else {
            $domain = $domainNOSSL;
        }

        $base_uri = '';

        if($addURI) {
            $base_uri = constant('__PS_BASE_URI__');
            if(!strlen($base_uri) || substr($base_uri, -1) != '/') {
                $base_uri = '/';
            }
        }

        return $domain . $base_uri;

    }

    public function setGlobalVariables()
    {
		$baseUrlAjax = $this->getBaseURL() .'modules/inpost/inpost.ajax.php?token='.$this->token;

		if (defined('_PS_ADMIN_DIR_'))
		{
			$baseUrlAjax = 'index.php?token'.Tools::getValue('token').'&controller=AdminController&configure=inpost&module_name=inpost&adminAjax=true';
		}

        $this->context->smarty->assign(array(
            'inpost_ajax_request' => $baseUrlAjax,
            'inpost_country' => Configuration::get('INPOST_COUNTRY'),
            'INPOST_GEOWIDGET_URL' => Configuration::get('INPOST_GEOWIDGET_URL'),
            'PARCEL_STATUSES' => array(
                'created' => $this->l('Created'),
                'prepared' => $this->l('Prepared'),
                'send' => $this->l('Send'),
                'sent' => $this->l('Sent'),
                'in_transit' => $this->l('In Transit'),
                'stored' => $this->l('Stored'),
                'delivered' => $this->l('Delivered'),
                'customer_delivering' => $this->l('Customer Delivering'),
                'customer_stored' => $this->l('Customer Stored'),
                'avizo' => $this->l('Avizo'),
                'expired' => $this->l('Expired'),
                'returnedtoagency' => $this->l('ReturnedToAgency'),
                'deliveredtoagency' => $this->l('DeliveredToAgency'),
                'returnedtosender' => $this->l('ReturnedToSender'),
                'cancelled' => $this->l('Cancelled'),
                'readytobesent' => $this->l('Ready To be sent'),
                'processing' => $this->l('Processing')
            )
        ));
        $this->context->smarty->assign('q_img_dir', _INPOST_MODULE_DIR_ . 'views/img/');
    }

    public function downloadManifestAction($packagesId, $toFile = false, $courierApiId = false)
    {
        $files = array();
        $courierApi = false;
        if ($courierApiId) {
            $courierApi = InpostCouriers::getCourierByCourierApiId($courierApiId);
        }


        InpostHelper::requirePdfFiles();
        $packagesInfo = array();

        if (!$packagesId) {
            $this->html .= $this->displayError($this->l('Select parcels'));
        } else {
            foreach ($packagesId as $packageId) {
                $packageD = InpostModel::findPackageByPackageId($packageId);

                $b = InpostHelper::generateBarcode($packageId);

                $packagesInfo[$packageD['dispatch_point_id']][] = array(
                    'api' => $this->api->getParcel($packageId),
                    'database' => $packageD,
                    'barcode' => $b
                );
            }

            $this->context->smarty->assign(array(
                'sender' => $this->api->getCustomer(),
                'courier_api' => $courierApi
            ));

            foreach ($packagesInfo as $key => $dispatchPoint) {
                $disPoint = InpostDispatchPoints::getDispatchPointById($key);
                $disPointApi = $this->api->getDispatchPoint($disPoint['href']);


                $this->context->smarty->assign(array(
                    'packagesInfo' => $dispatchPoint,
                    'dispatchPoint' => $disPointApi,
                ));

                $html = $this->context->smarty->fetch(_PS_MODULE_DIR_ . 'inpost/views/templates/admin/manifest.tpl');


                InpostHelper::generateManifestPdf($html, $key);
                $files[] = _PS_MODULE_DIR_ . '/inpost/pdf/manifest' . $key . '.pdf';
            }
            if (!$toFile) {
                InpostHelper::mergePdf($files);
            } else {
                return $files;
            }

        }
    }

    public function orderCourier()
    {

        $packagesId = Tools::getValue('inpostLabelsBox');
        $packagesInfo = array();
        $packagesX_Border = array();
        $responseA = array();
        if (!$packagesId) {
            $this->html .= $this->displayError($this->l('Select parcels'));
            return false;
        } else {
            foreach ($packagesId as $packageId) {
                $packageD = InpostModel::findPackageByPackageId($packageId);
                if ($packageD['source_machine_id']) {
                  if ((int)$packageD['x_border'] === 1) {
                      $packageIds = $packageD['tracking_number'];
                  } else {
                      $packageIds = $packageD['parcel_no'];
                  }

                    $this->html .= $this->displayError(sprintf($this->l('The shipments %s sent with use of the parcel locker cannot
                        be picked up by the InPost courier, please delete the shipments from
                        the list and place the order once again.'), $packageIds));
                    return false;
                }
                if ((int)$packageD['x_border'] === 1) {
                    $packagesX_Border[$packageD['dispatch_point_id']][] = $packageD;
                } else {
                    $packagesInfo[$packageD['dispatch_point_id']][] = $packageD;
                }
            }

            foreach ($packagesInfo as $key => $dispatchPoint) {
                $disPoint = InpostDispatchPoints::getDispatchPointById($key);
                $parcelIds = array();
                foreach ($dispatchPoint as $packageInfo) {
                    $parcelIds[] = $packageInfo['parcel_no'];
                }

                $response = $this->api->dispatchOrders($disPoint['href'], $parcelIds);

                if (is_array($response)) {
                    $this->html .= $this->displayError($response[0]);

                } else {
                    InpostLabels::updateCourierId($parcelIds, $response->id);
                    InpostCouriers::saveNewCourier($response);
                }
                $responseA[] = $response;
            }

            foreach ($packagesX_Border as $key => $dispatchPoint) {
                $parcelIdsCross = array();
                foreach ($dispatchPoint as $packageInfo) {
                    $parcelIdsCross[] = $packageInfo['parcel_no'];
                }


                $response = $this->x_api->carrierPickups($key, $parcelIdsCross);

                if (is_array($response)) {
                    $this->html .= $this->displayError($response[0]);

                } else {
                    $responseShipments = $this->x_api->getCarrierPickupsData($response->id);
                    InpostLabels::updateCourierId($parcelIdsCross, $response->id);
                    InpostCouriers::saveNewCourierX($responseShipments, $response->id);

                }
                $responseA[] = $response;
            }
        }

        return $responseA;
    }

    public function menuNavigationAndSaveActions()
    {

        if (Tools::isSubmit('btnSubmit')) {
            $this->postValidation();
            if (!count($this->postErrors)) {
                $this->postProcess();
            } else {
                foreach ($this->postErrors as $err) {
                    if (!$this->error) {
                        $this->html .= $this->displayError($err);
                    }
                }
            }
        }

        if ((int)Tools::getValue('x_border_prices') === 1) {
            InpostModel::updateXPrices();
        }
        if ((Tools::isSubmit('submitBulkdownload_labelsinpostLabels')
            || Tools::isSubmit('download_labels'))
            && !Tools::isSubmit('submitResetinpostLabels')
            && Tools::getValue('submitFilterinpostLabels') == 0
            && !Tools::isSubmit('order_courier_confirm')) {
            $b = $this->labelsController->downloadStickers();
            if (!$b) {
                $this->html .= $this->displayError($this->l('Select labels'));
            }
        }
        if (Tools::isSubmit('download_manifests') || Tools::isSubmit('submitBulkdownload_manifestinpostCouriers')) {
            $files = array();
            $couriers = Tools::getValue('inpostCouriersBox');

            if (!$couriers) {
                $this->html .= $this->displayError($this->l('Select manifests'));
            }
            if ($couriers) {
                foreach ($couriers as $courier) {

                    $parcels = InpostLabels::getCourierLabels($courier);

                    $parcelIds = array();
                    foreach ($parcels as $parcel) {
                        $parcelIds[] = $parcel['package_id'];
                    }
                    $courierApi = InpostCouriers::getCourierByCourierApiId($courier);
                    if ($courierApi['x_border'] == 1) {
                        $a = $this->x_api->generateManifest($parcelIds);
                        $files[] = $a;

                    } else {
                        $filesR = $this->downloadManifestAction($parcelIds, true, $courier);
                        foreach ($filesR as $fileR) {
                            $files[] = $fileR;
                        }
                    }

                }

                InpostHelper::mergePdf($files);
            }
        }
        if (Tools::isSubmit('updateinpostCouriers')) {
          if (!Tools::getValue('courier_api_id')) {
              $this->html .= $this->displayError($this->l('Select manifests'));
          }
          $parcels = InpostLabels::getCourierLabels(Tools::getValue('courier_api_id'));

          $parcelIds = array();
          foreach ($parcels as $parcel) {
              $parcelIds[] = $parcel['package_id'];
          }
          $courierApi = InpostCouriers::getCourierByCourierApiId(Tools::getValue('courier_api_id'));
          if ($courierApi['x_border'] == 1) {
              $a = $this->x_api->generateManifest($parcelIds);
              $files[] = $a;

          } else {
              $filesR = $this->downloadManifestAction($parcelIds, true, Tools::getValue('courier_api_id'));
              foreach ($filesR as $fileR) {
                  $files[] = $fileR;
              }
          }

            InpostHelper::mergePdf($files);
        }

        if (Tools::isSubmit('order_courier') && Tools::isSubmit('order_courier_confirm')) {
            $responses = $this->orderCourier();
            foreach ($responses as $response) {
                if (!is_array($response)) {
                    Tools::redirectAdmin($this->module_url . '&couriers');
                }
            }
        }

        if (Tools::isSubmit('delete_dispatch_points') || Tools::isSubmit('deleteinpostDispatch')) {
            $deleteResult = InpostDispatchPoints::deleteDispatchPoints();
            if (is_array($deleteResult)) {
                $this->html .= $this->displayError($deleteResult[0]);
            }
        }

        if (Tools::isSubmit('cancel_parcel')) {
            $result = $this->packagesController->cancelParcels();

            if (isset($result[0])) {
                foreach ($result as $singleResult) {
                    if ($singleResult != 'error') {
                        $this->html .= $this->displayError($singleResult);
                    }
                }

            }

        }
        if (Tools::isSubmit('generate_sticker')) {
            $packages = $this->labelsController->generateSticker();

            if (isset($packages['error'])) {
                $this->html .= $this->displayError($packages[0]);
            }

            if ($packages && !isset($packages['error'])) {
                foreach ($packages as $packageSticker) {
                    $this->addTrackingNumber($packageSticker['order_id'], $packageSticker['package_id']);
                    $this->changeStatuses('', $packageSticker['order_id']);
                }
                Tools::redirectAdmin($this->module_url . '&packages');
            }
        }
        if (Tools::isSubmit('packages') && !Tools::isSubmit('updateinpost_packages')) {
            $this->context->smarty->assign(array(
                'filterLabelGenerated' => Tools::getValue('inpost_packagesFilter_label_generated')
            ));

            $this->html .= $this->packagesController->generateTablePackages();

            $this->html .= $this->packagesController->renderPackagesActions();

        } elseif (Tools::getValue('updateinpost_packages') === '') {
            $order_id = InpostModel::getOrderIdByParcelNo(Tools::getValue('parcel_no'));
            Tools::redirectAdmin(
                'index.php?tab=AdminOrders&redirect_from_packages=1&vieworder&show_parcel='
                . Tools::getValue('parcel_no') . '&id_order='
                . $order_id . '&token=' . Tools::getAdminTokenLite('AdminOrders')
            );
        } elseif (Tools::isSubmit('get_sticker')) {
            $this->downloadSticker(Tools::getValue('sticker_id'));
        } elseif (Tools::isSubmit('dispatch_points')) {
            $this->html .= $this->renderAddNewDispatchPoint();
            $this->html .= $this->dispatchController->generateTableDispatchPoint();
            $this->html .= $this->dispatchController->renderDispatchPointActions();
        } elseif (Tools::isSubmit('prices')) {
            $this->html .= $this->renderPricesForm();
            $this->html .= $this->renderCrossBorderPricesForm();
        } elseif (Tools::isSubmit('labels')) {
            $this->html .= $this->labelsController->generateTableLabels();
            $this->html .= $this->labelsController->renderLabelsActions();
        } elseif (Tools::isSubmit('couriers')) {
            $this->html .= $this->couriers->generateTableCouriers();
            $this->html .= $this->couriers->renderCouriersActions();
        } else {

            $this->html .= $this->renderConfigurationForm();
            if (version_compare(_PS_VERSION_, '1.6', '<')) {
                $this->html .= $this->context->smarty->fetch(INPOST_TPL_DIR . 'admin/1.5/crossborder/api_data.tpl');
            } else {
                $this->html .= $this->context->smarty->fetch(INPOST_TPL_DIR . 'admin/crossborder/api_data.tpl');
            }
        }
    }

    public function uninstall()
    {
        if (!InpostModel::dropConfiguration() || !InpostDeliveryModulesCore::deleteCarriers() || !parent::uninstall()) {
            return false;
        }
        return true;
    }

    public function install()
    {
        $tabNames = array();
        foreach (Language::getLanguages(false) as $lang) {
            $tabNames[$lang['id_lang']] = 'InPost';
        }
        $tab = new Tab();
        $tab->class_name = "Inpost";
        $tab->name = $tabNames;
        $tab->module = 'inpost';
        $tab->id_parent = 0;
        $tab->save();
        $createTable = InpostModel::createTables();
        $securekey = md5(_COOKIE_KEY_ . Configuration::get('PS_SHOP_NAME'));

        Db::getInstance()->execute("INSERT INTO " . _DB_PREFIX_ . "cronjobs
                                                ( `id_module`, `description`, `task`, `hour`, `day`, `month`, `day_of_week`, `updated_at`, `one_shot`, `active`, `id_shop`, `id_shop_group`)
                                                VALUES
                                                (null, 'Inpost Parcel status update', '" . Configuration::get('PS_SHOP_DOMAIN') . "/modules/inpost/inpost_cron.php?secure_key=" . $securekey . "', -1, -1, -1, -1, null, 0, 1, 1, 1);");

        Configuration::updateValue('INPOST_API_URL_POLAND', 'https://api-pl.easypack24.net/v4/');
        Configuration::updateValue('INPOST_API_URL_FRANCE', 'https://api-fr.easypack24.net/v4/');
        Configuration::updateValue('INPOST_API_URL_ITALY', 'https://api-it.easypack24.net/v4/');

        Configuration::updateValue('INPOST_PL_DESC_PL', "Dzięki Paczkomatom InPost możesz odebrać lub zwrócić paczkę. 98% paczek jest gotowych do odbioru już dzień po nadaniu. Aby odebrać paczkę wystarczy numer telefonu oraz kod odbioru otrzymany sms-em.");
        Configuration::updateValue('INPOST_PL_DESC_PLC', "Dzięki Paczkomatom możesz wygodnie odebrać paczkę za pobraniem. Każdy Paczkomat jest wyposażony w czytnik kart. Podczas składania zamówienia wybierz opcję Paczkomat za pobraniem.");
        Configuration::updateValue('X_BORDER_PL_DESC', "Z InPost możesz nadać także paczkę za granicę z odbiorem w Paczkomacie. Możesz śledzić jej status na każdym etapie doręczenia wchodząc na stronę www lub do Managera Paczek.");
        Configuration::updateValue('X_BORDER_COURER_PL_DESC', "Dzięki InPost możesz nadać paczkę na adres domowy do 15 krajów Unii Europejskiej. Możesz śledzić jej status na każdym etapie doręczenia wchodząc na stronę www lub do Managera Paczek");
        Configuration::updateValue('INPOST_FR_DESC_PL', "Consignes automatiques, disponibles 24h/24 et 7j/7 ou en horaires étendus. Récupérez votre colis en quelques secondes sans faire la queue.");

        Configuration::updateValue('INPOST_IT_DESC_PL', "Seleziona il Locker InPost come indirizzo di spedizione, controlla la mappa che si aprirà automaticamente e scegli il Locker InPost che ti è più comodo. Non appena il pacco sarà sarà riposto nel Locker, riceverai un sms con il codice PIN ed un codice QR che potrai usare alternativamente per ritirare il tuo acquisto.");
        Configuration::updateValue('INPOST_IT_DESC_PLC', "Opzione cash on delivery che consente il pagamento del prodotto acquistato online direttamente al locker attraverso il lettore bancomat (di cui tutte le macchine sono provviste).");
        Configuration::updateValue('INPOST_DEFAULT_SEND_METHOD', "0");
        Configuration::updateValue('EE_INPOST_DEFAULT_DISPATCH_POINT', "0");

        if (!Configuration::updateValue('INPOST_DEFAULT_PARCEL_SIZE', 'A')
            || !Configuration::updateValue('FIRST_DISPATCH_POINTS_SYNCHRONIZATION', false)
            || !$createTable
            || !parent::install()
            || !$this->installHooks()
        )
        {
            return false;
        }

        return true;
    }

    public function downloadSticker($id)
    {
        header('Content-Type: application/pdf');
        header("Content-disposition: attachment;filename='$id.pdf'");
        readfile(_PS_MODULE_DIR_ . "inpost/pdf/$id.pdf");

    }

    public function hookDisplayBackOfficeHeader($params)
    {
		$this->runCrons();
        $this->checkHooks();

        $id = Db::getInstance()->getValue('SELECT id_tab FROM ' . _DB_PREFIX_ . 'tab WHERE class_name = "Inpost" AND module = "inpost"', true);
        if (!$id) {
            $id = 0;
        }
        $this->context->smarty->assign(array(
            'id' => $id,
            'new_route' => Configuration::get('X_BORDER_NEW_ROUTE')
        ));
        return $this->context->smarty->fetch(INPOST_TPL_DIR . 'admin/script_menu.tpl');
    }

    public function disableOneDotFivePayments()
    {
        $carrierId = $this->context->cart->id_carrier;

        $inpostIdModules = InpostDeliveryModulesCore::getIdModules();
        $name = array_search($carrierId, $inpostIdModules);

        if ($paymentModules = Module::getPaymentModules()) {
            foreach ($paymentModules as $module) {
                if ($name === 'PARCELS_LOCKERS_COD') {
                    $paymentModuleConfig = Configuration::get('INPOST_PARCEL_LOCKERS_COD_PAYMENT_' . $module['name']);
                    if ((int)$paymentModuleConfig === 0) {
                        $module_instance = Module::getInstanceByName($module['name']);
                        $module_instance->currencies = array();
                    }

                }
                if ($name === 'PARCELS_LOCKERS') {
                    $paymentModuleConfig = Configuration::get('INPOST_PARCEL_LOCKERS_PAYMENT_' . $module['name']);
                    if ((int)$paymentModuleConfig === 0) {
                        $module_instance = Module::getInstanceByName($module['name']);
                        $module_instance->currencies = array();
                    }
                }

                if ($name === "CROSSBORDER_COURIER" || $name === "CROSSBORDER_PARCEL") {
                    $paymentModuleConfig = Configuration::get('INPOST_X_BORDER_PAYMENT_' . $module['name']);

                    if ((int)$paymentModuleConfig === 0) {
                        $module_instance = Module::getInstanceByName($module['name']);
                        $module_instance->currencies = array();
                    }

                }
            }
        }
    }
	public function hookDisplayPaymentTop($params) {
		$this -> hookPaymentTop($params);

        $validate = $this->validateOnePageCheckout();

        if($validate !== true && isset($validate['error'])) {
            return (new InpostHelper())->htmlAssign('hookPaymentHide');
        }

		return (new InpostHelper())->htmlAssign('hookPaymentShow');
	}

	static public function isCarrierAParcelLocker($carrierId) {
        $inpostIdModules = InpostDeliveryModulesCore::getIdModules();
        $name = array_search($carrierId, $inpostIdModules);
		return $name !== false && $name != 'CROSSBORDER_COURIER';
	}

    public function hookPaymentTop($params)
    {
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
			return $this->disableOneDotFivePayments();
        }
		 $carrierId = $this->context->cart->id_carrier;

        $inpostIdModules = InpostDeliveryModulesCore::getIdModules();
        $name = array_search($carrierId, $inpostIdModules);

        $cache_id = 'exceptionsCache';
        $exceptionsCache = (Cache::isStored($cache_id)) ? Cache::retrieve($cache_id) : array(); // existing cache

        $controller = Configuration::get('PS_ORDER_PROCESS_TYPE');
        if ((int)$controller === 0) {
            $controller = 'order';
        } else {
            $controller = 'orderopc';
        }

        $id_hook = Hook::getIdByName('displayPayment');

        if ($paymentModules = Module::getPaymentModules()) {
            foreach ($paymentModules as $module) {
                if ($name === 'PARCELS_LOCKERS_COD') {
                    $paymentModuleConfig = Configuration::get('INPOST_PARCEL_LOCKERS_COD_PAYMENT_' . $module['name']);
                    if ((int)$paymentModuleConfig === 0) {
                        $module_instance = Module::getInstanceByName($module['name']);
                        $key = (int)$id_hook . '-' . (int)$module_instance->id;
                        $exceptionsCache[$key][$this->context->shop->id][] = $controller;
                    }
                    Cache::store($cache_id, $exceptionsCache);
                }
                if ($name === 'PARCELS_LOCKERS') {
                    $paymentModuleConfig = Configuration::get('INPOST_PARCEL_LOCKERS_PAYMENT_' . $module['name']);
                    if ((int)$paymentModuleConfig === 0) {
                        $module_instance = Module::getInstanceByName($module['name']);
                        $key = (int)$id_hook . '-' . (int)$module_instance->id;
                        $exceptionsCache[$key][$this->context->shop->id][] = $controller;
                    }
                    Cache::store($cache_id, $exceptionsCache);
                }

                if ($name === "CROSSBORDER_COURIER" || $name === "CROSSBORDER_PARCEL") {
                    $paymentModuleConfig = Configuration::get('INPOST_X_BORDER_PAYMENT_' . $module['name']);

                    if ((int)$paymentModuleConfig === 0) {
                        $module_instance = Module::getInstanceByName($module['name']);
                        $key = (int)$id_hook . '-' . (int)$module_instance->id;
                        $exceptionsCache[$key][$this->context->shop->id][] = $controller;
                    }
                    Cache::store($cache_id, $exceptionsCache);
                }
            }
        }
    }

    public function getContent()
    {
		if(Tools::getValue('adminAjax'))
		{
			require_once 'inpost.ajax.php';
		}

        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            $this->context->controller->addCSS($this->_path . 'views/css/1.5/style.css');
            $this->context->controller->addCSS($this->_path . 'views/css/1.5/bootstrap.css');
            $this->context->controller->addJS($this->_path . 'views/js/1.5/script.js?v' . $this->version);
        } else {
            $this->context->controller->addJS($this->_path . 'views/js/script.js?v' . $this->version);
            $this->context->controller->addCSS($this->_path . 'views/css/style.css');
        }
        $this->defaultMachineId();

        if (Tools::isSubmit('btnSubmit') && !Tools::isSubmit('dispatch_points') && !Tools::isSubmit('priceRules') && !Tools::isSubmit('prices') && !Tools::isSubmit('packages')) {
            $this->postValidation();
            if (!count($this->postErrors)) {
                InpostModel::updatePrestashopConfigurationTable();
            }
        }

        $this->html .= $this->leadingExcerptAndMenu();
        $this->defaultMachineId();

        if ($this->postErrors) {
            foreach ($this->postErrors as $err) {
                $this->html .= $this->displayError($err);
            }
        }
        $this->menuNavigationAndSaveActions();
        $this->defaultMachineId();
        if (isset($this->errors[0])) {
            $br = (new InpostHelper())->htmlAssign('br');
            $this->html .= $this->displayError(implode($br, $this->errors));
        }

        return $this->html;
    }

    public function leadingExcerptAndMenu()
    {
        $api = new InpostConnector();
        $this->api->login = $api->login;
        $this->api->password = $api->password;
        $apiCustomer = $api->getCustomer();
        $menu = $this->inpost_form_creator->leadingAndMenu($this->module_url, (bool)!$apiCustomer);

        $this->context->smarty->assign(array(
                'menu_tabs' => $menu,
                'config_filled' => $this->checkConfigIsFilled(),
                'curl_exists' => function_exists('curl_init')
            ));

        if ($this->checkConfigIsFilled() == false) {
            $this->context->smarty->assign(array(
                'error' => $this->api->msg
            ));
        }
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            return $this->display(__FILE__, 'views/templates/admin/1.5/excerpt_and_menu.tpl');
        } else {
            return $this->display(__FILE__, 'views/templates/admin/excerpt_and_menu.tpl');
        }
    }


    public function renderAddNewDispatchPoint()
    {
        $fields_form = array();
        $fields_form[0] = $this->inpost_form_creator->dispatchPointForm();

        if (Tools::isSubmit('updateinpostDispatch') && Tools::getValue('id')) {
            $fields = InpostModel::getDispatchPointFieldsToEditValues(Tools::getValue('id'));
            $fields_form[0]['form']['legend']['title'] = $this->l('Edit dispatch point');
        } else {
            $fields = InpostModel::getDispatchPointFieldsValues();
        }

        $helper = new HelperForm();
        $helper->show_toolbar = false;

        $helper->default_form_language = $this->context->language->id;

        $helper->id = (int)Tools::getValue('id_carrier');
        $helper->submit_action = 'btnSubmit';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name . '&dispatch_points';
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->tpl_vars = array(
            'fields_value' => $fields,
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id
        );

        $html = $helper->generateForm($fields_form);

        return $html;
    }

    /**
     * Renders tab with available function
     */

    public function renderConfigurationForm()
    {
        $fields_form = array();
        $api = new InpostConnector();

        $fields_form[] = $this->inpost_form_creator->accountInfoForm();
        $apiCustomer = $api->getCustomer();
        if ($apiCustomer) {
            $fields_form[] = $this->inpost_form_creator->availableServicesForm();
            $fields_form[] = $this->inpost_form_creator->defaultParcelSizeForm();
            $fields_form[] = $this->inpost_form_creator->defaultOrderStatusForm();
        }

        $helper = new HelperForm();
        $helper->show_toolbar = false;

        $helper->default_form_language = $this->context->language->id;

        $helper->id = (int)Tools::getValue('id_carrier');
        $helper->submit_action = 'btnSubmit';
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            $helper->currentIndex = $this->context->link->getAdminLink('adminmodules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
        } else {
            $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
        }


        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->tpl_vars = array(
            'fields_value' => InpostModel::getConfigFieldsValues(),
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id
        );


        $html = $helper->generateForm($fields_form);

        if ($apiCustomer) {
            $html .= $this->inpost_form_creator->renderSenderAddressForm();
        }
        return $html;
    }

    public function renderPricesForm()
    {
        if ($this->api->getCustomer()) {
            $html = $this->inpost_form_creator->loadPriceRules();
        }
        return $html;
    }

    public function renderCrossBorderPricesForm()
    {
        return $this->inpost_form_creator->loadXBorderPriceRules();
    }

    /**
     * save configuration
     * Ta funkcja ma zapisac cala zakladke konfiguracyjna
     */
    private function postProcess()
    {

        if (Tools::isSubmit('dispatch_points')) {
            if (Tools::getValue('DISPATCH_HREF')) {
                $result = $this->api->updateUserDispatchPoint();
                if (is_array($result)) {
                    $this->html .= $this->displayError($result[0]);
                } else {
                    InpostModel::updateDispatchPoint($result);
                }

            } else {
                $result = $this->api->createNewUserDispatchPoint();
                if (is_array($result)) {
                    unset($result['error']);
                    $br = (new InpostHelper())->htmlAssign('br');
                    $this->html .= $this->displayError(implode($br, $result));
                } else {
                    InpostModel::saveDispatchPoint($result);
                    Tools::redirectAdmin($this->module_url . '&dispatch_points');
                }
            }
        }
        if (Tools::isSubmit('priceRules')) {
            $a = InpostModel::checkTaxExist(Tools::getValue('tax_shipping_prices'));

            if (!$a && (int)Tools::getValue('tax_shipping_prices') != -1) {
                $this->html .= $this->displayError('Selected tax not exists. Tax not saved');
            } elseif ((int)Tools::getValue('tax_shipping_prices') == -1) {
                Configuration::updateValue('SHIPPING_TAX_INPOST', 0);
                InpostDeliveryModulesCore::updateTaxGroupForInpostCarriers(0);
            } else {

                Configuration::updateValue('SHIPPING_TAX_INPOST', Tools::getValue('tax_shipping_prices'));
                InpostDeliveryModulesCore::updateTaxGroupForInpostCarriers(Tools::getValue('tax_shipping_prices'));
            }


            InpostModel::saveFreeShipping();
            //clear price table before save
            InpostModel::removeAllData();
            //PARCELS LOCKERS
            InpostModel::saveParcelsLockersPriceRules();
            InpostModel::saveParcelsLockersWeightRules();
            InpostModel::saveParcelsLockersFlatPrice();
            //PARCELS LOCKERS COD
            InpostModel::saveParcelsLockersCodPriceRules();
            InpostModel::saveParcelsLockersCodWeightRules();
            InpostModel::saveParcelsLockersCodFlatPrice();
            InpostModel::saveParcelsLockersCartValuePercent();
        }

        if (Tools::isSubmit('btnSubmit') && !Tools::isSubmit('dispatch_points') && !Tools::isSubmit('priceRules')) {
			Configuration::updateValue('INPOST_DEFAULT_SEND_METHOD', Tools::getValue('INPOST_DEFAULT_SEND_METHOD'));
			Configuration::updateValue('EE_INPOST_DEFAULT_DISPATCH_POINT', Tools::getValue('EE_INPOST_DEFAULT_DISPATCH_POINT'));

            $x_border_conn = new CrossBorderConnector();
            $token = $x_border_conn->getToken();
            $this->synchronizePricesCross();
            if ($token && !property_exists($token, 'access_token')) {
                $_POST['INPOST_AVAILABLE_SERVICES_CROSSBORDER'] = 0;
            } else {
                InpostDeliveryModulesCore::createCrossBorderParcelCarriers();
                InpostDeliveryModulesCore::createCrossBorderCourierCarriers();
            }
            InpostModel::updatePrestashopConfigurationTable();

            InpostModel::saveSenderData();
            //AVAILABLE SERVICES
            InpostModel::saveAvailableFunctions();
            //After generation
            InpostModel::saveStatuses();

//            if (Configuration::get('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS_COD')) {
//
////                $response = $this->api->updateCustomer(['iban' => Configuration::get('INPOST_PARCERLS_LOCKERS_COD_IBAN')]);
//
//                if (is_array($response) && isset($response['error']) && $response['error'] == 1) {
//                    unset($response['error']);
//                    $this->html .= $this->displayError(implode('<br />', $response));
//                }
//            }
            $api = new InpostConnector();
            $response = $api->getCustomer();

            if ($response) {
                if (Configuration::get('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS')) {
                    InpostDeliveryModulesCore::createParcelLockersCarrier();
                }
                if (Configuration::get('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS_COD')) {
                    InpostDeliveryModulesCore::createParcelLockersCodCarrier();
                }
            } else {
                Tools::redirectAdmin($this->module_url . '&configuration');
            }
            $this->defaultMachineId();
            if (!isset($this->error) && $response) {
                $this->html .= $this->displayConfirmation($this->l('Settings updated'));
            }
        }
    }


    /**
     * walidation all config forms
     */
    private function postValidation()
    {

        if (Tools::isSubmit('btnSubmit') && !Tools::isSubmit('dispatch_points') && !Tools::isSubmit('priceRules')) {

            if (!Tools::getValue('INPOST_LOGIN') && !Configuration::get('INPOST_LOGIN')) {
                $this->postErrors[] = $this->l('Login is required.');
            } elseif (!Tools::getValue('INPOST_COUNTRY') && !Configuration::get('INPOST_COUNTRY')) {
                $this->postErrors[] = $this->l('Country is required.');
            }
            $api = new InpostConnector();
            $api->login = Tools::getValue('INPOST_LOGIN');
            if (Tools::getValue('INPOST_PASSWOWRD') !== '****************') {
                ;
            }
        }
    }

    /**
     * Check if the configuration is filled, if not it displays a error
     */
    private function checkConfigIsFilled()
    {
        $api = new InpostConnector();
        $api = $api->getCustomer();

        if (!Configuration::get('INPOST_LOGIN') && !Configuration::get('INPOST_PASSWORD') || (bool)$api === false) {
            return false;
        }
        return true;
    }

    public function hookActionValidateOrder($params)
    {
        InpostModel::updateParcelLockerToOrder([
            'order_id' => $params['order']->id,
            'cart_id' => $params['cart']->id
        ]);

    }

    public function hookDisplayBeforeCarrier($params)
    {
        $cart = $params['cart'];

        if(Configuration::get('PS_ORDER_PROCESS_TYPE') == 1 && !$cart->id_address_delivery) {
            return $this->hookDisplayCarrierList($params);
        }
    }

    public function hookDisplayCarrierList($params)
    {
        $phone_no = null;
        if(isset($params['address'])) {
            if ($params['address']->phone_mobile) {
                $phone_no = $params['address']->phone_mobile;
            } else {
                $phone_no = $params['address']->phone;
            }
        }

        $html = '';
        if (Configuration::get('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS')
            || Configuration::get('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS_COD')) {
            $cart_id = $params['cart']->id;
            $selectedMachine = InpostModel::getSelectedMachineInOrder($cart_id);
            $phone_order = InpostModel::getPhoneOrder($cart_id);
            if ($selectedMachine) {
                $selectedMachine = $this->api->getMachine($selectedMachine);
            }

            if ($selectedMachine && property_exists($selectedMachine, 'status_code')) {
                $selectedMachine = false;
            }

            $this->context->controller->addCSS($this->_path . 'views/css/front.css');
            if (version_compare(_PS_VERSION_, '1.6', '<')) {
                $jsFile = $this->_path . 'views/js/1.5/front.js?v' . $this->version;
                $this->context->controller->addJs($this->_path . 'views/js/1.5/front.js?v' . $this->version);
            } else {
                $jsFile = $this->_path . 'views/js/front.js';
                $this->context->controller->addJs($this->_path . 'views/js/front.js?v' . $this->version);
            }
            $this->context->smarty->assign(array(
                'modulesId' => InpostDeliveryModulesCore::getIdModules(),
                'selected_machine' => $selectedMachine ? $selectedMachine : false,
                'cityUser' => isset($params['address']) ? $params['address']->city : null,
                'phone_no' => isset($phone_order) && $phone_order  ? $phone_order : $phone_no,
                'errors_inpost' => $this->context->cookie->redirect_errors,
                'descriptions' => InpostDeliveryModulesCore::getModulesDescriptions(),
                'PS_ORDER_PROCESS_TYPE' => Configuration::get('PS_ORDER_PROCESS_TYPE'),
                'INPOST_COUNTRY' => Configuration::get('INPOST_COUNTRY'),
                'jsFile' => $this->getBaseURL(false) .  $jsFile,
                'ajaxScript' => $this->getBaseURL(false) . $this->_path . 'inpost.ajax.php'
            ));

            $html .= $this->context->smarty->fetch(INPOST_TPL_DIR . 'hook/select_parcel.tpl');
        }

        if (Configuration::get('INPOST_AVAILABLE_SERVICES_CROSSBORDER')) {
            $this->context->controller->addJs("http://widget-xborder-inpost.sheepla.com/js/SheeplaLib.js");
            $this->context->controller->addCSS("http://widget-xborder-inpost.sheepla.com/css/SheeplaCrossBorder.css");

            $cart_id = $params['cart']->id;
            $selectedMachine = InpostModel::getSelectedMachineInOrder($cart_id);

            if ($selectedMachine) {
                $selectedMachine = $this->x_api->getPop($selectedMachine);
            }

            if (is_array($selectedMachine) && $selectedMachine && ($selectedMachine[0]->message === 'XBorderV1.PopNotFound' || property_exists($selectedMachine[0], 'status_code'))) {
                $selectedMachine = false;
            }

            $isoCode = InpostModel::getCountryIsoCodeById($params['address']->id_country);

			$geoWidget = null;

			if(defined('CrossBorderConnector::INPOST_GEOWIDGET_' . $isoCode)) {
				$geoWidget = constant('CrossBorderConnector::INPOST_GEOWIDGET_' . $isoCode);
			}

            $this->context->controller->addCSS($this->_path . 'views/css/front.css');
            if (version_compare(_PS_VERSION_, '1.6', '<')) {
                $jsCrossFile = $this->_path . 'views/js/1.5/front_cross.js?v' . $this->version;
                $this->context->controller->addJs($this->_path . 'views/js/1.5/front_cross.js?v' . $this->version);
            } else {
                $jsCrossFile = $this->_path . 'views/js/front_cross.js';
                $this->context->controller->addJs($this->_path . 'views/js/front_cross.js?v' . $this->version);
            }
            $this->context->smarty->assign(array(
                'modulesId' => InpostDeliveryModulesCore::getIdModules(),
                'selected_machine_cross' => $selectedMachine ? $selectedMachine : false,
                'cityUser' => $params['address']->city,
                'geowidget_url' => $geoWidget,
                'countryUser' => $isoCode,
                'phone_no' => $phone_no,
                'errors_inpost' => $this->context->cookie->redirect_errors,
                'descriptions' => InpostDeliveryModulesCore::getModulesDescriptions(),
				'PS_ORDER_PROCESS_TYPE' => Configuration::get('PS_ORDER_PROCESS_TYPE'),
                'jsFile' => $jsCrossFile,
				'ajaxScript' => $this->getBaseURL(false) . $this->_path . 'inpost.ajax.php'
			));


            $html .= $this->context->smarty->fetch(INPOST_TPL_DIR . 'hook/select_parcel_cross.tpl');
        }
        unset($this->context->cookie->redirect_errors);
        return $html;

    }


    public function hookDisplayAdminOrder($params)
    {
        $this->context->controller->addCSS($this->_path . 'views/css/admin_hook.css');
        if ($this->checkConfigIsFilled() == false) {
            $this->context->smarty->assign(array(
                'config_not_filled' => true
            ));
            return $this->context->smarty->fetch(INPOST_TPL_DIR . 'hook/order.tpl');
        } else {
            $this->api = new InpostConnector();

            $errors = array();
            $order = new Order((int)$params['id_order']);
            $sizes = array(
                'height' => 0,
                'width' => 0,
                'length' => 0,
            );

            foreach ($order->getProducts() as $product) {
                $sizes['height'] += $product['height'];
                $sizes['width'] += $product['width'];
                $sizes['length'] += $product['depth'];
            }

            $packages = InpostModel::findPackagesByOrderId($params['id_order']);

            $package = false;
            $insurance_amount = false;
            $comments = false;
            if (Tools::isSubmit('show_parcel')) {
                if (Tools::getValue('show_parcel')) {
                    $customer_addresses = array();
                    $package = InpostModel::findPackageByPackageId(Tools::getValue('show_parcel'));

                    $customer_addresses[0] = array(
                        'firstname' => $package['receiver_firstname'],
                        'lastname' => $package['receiver_lastname'],
                        'postcode' => $package['receiver_post_code'],
                        'city' => $package['receiver_city'],
                        'email' => $package['receiver_email'],
                        'phone' => $package['receiver_phone'],
                        'phone_mobile' => $package['receiver_phone'],
                        'target_machine_id' => $package['target_machine_id'],
                        'company' => $package['receiver_company_name'],
                        'parcel_locker' => $package['target_machine_id'],
                        'street' => $package['receiver_street'],
                        'building_no' => $package['receiver_building_no'],
                        'flat_no' => $package['receiver_flat_no'],
                        'id_customer' => $order->id_customer,
                        'id_country' => $package['receiver_country'],

                    );

                    $comments = $package['additional1'];
                    $insurance_amount = (int)$package['insurance_amount'];

                    $sender = array(
                        'INPOST_SENDER_STREET' => $package['sender_street'],
                        'INPOST_SENDER_BUILDING_NO' => $package['sender_building_no'],
                        'INPOST_SENDER_FLAT_NO' => $package['sender_flat_no'],
                        'INPOST_SENDER_POSTCODE' => $package['sender_post_code'],
                        'INPOST_SENDER_CITY' => $package['sender_city'],
                        'INPOST_SENDER_PHONE' => $package['sender_phone'],
                        'INPOST_SENDER_EMAIL' => $package['sender_email'],
                        'INPOST_SENDER_FIRSTNAME' => $package['sender_first_name'],
                        'INPOST_SENDER_LASTNAME' => $package['sender_last_name'],
                        'INPOST_SENDER_COMPANY_NAME' => $package['sender_company_name'],
                        'INPOST_SENDER_PARCEL_LOCKER' => $package['source_machine_id'],
                        'INPOST_SENDER_DISPATCH_POINT' => $package['dispatch_point_id'] != -1 ? $package['dispatch_point_id'] : '',
                        'INPOST_CUSTOMER_REFERENCE' => $package['customer_reference'],
                        'INPOST_SENDER_COUNTRY' => constant('InpostConnector::INPOST_COUNTRY_' . Configuration::get('INPOST_COUNTRY'))
                    );
                }


            } else {
                $customer = new Customer((int)$order->id_customer);
                $customer_addresses = $customer->getAddresses($this->context->language->id);
                foreach ($customer_addresses as &$customer_addr) {

                    $splitAddr = InpostModel::splitAddress($customer_addr['address1'].' '.$customer_addr['address2'], '');

                    $customer_addr['street'] = $splitAddr['street'];
                    $customer_addr['building_no'] = $splitAddr['building_no'];
                    $customer_addr['flat_no'] = $splitAddr['flat_no'];
                    $customer_addr['email'] = $customer->email;
                    $phone = InpostModel::getCustomerPhone($params['id_order']);

                    if ($phone) {
                        $customer_addr['phone'] = $phone;
                        $customer_addr['phone_mobile'] = $phone;
                    }
                }

                $sender = InpostModel::getSenderData($params['id_order']);

            }

            if (Tools::isSubmit('cancel_parcel') && Tools::getValue('cancel_parcel')) {
                $api = new InpostConnector();
                $response = $api->cancelParcel(Tools::getValue('cancel_parcel'));
                if (property_exists($response, 'status_code')) {
                    if ((int)$response->status_code === 422) {
                        $errors[] = $response->message;
                    }
                } elseif (property_exists($response, 'status')) {
                    if ($response->status !== 'cancelled') {
                        $errors[] = $this->l('Parcel can not be cancelled');
                    } else {
                        InpostPackages::deletePackage($response->id);
                    }
                }
            }

            $priceList = $this->api->getPriceList();

            $address_delivery = new Address((int)$order->id_address_delivery);
            $iso_code = InpostModel::getCountryIsoCodeById($address_delivery->id_country);


            $shipping = $order->getShipping()[0]['id_carrier'];
            if ((int)InpostModel::checkIsXBorderOrder($params['id_order'])
                || array_search($shipping, InpostDeliveryModulesCore::getIdModules()) == 'CROSSBORDER_COURIER') {
                $x_border = true;
                $shippingAddress = new Address($order->id_address_invoice);
                $countryS = InpostModel::getCountryIsoCodeById($shippingAddress->id_country);
                $insurances = array();
                if (InpostModel::getSelectedParcel($params['id_order'])) {
                    $a = Db::getInstance()->getRow('SELECT *
                                                    FROM ' . _DB_PREFIX_ . 'x_border_types
                                                    WHERE to_country ="' . $countryS . '"
                                                    AND from_country = "' . $sender['INPOST_SENDER_COUNTRY'] . '"
                                                     AND recipient_method = "ToParcelMachine"');
                } else {
                    $a = Db::getInstance()->getRow('SELECT *
                                                    FROM ' . _DB_PREFIX_ . 'x_border_types
                                                    WHERE to_country ="' . $countryS . '"
                                                    AND from_country = "' . $sender['INPOST_SENDER_COUNTRY'] . '"
                                                     AND recipient_method = "ToDoor"');
                }

                if ($a) {
                    $insurances = array(
                        '0' => (object)array(
                            'level' => (float)$a['insurance_amount'],
                            'price' => (float)$a['insurance_cost_amount'],
                            'currency' => $a['insurance_currency']
                        )
                    );
                }
            } else {
                if ($priceList !== null && isset($priceList->insurance)) {
                    $insurances = $priceList->insurance;
                } else {
                    $insurances = '';
                }

                $x_border = false;
            }
            if ((int)$this->api->country === 1) {
                $currency = 'PLN';
            } else {
                $currency = 'EUR';
            }
            if (Tools::strtoupper(Configuration::get('PS_WEIGHT_UNIT')) != 'KG') {
                if (Tools::strtoupper(Configuration::get('PS_WEIGHT_UNIT')) == 'LB'
                    || Tools::strtoupper(Configuration::get('PS_WEIGHT_UNIT')) == 'LBS') {
                    $totalWeight = $order->getTotalWeight();
                    $totalWeight = $totalWeight * 0.453592338;
                    $selectedUnit = 'kg';
                }
                if (Tools::strtoupper(Configuration::get('PS_WEIGHT_UNIT')) == 'G') {
                    $totalWeight = $order->getTotalWeight();
                    $selectedUnit = 'g';
                }
            } else {
                $totalWeight = $order->getTotalWeight();
                $selectedUnit = 'kg';
            }

            $this->context->smarty->assign(array(
                'customer_addresses' => $customer_addresses,
                'order' => $order,
                'sender' => $sender,
                'packages' => $packages,
                'size_parcel' => $package ? $package['size'] : Configuration::get('INPOST_DEFAULT_PARCEL_SIZE'),
                'show_parcel' => Tools::getValue('show_parcel') ? Tools::getValue('show_parcel') : false,
                'package_db' => $package,
                'errors' => $errors,
                'add_new_package' => Tools::isSubmit('add_new_package'),
                'selected_parcel' => InpostModel::getSelectedParcel($params['id_order']),
                'x_border' => $x_border,
                'insurances' => $insurances,
                'shipping_cod' => array_search($shipping, InpostDeliveryModulesCore::getIdModules()),
                'dispatch_points' => InpostDispatchPoints::getDispatchPointForCourierOrder(),
                'countries' => Country::getCountries($this->context->language->id),
                'comments' => $comments,
                'insurance_amount' => $insurance_amount,
                'currency' => $currency,
                'geowidget_receiver_url' => self::geoWidgetByIsoCode($iso_code),
                'sizes' => $sizes,
                'total_weight' => $totalWeight,
                'selected_unit' => $selectedUnit,
				'INPOST_DEFAULT_SEND_METHOD' => Configuration::get('INPOST_DEFAULT_SEND_METHOD'),
				'EE_INPOST_DEFAULT_DISPATCH_POINT' => Configuration::get('EE_INPOST_DEFAULT_DISPATCH_POINT')
            ));
            $this->context->controller->addJs("http://widget-xborder-inpost.sheepla.com/js/SheeplaLib.js");
            $this->context->controller->addCSS("http://widget-xborder-inpost.sheepla.com/css/SheeplaCrossBorder.css");
            $this->context->controller->addJS($this->_path . 'views/js/admin_hook.js?v' . $this->version);

            if (version_compare(_PS_VERSION_, '1.6', '<')) {
                $this->context->controller->addCSS($this->_path . 'views/css/1.5/bootstrap_order.css');
                return $this->context->smarty->fetch(INPOST_TPL_DIR . 'hook/1.5/order.tpl');
            } else {
                return $this->context->smarty->fetch(INPOST_TPL_DIR . 'hook/order.tpl');
            }
        }
    }

    public static function geoWidgetByIsoCode($iso_code)
    {
        switch ($iso_code) {
            case 'PL':
                return 'https://geowidget.inpost.pl/';
            case 'CZ':
                return 'https://geowidget-cz.easypack24.net/';
            case 'SK':
                return 'https://geowidget-sk.easypack24.net/';
            case 'FR':
                return 'https://geowidget-fr.easypack24.net/';
            case 'IT':
                return 'https://geowidget-it.easypack24.net/';
            default:
                return 'https://geowidget.inpost.pl/';

        }

    }

    /**
     * @param $address_id
     * @param $order_id
     * @return array
     * Used in admin order to change user address
     */
    public function getUserAddress($address_id)
    {
        return InpostModel::getUserAddress($address_id);
    }

    public function getOrderShippingCost($cart, $shipping_cost)
    {
        $country_id = null;
        $address_id = null;
        if((int)$cart->id_address_delivery > 0 && ($address = new Address($cart->id_address_delivery))) {
            $country_id = $address->id_country;
            $address_id = $address->id;
        } else {
            $country_id = Context::getContext()->country->id;
        }

        if ($country_id) {
            $countryIsoCode = Db::getInstance()->getValue('SELECT iso_code
                                                            FROM ' . _DB_PREFIX_ . 'country
                                                            WHERE id_country = ' . $country_id);

            $apiCode = constant('InpostConnector::INPOST_COUNTRY_' . Configuration::get('INPOST_COUNTRY'));
            //if ($apiCode !== $countryIsoCode)
            //return false;
            $taxCalculationMethod = Group::getPriceDisplayMethod((int)Group::getCurrent()->id);

            $useTax = !($taxCalculationMethod == PS_TAX_EXC);
            $cartTotalCost = $cart->getOrderTotal($useTax, Cart::ONLY_PRODUCTS);

            $cartTotalWeight = $cart->getTotalWeight();

            $module = InpostModel::getMethodByCarrierId($this->id_carrier);

            switch ($module['module_name']) {
                case 'PARCELS_LOCKERS':
                    if ($apiCode !== $countryIsoCode) {
                        return false;
                    }
                    return InpostDeliveryModulesCore::calculateParcelsLockersPrice(
                        $cartTotalCost, $cartTotalWeight, $cart->id_currency, $address_id);

                case 'PARCELS_LOCKERS_COD':
                    if ($apiCode !== $countryIsoCode) {
                        return false;
                    }
                    return InpostDeliveryModulesCore::calculateParcelsLockersCodPrice(
                        $cartTotalCost, $cartTotalWeight, $cart->id_currency, $address_id);

                case 'CROSSBORDER_COURIER':
                    return InpostDeliveryModulesCore::calculateCrossBorderCourierPrice(
                        $cartTotalWeight, $countryIsoCode, $cart->id_currency, $address_id);

                case 'CROSSBORDER_PARCEL':
                    return InpostDeliveryModulesCore::calculateCrossBorderParcelPrice(
                        $cartTotalWeight, $countryIsoCode, $cart->id_currency, $address_id);
            }

            return false;
        }
        return false;
    }

    public function getOrderShippingCostExternal($params)
    {
        return false;
    }

    public function createInpostCarrier()
    {
        InpostDeliveryModulesCore::createParcelLockersCarrier();
        InpostDeliveryModulesCore::createParcelLockersCodCarrier();
    }

    public function hookUpdateCarrier($params)
    {

        Configuration::updateValue('SHIPPING_TAX_INPOST', $params['carrier']->id_tax_rules_group);
        $id_reference = (int)InpostDeliveryModulesCore::getReferenceByIdCarrier((int)$params['id_carrier']);
        $id_carrier = (int)$params['carrier']->id;

        $carrier = new Carrier($id_carrier);

        InpostModel::updateOldCarrier($id_carrier, $id_reference);

        $groups = GroupCore::getGroups($this->context->language->id);
        $zones = ZoneCore::getZones();
        $groupsForCarrier = [];
        foreach ($groups as $group) {
            $groupsForCarrier[] = $group['id_group'];
        }
        foreach ($zones as $zone) {
            $carrier->addZone($zone['id_zone']);
        }
        $carrier->setGroups($groupsForCarrier);
#        $rangePrice = new RangePriceCore();
#        $rangePrice->id_carrier = $carrier->id;
#        $rangePrice->delimiter1 = 0.00;
#        $rangePrice->delimiter2 = 999999.00;
#        $rangePrice->add(true, true);


    }

    /**
     * @param $paramspaymenttype przyjąć może jedną z trzech wartości:
     * 0 – brak możliwości zapłaty za przesyłkę
     * 1 – możliwość zapłaty za przesyłkę gotówką
     * 2 – możliwość zapłaty za przesyłkę kartą płatniczą
     * 3 – możliwość zapłaty za przesyłkę gotówką bądź kartą płatniczą
     */
    public function hookActionCarrierProcess($params)
    {
        if ((int)Configuration::get('PS_ORDER_PROCESS_TYPE') === 0)
        {
            $carriers = InpostDeliveryModulesCore::getIdModules();

            if (in_array($params['cart']->id_carrier, $carriers)) {
                $phone_no = Tools::getValue('phone_parcel_locker');
                $phone_no_cross = Tools::getValue('phone_parcel_cross');
                $address = new Address($params['cart']->id_address_delivery);

                if (!$phone_no) {
                    $phone_no = $address->phone ? $address->phone : $address->phone_mobile;
                }

                if (!$phone_no_cross) {
                    $phone_no_cross = $address->phone ? $address->phone : $address->phone_mobile;
                }

                $phonePattern = '/[^0-9\+]/';
                $phone_no = preg_replace($phonePattern, '', $phone_no);
                $phone_no_cross = preg_replace($phonePattern, '', $phone_no_cross);

                $inpostCountry = Configuration::get('INPOST_COUNTRY');

                if ($inpostCountry == 1) {
                    $preg_phone = preg_match(self::POLAND_PHONE, $phone_no, $matches);
                } elseif ($inpostCountry == 2) {
                    $preg_phone = preg_match(self::FRANCE_PHONE, $phone_no, $matches);
                } elseif ($inpostCountry == 3) {
                    $preg_phone = preg_match(self::ITALY_PHONE, $phone_no, $matches);
                }

                $parcel_locker = Tools::getValue('selected_parcel');
                $parcel_locker_cross = Tools::getValue('sheepla-widget-data');
                if ($params['cart']->id_carrier == $carriers['CROSSBORDER_COURIER']) {
                    $parcel_locker_cross = null;
                    $parcel_locker = null;
                }

                if (!$parcel_locker && !$parcel_locker_cross && $carriers['CROSSBORDER_COURIER'] != $params['cart']->id_carrier) {
                    $this->context->cookie->__set('redirect_errors', Tools::displayError($this->l('Select machine')));
                    Tools::redirect('index.php?controller=order&step=2');
                }

                if ($parcel_locker && !$preg_phone) {

                    $fields = array(
                        'parcel_locker' => $parcel_locker,
                        'cart_id' => $params['cart']->id,
                        'phone_no' => $phone_no
                    );

                    InpostModel::connectParcelLockerWithCart($fields);
                    $this->context->cookie->__set('redirect_errors', Tools::displayError($this->l('Phone number is invalid.')));
                    Tools::redirect('index.php?controller=order&step=2');
                }

                if ($carriers['CROSSBORDER_COURIER'] == $params['cart']->id_carrier) {
                    $isoCodeCustomerCountry = InpostModel::getCountryIsoCodeById($address->id_country);

                    $addressFormats = $this->x_api->getAddressFormat($isoCodeCustomerCountry);

                    if ($addressFormats && (!is_object($addressFormats) || !property_exists($addressFormats, 'status_code'))) {
                        $regexPhone = $addressFormats[0]->phone->regex;

                        $preg_phone_cross = preg_match('/'.$regexPhone.'/', $phone_no_cross, $matches);
                        if (!$preg_phone_cross) {

                            $this->context->cookie->__set('redirect_errors', Tools::displayError($this->l('Phone number is invalid.')));
                            Tools::redirect('index.php?controller=order&step=2');
                        }
                    }


                }
                if ($parcel_locker) {
                    $response = $this->api->getMachine($parcel_locker);
                    if ($response) {
                        //if selected cod payment and parcel lockers payment type cod is not available
                        if ((int)$params['cart']->id_carrier === (int)$carriers['PARCELS_LOCKERS_COD'] && $response) {
                            if ((int)$response->payment_type === 0) {
                                $this->context->cookie->__set('redirect_errors', Tools::displayError($this->l('COD is unavailable in this parcel locker.')));
                                Tools::redirect('index.php?controller=order&step=2');
                            }
                        }
                        if ((property_exists($response, 'status_code') || empty($parcel_locker)) && $response) {
                            $this->context->cookie->__set('redirect_errors', Tools::displayError($this->l('Parcel locker not found.')));
                            Tools::redirect('index.php?controller=order&step=2');
                        }
                        $fields = array(
                            'parcel_locker' => $parcel_locker,
                            'cart_id' => $params['cart']->id,
                            'phone_no' => $phone_no
                        );
                        InpostModel::connectParcelLockerWithCart($fields);
                    } else {
                        $_POST['selected_parcel'] = '';
                    }
                }
                if ($parcel_locker_cross || $params['cart']->id_carrier == $carriers['CROSSBORDER_COURIER']) {
                    $fields = array(
                        'parcel_locker' => $parcel_locker_cross,
                        'cart_id' => $params['cart']->id,
                        'x_border' => true,
                        'phone_no' => $phone_no
                    );
                    InpostModel::connectParcelLockerWithCart($fields);
                }

            }
        }
    }

    public function changeStatuses($package, $order_id)
    {
        if (Configuration::get('INPOST_DEFAULT_STATUS_AFTER_LABEL_GENERATION')) {
            $order = new Order($order_id);
            $order_state = new OrderState(Configuration::get('INPOST_DEFAULT_STATUS_AFTER_LABEL_GENERATION'));
            $current_order_state = $order->getCurrentOrderState();

            if ($current_order_state->id != $order_state->id) {
                $history = new OrderHistory();
                $history->id_order = $order->id;

                $history->id_employee = 1;

                $use_existings_payment = false;
                if (!$order->hasInvoice()) {
                    $use_existings_payment = true;
                }

                $history->changeIdOrderState(Configuration::get('INPOST_DEFAULT_STATUS_AFTER_LABEL_GENERATION'), $order, $use_existings_payment);
                $history->addWithemail();

            }

            //$this->addTrackingNumber($order_id, $package->id);
        }
    }



    public function addTrackingNumber($id_order, $tracking_number)
    {
        $order = new Order((int)$id_order);

        if(!$order) {
            return false;
        }

        $orderCarrierId = $this->getIdOrderCarrier($order);

        $order_carrier = new OrderCarrier($orderCarrierId);

        $order->shipping_number = $tracking_number;
        $order->update();

        $order_carrier->tracking_number = $tracking_number;
        if ($order_carrier->update()) {
            $customer = new Customer((int)$order->id_customer);
            $carrier = new Carrier((int)$order->id_carrier, $order->id_lang);
            if (!Validate::isLoadedObject($customer)) {
                self::$errors[] = $this->l('Can\'t load Customer object');
                return false;
            }
            if (!Validate::isLoadedObject($carrier)) {
                return false;
            }
            $templateVars = array(
                '{followup}' => str_replace('@', $order->shipping_number, $carrier->url),
                '{firstname}' => $customer->firstname,
                '{lastname}' => $customer->lastname,
                '{id_order}' => $order->id,
                '{shipping_number}' => $order->shipping_number,
                '{order_name}' => $order->getUniqReference()
            );

            if (@Mail::Send((int)$order->id_lang, 'in_transit', Mail::l('Package in transit', (int)$order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int)$order->id_shop)) {
                Hook::exec('actionAdminOrdersTrackingNumberUpdate', array(
                    'order' => $order,
                    'customer' => $customer,
                    'carrier' => $carrier
                ));
                return true;
            } else {
                $this->addFlashError($this->l('An error occurred while sending an email to the customer.'));
                return true;
            }
        } else {
            self::$errors[] = $this->l('The order carrier cannot be updated.');
            return false;
        }

    }

    public function defaultMachineId()
    {

        if (((int)Tools::getValue("INPOST_COUNTRY") === 1 || Configuration::get('INPOST_COUNTRY') == 1) && !Configuration::get('INPOST_PARCERLS_LOCKERS_RETURNS_DESCRIPTION'))
        {
            Configuration::updateValue('INPOST_PARCERLS_LOCKERS_RETURNS_URL', self::ZWROTY_URL);
            Configuration::updateValue('INPOST_PARCERLS_LOCKERS_RETURNS_DESCRIPTION', "Zwracaj zamówienia przez ponad 1 600 Paczkomatów w całej Polsce. Szybko, wygodnie, bez kolejek!");
        }

        if (!Configuration::get('INPOST_LOGIN'))
        {
            return false;
        }
        if (!$this->api->getCustomer())
        {
            return false;
        }
        if (!Configuration::get('INPOST_SENDER_PARCEL_LOCKER') && property_exists($api = $this->api->getCustomer(), 'default_machine_id'))
        {
            Configuration::updateValue('INPOST_SENDER_PARCEL_LOCKER', $api->default_machine_id);
        }
        if ((int)Configuration::get('INPOST_COUNTRY')  === 1)
        {
            $this->synchronizeDispatch();
        }

    }

    public function synchronizeDispatch($forceSync = false)
    {
        if (Configuration::get('INPOST_COUNTRY') == 1) {
          if ((int)Configuration::get('INPOST_AVAILABLE_SERVICES_CROSSBORDER') === 1 ) {
              self::synchronizePackagesStatusXBorder();
          }
        }

        if (
            !Configuration::get('X_BORDER_SYNCHRONIZE')
            && ((int)Configuration::get('INPOST_AVAILABLE_SERVICES_CROSSBORDER') === 1
                || Tools::isSubmit('INPOST_AVAILABLE_SERVICES_CROSSBORDER')
            )
        ) {
            $dispatchX = $this->x_api->getUserDispatchPoints();
            if ($dispatchX && isSet($dispatchX[0]))
            {
                foreach ($dispatchX as $singleDisX)
                {
                    Db::getInstance()->update('inpost_dispatch_points', array(
                        'x_border_id' => $singleDisX->id
                    ), 'name = "' . $singleDisX->name . '"');
                    InpostModel::saveXBorderDispatchPoint($singleDisX);
                }
                Configuration::updateValue('X_BORDER_SYNCHRONIZE', true);
            }
        }

        if (!Configuration::get('FIRST_DISPATCH_POINTS_SYNCHRONIZATION') || $forceSync)
        {
            $defaultDispatchPoints = $this->api->getUserDispatchPoints();

            if ($defaultDispatchPoints && !property_exists($defaultDispatchPoints, 'status_code') && $defaultDispatchPoints->count > 0) {
                foreach ($defaultDispatchPoints->_embedded->dispatch_points as $b) {
                    InpostModel::saveDispatchPoint($b);
                }
            }

            if ($defaultDispatchPoints && !property_exists($defaultDispatchPoints, 'status_code') && property_exists($defaultDispatchPoints, 'count') ) {
                Configuration::updateValue('FIRST_DISPATCH_POINTS_SYNCHRONIZATION', true);
            }
        }
    }

    private function runCrons()
    {
        $lastRef = DB::getInstance()->executeS('SELECT value, date_upd FROM ' . _DB_PREFIX_ . 'configuration
                                                WHERE `name` = "INPOST_LAST_REFRESH"');

        if ($lastRef) {
            if (date('U') > date('U', strtotime($lastRef[0]['date_upd'] . '+1 hour'))) {
                Configuration::updateValue('INPOST_LAST_REFRESH', time());
				$this->refreshCachedData();
            }
        } else {
            Configuration::updateValue('INPOST_LAST_REFRESH', time());
			$this->refreshCachedData();
        }
    }

	private function refreshCachedData() {
		$x_api = new CrossBorderConnector();
		$fieldsX = $x_api->getUserRoutesServices();
		InpostModel::importAvailableCrossBorderTypes($fieldsX, true);
		self::synchronizePackagesStatus();
		self::synchronizePackagesStatusXBorder();
		$this->synchronizeDispatch(true);
		Configuration::updateValue('INPOST_LAST_REFRESH', '1');
	}
    public function hookDisplayTop()
    {
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            $this->context->controller->addJS($this->_path . 'views/js/1.5/front_hook.js?v' . $this->version);
        } else {
            $this->context->controller->addJS($this->_path . 'views/js/front_hook.js?v' . $this->version);
        }
        $this->context->smarty->assign(array(
                'return_url' => Configuration::get('INPOST_PARCERLS_LOCKERS_RETURNS_URL'),
                'return_description' => Configuration::get('INPOST_PARCERLS_LOCKERS_RETURNS_DESCRIPTION')
            ));

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

    public function hookDisplayCustomerAccount($params)
    {
        $this->context->smarty->assign(array(
                'return_url' => Configuration::get('INPOST_PARCERLS_LOCKERS_RETURNS_URL'),
                'return_description' => Configuration::get('INPOST_PARCERLS_LOCKERS_RETURNS_DESCRIPTION')
            ));
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            return $this->display(__FILE__, 'views/templates/hook/1.5/my_account.tpl');
        } else {
            return $this->display(__FILE__, 'views/templates/hook/my_account.tpl');
        }
    }


    public function synchronizePricesCross()
    {
        $fields = $this->x_api->getUserRoutesServices();

        if ($fields) {
            InpostModel::importAvailableCrossBorderTypes($fields);
        }
    }

    /**
     * Should be used in 1.5
     */
    public static function synchronizePackagesStatus()
    {
        $api = new InpostConnector();
        $x_api = new CrossBorderConnector();
        $packages = InpostModel::getAllPackagesForCron();

        if ($packages) {
            foreach ($packages as $package) {
                $parcel = $api->getParcel($package['parcel_no']);

                if (property_exists($parcel, 'status_code') || !property_exists($parcel, 'status')) {
                    if ($parcel->status_code == 404) {

                        $parcel = $x_api->getShipment($package['parcel_no']);

                        if ($parcel) {
                            InpostPackages::changeParcelStatus($package['parcel_no'], $parcel->status->code);
                            continue;
                        }
                    }
                }

                if ($parcel && !property_exists($parcel, 'status_code') && $parcel->status !== $package['status']) {
                    InpostPackages::changeParcelStatus($package['parcel_no'], $parcel->status);
                }

            }
        }
    }


    public static function synchronizePackagesStatusXBorder()
    {
        $x_api = new CrossBorderConnector();
        $packages = InpostModel::getAllXBorderPackagesWithProcessingStatus();

        if ($packages) {
          foreach ($packages as $package) {
                $parcel = $x_api->getShipment($package['parcel_no']);
                if ($parcel) {
                    InpostPackages::changeParcelStatus($package['parcel_no'], $parcel->status->code, $parcel->tracking_number);
                    continue;
                }
          }
        }
    }

    public function installHooks()
    {
        return $this->registerHook('actionValidateOrder')
            && $this->registerHook('adminOrder')
            && $this->registerHook('displayCarrierList')
            && $this->registerHook('updateCarrier')
            && $this->registerHook("actionCarrierProcess")
            && $this->registerHook('paymentTop')
            && $this->registerHook('displayBackOfficeHeader')
            && $this->registerHook('customerAccount')
            && $this->registerHook('hookDisplayPaymentTop')
            && $this->registerHook('displayTop')
            && $this->registerHook('displayBeforeCarrier')
        ;
    }

    public function checkHooks()
    {
        $cache_id = 'EE_Inpost_checkHooks';
        if (!Cache::isStored($cache_id))
        {
            $return = $this->installHooks();
            Cache::store($cache_id, $return);
        }

        return Cache::retrieve($cache_id);
    }

    public function  getIdOrderCarrier(OrderCore $order)
    {
        if(method_exists($order, 'getIdOrderCarrier')) {
            return (int)$order->getIdOrderCarrier();
        } else {
            return (int)Db::getInstance()->getValue('
                SELECT `id_order_carrier`
                FROM `' . _DB_PREFIX_ . 'order_carrier`
                WHERE `id_order` = ' . (int)$order->id
            );
        }
    }

    public function validateOnePageCheckout()
    {
        $context = Context::getContext();
        $cart = $context -> cart;
        $carrierId = $cart -> id_carrier;

        if (self::isCarrierAParcelLocker($carrierId)) {
            $parcelLocker = InpostModel::getSelectedParcelForCart($cart -> id);

            $errorText = '';

            if (!$parcelLocker) {
                $errorText = $this->l('Select machine');
            } else {
                $phonePattern = '/[^0-9\+]/';
                $phoneNo = preg_replace($phonePattern, '', InpostModel::getParcelLockerPhoneNumberForCart($cart -> id));

                if(!$phoneNo) {
                    $errorText = $this->l('Phone number is invalid.');
                } else {
                    $inpostCountry = Configuration::get('INPOST_COUNTRY');

                    if ($inpostCountry == 1) {
                        $preg_phone = preg_match(self::POLAND_PHONE, $phoneNo, $matches);
                    } elseif ($inpostCountry == 2) {
                        $preg_phone = preg_match(self::FRANCE_PHONE, $phoneNo, $matches);
                    } elseif ($inpostCountry == 3) {
                        $preg_phone = preg_match(self::ITALY_PHONE, $phoneNo, $matches);
                    }

                    if (!$preg_phone) {
                        $errorText = $this->l('Phone number is invalid.');
                    }
                }
            }

            if ($errorText) {
                $html = (new InpostHelper())->htmlAssign('validateOnePageCheckoutError', array('errorText' => $errorText));
                return array('error' => $html);
            }
        }

        return  true;
    }
}
