<?php
/**
 * 2016 Eengine Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 */
if (!defined('_PS_VERSION_')) {
    exit;
}

class InpostModel
{
    public function __construct()
    {

    }


    public static function getAllPriceRules()
    {
        $sql = "SELECT * FROM " . _DB_PREFIX_ . "parcels_lockers_prices WHERE type_of = 'PRICE_RULES'";
        return Db::getInstance()->ExecuteS($sql);
    }

    /**
     * PRICE RULES
     */
    public static function getParcelLockersAppropriatePrice($cart_total)
    {
        $sql = "SELECT * FROM ". _DB_PREFIX_ . "parcels_lockers_prices WHERE type_of = 'PRICE_RULES' AND {$cart_total} > price_from AND {$cart_total} < price_to";
        return Db::getInstance()->getRow($sql);
    }

    public static function getParcelLockersAppropriatePriceWeight($cart_total)
    {
        $sql = "SELECT * FROM ". _DB_PREFIX_ . "parcels_lockers_prices WHERE type_of = 'WEIGHT_RULES' AND {$cart_total} >= price_from AND {$cart_total} < price_to";
        return Db::getInstance()->getRow($sql);
    }

    /**
     * PRICE RULES COD
     */
    public static function getParcelLockersCodAppropriatePrice($cart_total)
    {
        $sql = "SELECT * FROM ". _DB_PREFIX_ . "parcels_lockers_prices WHERE type_of = 'PRICE_RULES_COD' AND {$cart_total} > price_from AND {$cart_total} < price_to";
        return Db::getInstance()->getRow($sql);
    }

    public static function getParcelLockersCodAppropriatePriceWeight($cart_total)
    {
        $sql = "SELECT * FROM ". _DB_PREFIX_ . "parcels_lockers_prices WHERE type_of = 'WEIGHT_RULES_COD' AND {$cart_total} >= price_from AND {$cart_total} < price_to";
        return Db::getInstance()->getRow($sql);
    }


    /*====== */

    public static function getAllPriceRulesCod()
    {
        $sql = "SELECT * FROM " . _DB_PREFIX_ . "parcels_lockers_prices WHERE type_of = 'PRICE_RULES_COD'";
        return Db::getInstance()->ExecuteS($sql);
    }

    public static function getAllWeightRulesCod()
    {
        $sql = "SELECT * FROM " . _DB_PREFIX_ . "parcels_lockers_prices WHERE type_of = 'WEIGHT_RULES_COD'";
        return Db::getInstance()->ExecuteS($sql);
    }
    public static function getAllWeightRules()
    {
        $sql = "SELECT * FROM " . _DB_PREFIX_ . "parcels_lockers_prices WHERE type_of = 'WEIGHT_RULES'";
        return Db::getInstance()->ExecuteS($sql);
    }

    public static function getSelectedPriceRule()
    {
        $sql = "SELECT DISTINCT type_of FROM " . _DB_PREFIX_."parcels_lockers_prices WHERE status = 1";
        $c = [];
        foreach (Db::getInstance()->executeS($sql) as $r) {
            $c[] = $r['type_of'];
        }
        return $c;
    }
    public static function parcelsLockersGetFlatPrice()
    {
        $sql = "SELECT * FROM ". _DB_PREFIX_."parcels_lockers_prices WHERE type_of = 'PARCELS_LOCKERS_FLAT_PRICE'";
        return Db::getInstance()->getRow($sql);
    }

    public static function parcelsLockersCodGetFlatPrice()
    {
        $sql = "SELECT * FROM ". _DB_PREFIX_."parcels_lockers_prices WHERE type_of = 'PARCELS_LOCKERS_COD_FLAT_PRICE'";
        return Db::getInstance()->getRow($sql);
    }

    public static function removeAllData()
    {
        $sql = 'DELETE FROM '._DB_PREFIX_.'parcels_lockers_prices';
        return Db::getInstance()->execute($sql);
    }

    public static function dropConfiguration()
    {
        Configuration::deleteByName('INPOST_PARCERLS_LOCKERS_RETURNS_URL');
        Configuration::deleteByName('INPOST_PARCERLS_LOCKERS_RETURNS_DESCRIPTION');
        Configuration::deleteByName('INPOST_API_URL_FRANCE');
        Configuration::deleteByName('INPOST_API_URL_ITALY');
        Configuration::deleteByName('INPOST_API_URL_POLAND');
        Configuration::deleteByName('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS');
        Configuration::deleteByName('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS_COD');
        Configuration::deleteByName('INPOST_AVAILABLE_SERVICES_RETURNS');
        Configuration::deleteByName('INPOST_COUNTRY');
        Configuration::deleteByName('INPOST_CUSTOMER_REFERENCE');
        Configuration::deleteByName('INPOST_DEFAULT_PARCEL_SIZE');
        Configuration::deleteByName('INPOST_DEFAULT_STATUS_AFTER_LABEL_GENERATION');
        Configuration::deleteByName('INPOST_DEFAULT_STATUS_AFTER_PARCEL_DELIVERY');
        Configuration::deleteByName('INPOST_LOGIN');
        Configuration::deleteByName('INPOST_PARCERLS_LOCKERS_COD_IBAN');
        Configuration::deleteByName('INPOST_PASSWORD');
        Configuration::deleteByName('INPOST_SENDER_ADDRESS');
        Configuration::deleteByName('INPOST_SENDER_BUILDING_NO');
        Configuration::deleteByName('INPOST_SENDER_CITY');
        Configuration::deleteByName('INPOST_SENDER_EMAIL');
        Configuration::deleteByName('INPOST_SENDER_FLAT_NO');
        Configuration::deleteByName('INPOST_SENDER_PARCEL_LOCKER');
        Configuration::deleteByName('INPOST_SENDER_PHONE');
        Configuration::deleteByName('INPOST_SENDER_POSTCODE');
        Configuration::deleteByName('INPOST_SENDER_STREET');
        Configuration::deleteByName('EE_INPOST_API_URL');
        Configuration::deleteByName('FIRST_DISPATCH_POINTS_SYNCHRONIZATION');
        Configuration::deleteByName('PARCELS_LOCKERS_FREE_SHIPPING');
        Configuration::deleteByName('PARCELS_LOCKERS_COD_FREE_SHIPPING');
        Configuration::deleteByName('SHIPPING_TAX_INPOST');
        Configuration::deleteByName('PARCELS_LOCKERS_FLAT_PRICE');
        Configuration::deleteByName('PERCENT_OF_CART_VALUE');
        Configuration::deleteByName('PARCELS_LOCKERS_COD_FLAT_PRICE');
        Configuration::deleteByName('INPOST_TOKEN_X_BORDER');
        Configuration::deleteByName('X_BORDER_SYNCHRONIZE');
        Configuration::deleteByName('INPOST_X_BORDER_LOGIN');
        Configuration::deleteByName('INPOST_X_BORDER_PASSWORD');
        Db::getInstance()->delete('tab', 'module="inpost"');
        Db::getInstance()->delete('tab_lang', 'name="InPost"');
        return DB::getInstance()->Execute("
			DROP TABLE IF EXISTS
				"._DB_PREFIX_."inpost_delivery_modules,
                "._DB_PREFIX_ ."inpost_dispatch_points,
                "._DB_PREFIX_ ."inpost_labels,
                "._DB_PREFIX_ ."inpost_packages,
                "._DB_PREFIX_ ."parcels_lockers_prices,
                "._DB_PREFIX_ ."inpost_couriers,
                "._DB_PREFIX_ ."x_border_types_details,
                "._DB_PREFIX_ ."x_border_types
		");
    }
    public static function createTables()
    {
        $sql = "
            CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."inpost_couriers` (
              `courier_id` int(11) NOT NULL AUTO_INCREMENT,
              `courier_status` varchar(20) DEFAULT NULL,
              `courier_from` datetime DEFAULT NULL,
              `courier_to` datetime DEFAULT NULL,
              `courier_api_id` int(11) DEFAULT NULL,
              `created_at` datetime DEFAULT NULL,
              `dispatch_point_id` int(11) DEFAULT NULL,
              `reference` varchar(255) DEFAULT NULL,
              `comment` varchar(255),
              `x_border` bool,
              PRIMARY KEY (`courier_id`)
            ) ENGINE=" ._MYSQL_ENGINE_."  DEFAULT CHARSET=utf8;

            CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."inpost_delivery_modules` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `module_name` varchar(255) DEFAULT NULL,
              `id_module` int(11) DEFAULT NULL,
              `reference` int(11) DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=" . _MYSQL_ENGINE_ . " DEFAULT CHARSET=utf8;

            CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_ ."inpost_dispatch_points` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `country` varchar(255) DEFAULT NULL,
              `postcode` varchar(20) DEFAULT NULL,
              `city` varchar(255) DEFAULT NULL,
              `street` varchar(255) DEFAULT NULL,
              `building_no` varchar(255) DEFAULT NULL,
              `flat_no` varchar(255) DEFAULT NULL,
              `phone_no` varchar(255) DEFAULT NULL,
              `email` varchar(255) DEFAULT NULL,
              `name` varchar(255) DEFAULT NULL,
              `comments` varchar(255) DEFAULT NULL,
              `office_hours` varchar(255) DEFAULT NULL,
              `href` varchar(255) DEFAULT NULL,
              `status` varchar(255) DEFAULT NULL,
              `inpost_service` varchar(255) DEFAULT NULL,
              `x_border_id` int(11) DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=" . _MYSQL_ENGINE_ . " DEFAULT CHARSET=utf8;

            CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_ ."inpost_labels` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `order_id` int(11) DEFAULT NULL,
              `package_id` varchar(255) DEFAULT NULL,
              `label_no` varchar(255) DEFAULT NULL,
              `date_label_generation` datetime DEFAULT NULL,
              `label_downloaded` tinyint(1) DEFAULT NULL,
              `courier_id` int(11) DEFAULT NULL,
              `pdf_url` varchar(255) DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=" . _MYSQL_ENGINE_ . " DEFAULT CHARSET=utf8;


            CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_ ."inpost_packages` (
              `id` bigint(20) NOT NULL AUTO_INCREMENT,
              `order_id` int(11) DEFAULT NULL,
              `parcel_no` varchar(255) DEFAULT NULL,
              `receiver_id` int(11) DEFAULT NULL,
              `date_parcel_generation` datetime DEFAULT NULL,
              `created_at` datetime DEFAULT NULL,
              `status` varchar(255) DEFAULT NULL,
              `status_updated_at` datetime DEFAULT NULL,
              `additional1` varchar(255) DEFAULT NULL,
              `additional2` varchar(255) DEFAULT NULL,
              `avizo_time` datetime DEFAULT NULL,
              `cod_amount` varchar(255) DEFAULT NULL,
              `customer_reference` varchar(255) DEFAULT NULL,
              `expiration_time` varchar(255) DEFAULT NULL,
              `insurance_amount` varchar(255) DEFAULT NULL,
              `letter_type` varchar(255) DEFAULT NULL,
              `pickup_expiration_time` varchar(255) DEFAULT NULL,
              `receiver_phone` varchar(255) DEFAULT NULL,
              `receiver_email` varchar(255) DEFAULT NULL,
              `sender_building_no` varchar(255) DEFAULT NULL,
              `sender_city` varchar(255) DEFAULT NULL,
              `sender_company_name` varchar(255) DEFAULT NULL,
              `sender_address_email` varchar(255) DEFAULT NULL,
              `sender_first_name` varchar(255) DEFAULT NULL,
              `sender_flat_no` varchar(255) DEFAULT NULL,
              `sender_last_name` varchar(255) DEFAULT NULL,
              `sender_address_phone` varchar(255) DEFAULT NULL,
              `sender_post_code` varchar(255) DEFAULT NULL,
              `sender_province` varchar(255) DEFAULT NULL,
              `sender_street` varchar(255) DEFAULT NULL,
              `sender_email` varchar(255) DEFAULT NULL,
              `sender_phone` varchar(255) DEFAULT NULL,
              `service` varchar(255) DEFAULT NULL,
              `size` varchar(255) DEFAULT NULL,
              `skip_pickup_point` varchar(255) DEFAULT NULL,
              `source_machine_id` varchar(255) DEFAULT NULL,
              `target_machine_id` varchar(255) DEFAULT NULL,
              `calculated_amount` varchar(255) DEFAULT NULL,
              `charged_amount` varchar(255) DEFAULT NULL,
              `dropoff_code` varchar(255) DEFAULT NULL,
              `receiver_company_name` varchar(255) DEFAULT NULL,
              `receiver_firstname` varchar(255) DEFAULT NULL,
              `receiver_address` varchar(255) DEFAULT NULL,
              `receiver_post_code` varchar(255) DEFAULT NULL,
              `receiver_city` varchar(255) DEFAULT NULL,
              `receiver_country` varchar(255) DEFAULT NULL,
              `receiver_phone_mobile` varchar(255) DEFAULT NULL,
              `receiver_parcel_locker` varchar(255) DEFAULT NULL,
              `package_canceled` tinyint(1) DEFAULT NULL,
              `receiver_lastname` varchar(255) DEFAULT NULL,
              `receiver_building_no` varchar(255) DEFAULT NULL,
              `receiver_flat_no` varchar(255) DEFAULT NULL,
              `receiver_street` varchar(255) DEFAULT NULL,
              `receiver_province` varchar(255) DEFAULT NULL,
              `dispatch_point_id` int(11) DEFAULT NULL,
               `delivery_price_amount` varchar(50) DEFAULT NULL,
              `delivery_price_currency` varchar(50) DEFAULT NULL,
              `insurance_currency` varchar(50) DEFAULT NULL,
              `receiver_country_code` varchar(50) DEFAULT NULL,
              `declared_value_currency` varchar(50) DEFAULT NULL,
              `declared_value_amount` varchar(50) DEFAULT NULL,
              `declared_weight_amount` varchar(50) DEFAULT NULL,
              `declared_weight_unit` varchar(50) DEFAULT NULL,
              `tracking_number` varchar(50) DEFAULT NULL,
              `sender_method` varchar(50) DEFAULT NULL,
              `recipient_method` varchar(50) DEFAULT NULL,
              `declared_dimensions_height` VARCHAR(30),
            `declared_dimensions_length` VARCHAR(30),
            `declared_dimensions_unit` VARCHAR(30),
            `declared_dimensions_width` VARCHAR(30),
              PRIMARY KEY (`id`)
            ) ENGINE=" . _MYSQL_ENGINE_ . " DEFAULT CHARSET=utf8;


            CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_ ."inpost_parcel_lockers_orders` (
              `id` int(10) NOT NULL AUTO_INCREMENT,
              `parcel_locker` varchar(255) DEFAULT NULL,
              `order_id` int(11) DEFAULT NULL,
              `cart_id` int(11) DEFAULT NULL,
              `x_border` bool,
              `phone_no` varchar(255) DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=" . _MYSQL_ENGINE_ . " DEFAULT CHARSET=utf8;


            CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_ ."parcels_lockers_prices` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `type_of` varchar(255) DEFAULT NULL,
              `price_from` decimal(20,2) DEFAULT NULL,
              `price_to` decimal(20,2) DEFAULT NULL,
              `cost` decimal(20,2) DEFAULT NULL,
              `status` int(11) DEFAULT NULL,
              `cart_value` varchar(25) DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=" . _MYSQL_ENGINE_ . " DEFAULT CHARSET=utf8;

            CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_ ."x_border_types` (
              `id` int(10) NOT NULL AUTO_INCREMENT,
              `from_country` varchar(10) DEFAULT NULL,
              `to_country` varchar(10) DEFAULT NULL,
              `shipping_method` varchar(20) DEFAULT NULL,
              `recipient_method` varchar(30) DEFAULT NULL,
              `sender_method` varchar(30) DEFAULT NULL,
              `insurance_amount` decimal(20,6) DEFAULT NULL,
              `insurance_currency` varchar(10) DEFAULT NULL,
              `insurance_cost_currency` varchar(10) DEFAULT NULL,
              `insurance_cost_amount` decimal(20,6) DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=" . _MYSQL_ENGINE_ . " DEFAULT CHARSET=utf8;

            CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_ ."x_border_types_details` (
              `id_border_type` int(10) DEFAULT NULL,
              `parcel_weight` varchar(10) DEFAULT NULL,
              `parcel_price` decimal(20,2) DEFAULT NULL,
              `cod` varchar(10) DEFAULT NULL,
              `currency` varchar(10) DEFAULT NULL
            ) ENGINE=" . _MYSQL_ENGINE_ . " DEFAULT CHARSET=utf8;

            ";


            if (version_compare(_PS_VERSION_, '1.6', '<')) {
              $sql .= " ALTER TABLE  `"._DB_PREFIX_."configuration` CHANGE  `name`  `name` VARCHAR( 255 ) NOT NULL; ";
             }
        return Db::getInstance()->execute($sql);

    }



    /**
     * Save data from configuration tab
     * @param $data
     * @return array|bool
     * @throws PrestaShopDatabaseException
     */

    public static function saveParcelsLockersPriceRules()
    {
        if ($plPriceRules = Tools::getValue('PARCELS_LOCKERS_PRICE_RULES_FROM')) {
            foreach ($plPriceRules as $price_rule_form_key => $price_rule_from) {
                /**
                 * Active = status = 1
                 */
                $status = 0;
                if (Tools::getValue('PARCELS_LOCKERS_PRICE_RULES') && (int)Tools::getValue('PARCELS_LOCKERS_PRICE_RULES') === 1) {
                    $status = 1;
                }
                $parcelsLockersPriceRulesTo = Tools::getValue('PARCELS_LOCKERS_PRICE_RULES_TO_');
                $parcelsLockersPriceRulesCost = Tools::getValue('PARCELS_LOCKERS_PRICE_RULES_COST_');

                if (!Db::getInstance()->insert('parcels_lockers_prices', array(
                    'type_of'              => pSQL('PRICE_RULES'),
                    'price_from'        => (float) str_replace(',', '.', $price_rule_from),
                    'price_to'          => (float) str_replace(',', '.', $parcelsLockersPriceRulesTo[$price_rule_form_key]),
                    'cost'              => (float) str_replace(',', '.', $parcelsLockersPriceRulesCost[$price_rule_form_key]),
                    'status'            => pSQL($status)
                ))) {
                    return false;
                }
            }
        }

        return true;
    }

    public static function saveParcelsLockersWeightRules()
    {
        if ($parcelsLockersWeightRulesFrom =Tools::getValue('PARCELS_LOCKERS_WEIGHT_RULES_FROM')) {
            foreach ($parcelsLockersWeightRulesFrom as $weight_rule_form_key => $weight_rule_from) {
                /**
                 * Active = status = 1
                 */
                $status = 0;
                if (Tools::getValue('PARCELS_LOCKERS_WEIGHT_RULES') && (int)Tools::getValue('PARCELS_LOCKERS_WEIGHT_RULES') === 1) {
                    $status = 1;
                }
                $parcelsLockersWeightRulesTo = Tools::getValue('PARCELS_LOCKERS_WEIGHT_RULES_TO_');
                $parcelsLockersWeightRulesCost = Tools::getValue('PARCELS_LOCKERS_WEIGHT_RULES_COST_');

                if (!Db::getInstance()->insert('parcels_lockers_prices', array(
                    'type_of'              => pSQL('WEIGHT_RULES'),
                    'price_from'        => (float) str_replace(',', '.', $weight_rule_from),
                    'price_to'          => (float) str_replace(',', '.', $parcelsLockersWeightRulesTo[$weight_rule_form_key]),
                    'cost'              => (float) str_replace(',', '.', $parcelsLockersWeightRulesCost[$weight_rule_form_key]),
                    'status'            => pSQL($status)
                ))) {
                    return false;
                }
            }
        }

        return true;
    }

    public static function saveParcelsLockersFlatPrice()
    {
        if (Tools::getValue('PARCELS_LOCKERS_FLAT_PRICE')) {
            if (!Db::getInstance()->insert('parcels_lockers_prices', array(
                'type_of'              => pSQL('PARCELS_LOCKERS_FLAT_PRICE'),
                'price_from'        => pSQL(''),
                'price_to'          => pSQL(''),
                'cost'              => (float) str_replace(',', '.', Tools::getValue('PARCELS_LOCKERS_FLAT_PRICE')),
                'status'            => (int)Tools::getValue('PARCELS_LOCKERS_FLAT_PRICE_CHECKED')
            ))) {
                return false;
            }
        }
        return true;
    }


    public static function saveParcelsLockersCodPriceRules()
    {
        if ($parcelsLockersCodPriceRulesFrom = Tools::getValue('PARCELS_LOCKERS_COD_PRICE_RULES_FROM')) {
            foreach ($parcelsLockersCodPriceRulesFrom as $price_rule_form_key => $price_rule_from) {
                /**
                 * Active = status = 1
                 */
                $status = 0;
                if (Tools::getValue('PARCELS_LOCKERS_COD_PRICE_RULES') && (int)Tools::getValue('PARCELS_LOCKERS_COD_PRICE_RULES') === 1) {
                    $status = 1;
                }
                $parcelsLockersCodPriceRulesTo = Tools::getValue('PARCELS_LOCKERS_COD_PRICE_RULES_TO_');
                $parcelsLockersCodPriceRulesCost = Tools::getValue('PARCELS_LOCKERS_COD_PRICE_RULES_COST_');
                if (!Db::getInstance()->insert('parcels_lockers_prices', array(
                    'type_of'              => pSQL('PRICE_RULES_COD'),
                    'price_from'        => (float) str_replace(',', '.', $price_rule_from),
                    'price_to'          => (float) str_replace(',', '.', $parcelsLockersCodPriceRulesTo[$price_rule_form_key]),
                    'cost'              => (float) str_replace(',', '.', $parcelsLockersCodPriceRulesCost[$price_rule_form_key]),
                    'status'            => pSQL($status)
                ))) {
                    return false;
                }
            }
        }
        return true;
    }

    public static function saveParcelsLockersCodWeightRules()
    {

        if ($parcelsLockersCodWeightRulesFrom = Tools::getValue('PARCELS_LOCKERS_COD_WEIGHT_RULES_FROM')) {
            foreach ($parcelsLockersCodWeightRulesFrom as $weight_rule_form_key => $weight_rule_from) {
                /**
                 * Active = status = 1
                 */
                $status = 0;
                if (Tools::getValue('PARCELS_LOCKERS_COD_WEIGHT_RULES') && (int)Tools::getValue('PARCELS_LOCKERS_COD_WEIGHT_RULES') === 1) {
                    $status = 1;
                }
                $parcelsLockersCodWeightRulesTo = Tools::getValue('PARCELS_LOCKERS_COD_WEIGHT_RULES_TO_');
                $parcelsLockersCodWeightRulesCost = Tools::getValue('PARCELS_LOCKERS_COD_WEIGHT_RULES_COST_');
                $parcelsLockersCodWeightRulesPercent = Tools::getValue('PARCELS_LOCKERS_COD_WEIGHT_RULES_PERCENT');
                if (!Db::getInstance()->insert('parcels_lockers_prices', array(
                    'type_of'              => pSQL('WEIGHT_RULES_COD'),
                    'price_from'        => (float) str_replace(',', '.', $weight_rule_from),
                    'price_to'          => (float) str_replace(',', '.', $parcelsLockersCodWeightRulesTo[$weight_rule_form_key]),
                    'cost'              => (float) str_replace(',', '.', $parcelsLockersCodWeightRulesCost[$weight_rule_form_key]),
                    'cart_value'        => (float) str_replace(',', '.', $parcelsLockersCodWeightRulesPercent[$weight_rule_form_key]),
                    'status'            => (float) str_replace(',', '.', $status)
                ))) {
                    return false;
                }
            }
        }
        return true;
    }

    public static function saveParcelsLockersCodFlatPrice()
    {

        if (Tools::getValue('PARCELS_LOCKERS_COD_FLAT_PRICE') > 0) {
            if (!Db::getInstance()->insert('parcels_lockers_prices', array(
                'type_of'              => pSQL('PARCELS_LOCKERS_COD_FLAT_PRICE'),
                'price_from'        => pSQL(''),
                'price_to'          => pSQL(''),
                'cost'              => (float) str_replace(',', '.', Tools::getValue('PARCELS_LOCKERS_COD_FLAT_PRICE')),
                'status'            => (int)Tools::getValue('PARCELS_LOCKERS_COD_FLAT_PRICE_CHECKED')
            ))) {
                return false;
            }

            return true;
        }

    }

    public static function updatePrestashopConfigurationTable()
    {
        $token = str_replace('Bearer ', '', Tools::getValue('INPOST_PASSWORD'));
        $currentCountry = Configuration::get('INPOST_COUNTRY');
        $login = str_replace(' ', '', Tools::getValue('INPOST_LOGIN'));

        Configuration::updateValue('INPOST_LOGIN', $login);

        Configuration::updateValue('EE_INPOST_API_URL', Tools::getValue('EE_INPOST_API_URL'));
        if (Tools::getValue('INPOST_PASSWORD') != '****************') {
            Configuration::updateValue('INPOST_PASSWORD', $token);
        }

        Configuration::updateValue('INPOST_COUNTRY', Tools::getValue('INPOST_COUNTRY'));

        if ((int)Tools::getValue('INPOST_COUNTRY') === 1) {
            Configuration::updateValue('INPOST_GEOWIDGET_URL', "https://geowidget.inpost.pl/");
        }
        if ((int)Tools::getValue('INPOST_COUNTRY') === 2) {
            Configuration::updateValue('INPOST_GEOWIDGET_URL', "https://geowidget-fr.easypack24.net/");
        }
        if ((int)Tools::getValue('INPOST_COUNTRY') === 3) {
            Configuration::updateValue('INPOST_GEOWIDGET_URL', "https://geowidget-it.easypack24.net/");
        }

        if (Tools::getValue('INPOST_DEFAULT_PARCEL_SIZE')) {
            Configuration::updateValue('INPOST_DEFAULT_PARCEL_SIZE', Tools::getValue('INPOST_DEFAULT_PARCEL_SIZE'));
        }

        if (Tools::getValue('INPOST_SENDER_PARCEL_LOCKER')) {
            Configuration::updateValue('INPOST_SENDER_PARCEL_LOCKER', Tools::getValue('INPOST_SENDER_PARCEL_LOCKER'));
        }

        if ($currentCountry != Tools::getValue('INPOST_COUNTRY')) {
            Configuration::updateValue('INPOST_SENDER_PARCEL_LOCKER', false);
        }
        $country = Configuration::get('INPOST_COUNTRY');
        if (!$country) {
            $country = Tools::getValue('INPOST_COUNTRY');
        }
        switch ((int)$country) {
            case 1:
                $url = "https://twoj.inpost.pl/pl/znajdz-przesylke?parcel=@";
                break;
            case 2:
                $url = "https://inpost24.fr/fr/track-parcel?parcel=@";
                break;
            case 3:
                $url = "https://inpost24.it/it/track-parcel?parcel=@";
                break;
            default:
                $url = '';
                break;
        }

        //self::updateCarrierTrackingUrl($url);
    }

    public static function updateCarrierTrackingUrl($url)
    {
        return Db::getInstance()->update('carrier', array(
            'url' => $url
        ), 'external_module_name = "inpost"');
    }
    public static function saveAvailableFunctions()
    {
        $paymentModules = Module::getPaymentModules();

        foreach ($paymentModules as $payment) {
            Configuration::updateValue('INPOST_PARCEL_LOCKERS_PAYMENT_'.$payment['name'], (int)Tools::getValue('INPOST_PARCEL_LOCKERS_PAYMENT_'.$payment['name']));
            Configuration::updateValue('INPOST_PARCEL_LOCKERS_COD_PAYMENT_'.$payment['name'], (int)Tools::getValue('INPOST_PARCEL_LOCKERS_COD_PAYMENT_'.$payment['name']));
            Configuration::updateValue('INPOST_X_BORDER_PAYMENT_'.$payment['name'], (int)Tools::getValue('INPOST_X_BORDER_PAYMENT_'.$payment['name']));
        }
        Configuration::updateValue('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS', (int)Tools::getValue('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS'));

        Configuration::updateValue('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS_COD', (int)Tools::getValue('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS_COD'));

        Configuration::updateValue('INPOST_AVAILABLE_SERVICES_CROSSBORDER', (int)Tools::getValue('INPOST_AVAILABLE_SERVICES_CROSSBORDER'));
        Configuration::updateValue('INPOST_AVAILABLE_SERVICES_RETURNS', (int)Tools::getValue('INPOST_AVAILABLE_SERVICES_RETURNS'));

        if (Tools::getValue('INPOST_PARCERLS_LOCKERS_RETURNS_URL')) {
            Configuration::updateValue('INPOST_PARCERLS_LOCKERS_RETURNS_URL', Tools::getValue('INPOST_PARCERLS_LOCKERS_RETURNS_URL'));
        }
        Configuration::updateValue('INPOST_PARCERLS_LOCKERS_RETURNS_DESCRIPTION', Tools::getValue('INPOST_PARCERLS_LOCKERS_RETURNS_DESCRIPTION'));



    }
    public static function saveSenderData()
    {

        if (!Configuration::updateValue('INPOST_SENDER_POSTCODE', Tools::getValue('INPOST_SENDER_POSTCODE')) ||
            !Configuration::updateValue('INPOST_SENDER_CITY', Tools::getValue('INPOST_SENDER_CITY')) ||
            !Configuration::updateValue('INPOST_SENDER_PHONE', Tools::getValue('INPOST_SENDER_PHONE')) ||
            !Configuration::updateValue('INPOST_SENDER_EMAIL', Tools::getValue('INPOST_SENDER_EMAIL')) ||
            !Configuration::updateValue('INPOST_SENDER_STREET', Tools::getValue('INPOST_SENDER_STREET')) ||
            !Configuration::updateValue('INPOST_SENDER_BUILDING_NO', Tools::getValue('INPOST_SENDER_BUILDING_NO')) ||
            !Configuration::updateValue('INPOST_SENDER_FLAT_NO', Tools::getValue('INPOST_SENDER_FLAT_NO', '')) ||
            !Configuration::updateValue('INPOST_CUSTOMER_REFERENCE', Tools::getValue('INPOST_CUSTOMER_REFERENCE', ''))


        ) {
            return false;
        }
        return true;
    }
    public static function getAllPackagesForCron()
    {
        return Db::getInstance()->executeS("SELECT * FROM "._DB_PREFIX_."inpost_packages WHERE status != 'canceled' AND status != 'delivered'");
    }
    public static function findPackagesByOrderId($id_order)
    {
        if ((int)$id_order) {
            return Db::getInstance()->ExecuteS('SELECT iiplo.x_border, iip.* FROM '._DB_PREFIX_.'inpost_packages iip LEFT JOIN '._DB_PREFIX_.'inpost_parcel_lockers_orders iiplo on iip.order_id=iiplo.order_id WHERE iip.order_id ='.$id_order.' GROUP BY iip.parcel_no');
        }
        return false;
    }

    public static function findPackageByPackageId($package_id)
    {
        if ($package_id) {
            return Db::getInstance()->getRow('SELECT iiplo.x_border, iip.*, iil.package_id, iil.pdf_url, iil.label_no, iil.date_label_generation, iil.label_downloaded FROM '._DB_PREFIX_.'inpost_packages iip LEFT JOIN '._DB_PREFIX_.'inpost_labels iil on iip.parcel_no=iil.package_id LEFT JOIN '._DB_PREFIX_.'inpost_parcel_lockers_orders iiplo on iip.order_id=iiplo.order_id WHERE parcel_no ="'.$package_id.'" OR tracking_number = "'.$package_id.'"');
        }
        return false;
    }

    public static function getSelectedMachineInOrder($cart_id)
    {
        if(isset($cart_id)) {
            $cart_id = pSQL($cart_id);
            return Db::getInstance()->getValue('SELECT parcel_locker FROM '._DB_PREFIX_.'inpost_parcel_lockers_orders WHERE cart_id ='.$cart_id ." ORDER BY id DESC");
        }

        return false;
    }

    public static function getPhoneOrder($cart_id)
    {
        if(isset($cart_id)) {
            $cart_id = pSQL($cart_id);
            return Db::getInstance()->getValue('SELECT phone_no FROM '._DB_PREFIX_.'inpost_parcel_lockers_orders WHERE cart_id ='.$cart_id ." ORDER BY id DESC");
        }

        return false;
    }

    public static function getSenderData()
    {
        $api = new InpostConnector();

        $street         = Configuration::get('INPOST_SENDER_STREET');
        $building_no    = Configuration::get('INPOST_SENDER_BUILDING_NO');
        $flat_no        = Configuration::get('INPOST_SENDER_FLAT_NO');
        $postcode       = Configuration::get('INPOST_SENDER_POSTCODE');
        $city           = Configuration::get('INPOST_SENDER_CITY');
        $phone          = Configuration::get('INPOST_SENDER_PHONE');
        $sender_email   = Configuration::get('INPOST_SENDER_EMAIL');

        $company_name   = Configuration::get('INPOST_SENDER_COMPANY_NAME');
        $parcel_locker   = Configuration::get('INPOST_SENDER_PARCEL_LOCKER');
        $customer_reference = Configuration::get('INPOST_CUSTOMER_REFERENCE');

        $apiData = $api->getFormattedCustomerData();
        $allParcelLockers = $api->getAllMachines();

        if(is_object($allParcelLockers))
        {
            if (property_exists($allParcelLockers, 'errors')) {
                $allParcelLockers = array();
            }
            if (!property_exists($allParcelLockers, '_embedded'))
            {
                $allParcelLockers = array();
            }
        }
        else
        {
            $allParcelLockers = array();
        }

        if ($allParcelLockers)
        {
            $allParcelLockers = $allParcelLockers->_embedded->machines;
        }

        $allActiveDispatchPoints = array();
		if(InpostDispatchPoints::isActive()) {
			$allActiveDispatchPoints = InpostDispatchPoints::getDispatchPoints();
		}

        return array(
            'INPOST_SENDER_STREET'     => $street ? $street : $apiData['INPOST_SENDER_STREET'],
            'INPOST_SENDER_BUILDING_NO'     => $building_no ? $building_no : $apiData['INPOST_SENDER_BUILDING_NO'],
            'INPOST_SENDER_FLAT_NO'     => $flat_no ? $flat_no : $apiData['INPOST_SENDER_FLAT_NO'],
            'INPOST_SENDER_POSTCODE'    => $postcode ? $postcode : $apiData['INPOST_SENDER_POSTCODE'],
            'INPOST_SENDER_CITY'        => $city ? $city : $apiData['INPOST_SENDER_CITY'],
            'INPOST_SENDER_PHONE'       => $phone ? $phone : $apiData['INPOST_SENDER_PHONE'],
            'INPOST_SENDER_EMAIL'       => $sender_email ? $sender_email : $apiData['INPOST_SENDER_EMAIL'],
            'INPOST_SENDER_FIRSTNAME' => $apiData['INPOST_SENDER_FIRSTNAME'],
            'INPOST_SENDER_LASTNAME' => $apiData['INPOST_SENDER_LASTNAME'],
            'INPOST_SENDER_COMPANY_NAME' => $company_name ? $company_name : $apiData['INPOST_SENDER_COMPANY_NAME'],
            'INPOST_SENDER_PARCEL_LOCKER' => $parcel_locker,
            'CUSTOMER_REFERENCE' => '',
            'INPOST_SENDER_DISPATCH_POINT' => '',
            'INPOST_CUSTOMER_REFERENCE' => $customer_reference,
            'INPOST_SENDER_COUNTRY' => constant('InpostConnector::INPOST_COUNTRY_'.Configuration::get('INPOST_COUNTRY')),
            'parcels_lockers' => $allParcelLockers,
			'dispatch_points' => $allActiveDispatchPoints,
			'INPOST_DEFAULT_SEND_METHOD' => Configuration::get('INPOST_DEFAULT_SEND_METHOD'),
			'EE_INPOST_DEFAULT_DISPATCH_POINT' => Configuration::get('EE_INPOST_DEFAULT_DISPATCH_POINT')
        );
    }
    public static function getConfigFieldsValues()
    {
        $paymentModules = Module::getPaymentModules();
        $payments = [];
        foreach ($paymentModules as $payment) {
            $payments['INPOST_PARCEL_LOCKERS_PAYMENT_'.$payment['name']] = Configuration::get('INPOST_PARCEL_LOCKERS_PAYMENT_'.$payment['name']);
            $payments['INPOST_PARCEL_LOCKERS_COD_PAYMENT_'.$payment['name']] = Configuration::get('INPOST_PARCEL_LOCKERS_COD_PAYMENT_'.$payment['name']);
            $payments['INPOST_X_BORDER_PAYMENT_'.$payment['name']] = Configuration::get('INPOST_X_BORDER_PAYMENT_'.$payment['name']);
        }

        return array_merge(
            array(
            'INPOST_LOGIN' => Tools::getValue('INPOST_LOGIN', Configuration::get('INPOST_LOGIN')),
            'INPOST_PASSWORD' => Tools::getValue('INPOST_PASSWORD', '****************'),
            'INPOST_COUNTRY' => Tools::getValue('INPOST_COUNTRY', Configuration::get('INPOST_COUNTRY')),
            'INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS' => Tools::getValue('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS', Configuration::get('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS')),
            'INPOST_AVAILABLE_SERVICES_CROSSBORDER' => Tools::getValue('INPOST_AVAILABLE_SERVICES_CROSSBORDER', Configuration::get('INPOST_AVAILABLE_SERVICES_CROSSBORDER')),
            'INPOST_AVAILABLE_SERVICES_RETURNS' => Tools::getValue('INPOST_AVAILABLE_SERVICES_RETURNS', Configuration::get('INPOST_AVAILABLE_SERVICES_RETURNS')),
            'INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS_COD' => Tools::getValue('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS_COD', Configuration::get('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS_COD')),
            'INPOST_PARCERLS_LOCKERS_COD_IBAN' => Tools::getValue('INPOST_PARCERLS_LOCKERS_COD_IBAN', Configuration::get('INPOST_PARCERLS_LOCKERS_COD_IBAN')),
            'INPOST_DEFAULT_PARCEL_SIZE' => Tools::getValue('INPOST_DEFAULT_PARCEL_SIZE', Configuration::get('INPOST_DEFAULT_PARCEL_SIZE')),
            'INPOST_DEFAULT_STATUS_AFTER_LABEL_GENERATION' => Tools::getValue('INPOST_DEFAULT_STATUS_AFTER_LABEL_GENERATION', Configuration::get('INPOST_DEFAULT_STATUS_AFTER_LABEL_GENERATION')),
            'INPOST_DEFAULT_STATUS_AFTER_PARCEL_DELIVERY' => Tools::getValue('INPOST_DEFAULT_STATUS_AFTER_PARCEL_DELIVERY', Configuration::get('INPOST_DEFAULT_STATUS_AFTER_PARCEL_DELIVERY')),
            'EE_INPOST_API_URL' => Tools::getValue('EE_INPOST_API_URL', Configuration::get('EE_INPOST_API_URL')),
            'INPOST_API_URL_POLAND' => Configuration::get('INPOST_API_URL_POLAND'),
            'INPOST_API_URL_FRANCE' => Configuration::get('INPOST_API_URL_FRANCE'),
            'INPOST_API_URL_ITALY' => Configuration::get('INPOST_API_URL_ITALY'),
            'INPOST_CUSTOMER_REFERENCE' => Configuration::get('INPOST_CUSTOMER_REFERENCE'),
            'INPOST_PARCERLS_LOCKERS_RETURNS_URL' => Configuration::get('INPOST_PARCERLS_LOCKERS_RETURNS_URL'),
            'INPOST_PARCERLS_LOCKERS_RETURNS_DESCRIPTION' => Configuration::get('INPOST_PARCERLS_LOCKERS_RETURNS_DESCRIPTION')
            ),
            $payments
        );
    }

    public static function getUserAddress($address_id)
    {
        $customerAddress = new Address($address_id);

        $addr = array(
            'company_name' => $customerAddress->company,
            'firstname_and_lastname' => $customerAddress->firstname.' '.$customerAddress->lastname,
            'address' => $customerAddress->address1.' '.$customerAddress->address2,
            'postcode' => $customerAddress->postcode,
            'city' => $customerAddress->city,
            'country' => $customerAddress->country

        );
        return $addr;
    }

    public static function getMethodByCarrierId($carrier_id)
    {
        $sql = "SELECT * FROM " . _DB_PREFIX_ . "inpost_delivery_modules WHERE id_module = {$carrier_id}";
        $module =  Db::getInstance()->ExecuteS($sql);

        if (isset($module[0])) //Tools::getIsset return false on array
        {
           return $module[0];
        }

    }

    public static function updateOldCarrier($new, $reference)
    {
        Db::getInstance()->update('inpost_delivery_modules', array(
            'id_module'  => (int)$new,
            'reference' => (int)$new
        ), 'reference='.(int)$reference);
    }

    public static function updateLabel($package_id)
    {
        Db::getInstance()->update('inpost_labels', array(
            'label_downloaded' => 1
        ), 'package_id="'.$package_id.'"');
    }

    public static function saveSticker($package, $id_order, $label_downloaded)
    {

        Db::getInstance()->delete('inpost_labels', 'package_id="'.(string)$package->id.'"', 1);

        return Db::getInstance()->insert('inpost_labels', array(
            'order_id'      => $id_order,
            'package_id'    => pSQL($package->id),
            'date_label_generation' => date('Y-m-d H:i:s'),
            'label_downloaded' => (bool)$label_downloaded
        ));
    }
    public static function saveStatuses()
    {
        Configuration::updateValue('INPOST_DEFAULT_STATUS_AFTER_LABEL_GENERATION', Tools::getValue('INPOST_DEFAULT_STATUS_AFTER_LABEL_GENERATION'));
        Configuration::updateValue('INPOST_DEFAULT_STATUS_AFTER_PARCEL_DELIVERY', Tools::getValue('INPOST_DEFAULT_STATUS_AFTER_PARCEL_DELIVERY'));
    }

    public static function savePackage($response, $id_order, $country_id, $id_customer = 0, $dispatch_points_id = 0)
    {
        if (!$response->status_updated_at) {
            $response->status_updated_at = Date('Y-m-d H:i:s');
        }
        $database = Db::getInstance()->insert('inpost_packages', array(
            'receiver_id'               => (int)$id_customer,
            'order_id'                  => pSQL($id_order),
            'parcel_no'                 => $response->id,
            'created_at'                => date('Y-m-d H:i:s', strtotime($response->created_at)),
            'status'                    => $response->status,
            'status_updated_at'         => date('Y-m-d H:i:s', strtotime($response->status_updated_at)),
            'additional1'               => pSQL($response->additional1),
            'additional2'               => pSQL($response->additional2),
            'avizo_time'                => pSQL($response->avizo_time),
            'cod_amount'                => pSQL($response->cod_amount),
            'customer_reference'        => pSQL($response->customer_reference),
            'expiration_time'           => pSQL($response->expiration_time),
            'insurance_amount'          => pSQL($response->insurance_amount),
            'letter_type'               => pSQL($response->letter_type),
            'pickup_expiration_time'    => pSQL($response->pickup_expiration_time),
            'sender_building_no'        => pSQL($response->sender_address->building_no),
            'sender_city'               => pSQL($response->sender_address->city),
            'sender_company_name'       => pSQL($response->sender_address->company_name),
            'sender_address_email'      => pSQL($response->sender_address->email),
            'sender_first_name'         => pSQL($response->sender_address->first_name),
            'sender_flat_no'            => pSQL($response->sender_address->flat_no),
            'sender_last_name'          => pSQL($response->sender_address->last_name),
            'sender_address_phone'      => pSQL($response->sender_address->phone),
            'sender_post_code'          => pSQL($response->sender_address->post_code),
            'sender_province'           => pSQL($response->sender_address->province),
            'sender_street'             => pSQL($response->sender_address->street),
            'sender_email'              => pSQL($response->sender_email),
            'sender_phone'              => pSQL($response->sender_phone),
            'service'                   => pSQL($response->service),
            'size'                      => pSQL($response->size),
            'skip_pickup_point'         => pSQL($response->skip_pickup_point),
            'source_machine_id'         => pSQL($response->source_machine_id),
            'target_machine_id'         => pSQL($response->target_machine_id),
            'calculated_amount'         => pSQL($response->calculated_amount),
            'charged_amount'            => pSQL($response->charged_amount),
            'dropoff_code'              => pSQL($response->dropoff_code),
            'receiver_phone'            => pSQL($response->receiver_phone),
            'receiver_email'            => pSQL($response->receiver_email),
            'receiver_firstname'        => pSQL($response->receiver->first_name),
            'receiver_lastname'         => pSQL($response->receiver->last_name),
            'receiver_building_no'      => pSQL($response->receiver->address->building_no),
            'receiver_city'             => pSQL($response->receiver->address->city),
            'receiver_flat_no'          => pSQL($response->receiver->address->flat_no),
            'receiver_post_code'        => pSQL($response->receiver->address->post_code),
            'receiver_street'           => pSQL($response->receiver->address->street),
            'receiver_province'         => pSQL($response->receiver->address->province),
            'receiver_company_name'     => pSQL($response->receiver->company_name),
            'dispatch_point_id'         => $dispatch_points_id,
            'receiver_country'          => $country_id
        ));
        return (bool)$database;
    }
    public static function savePackageCrossBorder($response, $id_order, $country_id, $sizesInCm, $id_customer = 0, $dispatch_points_id = 0)
    {

        $a = array(
            'receiver_id'               => (int)$id_customer,
            'order_id'                  => pSQL($id_order),
            'parcel_no'                 => $response->id,
            'created_at'                => date('Y-m-d H:i:s', strtotime($response->created_on)),
            'delivery_price_amount'     => $response->delivery_price->amount,
            'delivery_price_currency'   => $response->delivery_price->currency,
            'status'                    => $response->status->code,
            'status_updated_at'         => date('Y-m-d'),
            'additional1'               =>'',
            'additional2'               => '',
            'avizo_time'                => '',
            'cod_amount'                => '',
            'customer_reference'        => $response->reference_id,
            'expiration_time'           => '',
            'letter_type'               => '',
            'pickup_expiration_time'    => '',
            'sender_company_name'       => pSQL($response->sender->company_name),
            'sender_address_email'      => pSQL($response->sender->email),
            'sender_first_name'         => pSQL($response->sender->first_name),
            'sender_last_name'          => pSQL($response->sender->last_name),
            'sender_address_phone'      => pSQL($response->sender->phone),
            'sender_province'           => '',
            'sender_email'              => pSQL($response->sender->email),
            'sender_phone'              => pSQL($response->sender->phone),
            'service'                   => pSQL($response->service),
            'size'                      => '',
            'skip_pickup_point'         => '',
            'source_machine_id'         => '',
            'target_machine_id'         => '',
            'calculated_amount'         => '',
            'charged_amount'            => '',
            'dropoff_code'              => '',
            'receiver_phone'            => pSQL($response->recipient->phone),
            'receiver_email'            => pSQL($response->recipient->email),
            'receiver_firstname'        => pSQL($response->recipient->first_name),
            'receiver_lastname'         => pSQL($response->recipient->last_name),
            'receiver_province'         => '',
            'receiver_company_name'     => pSQL($response->recipient->company_name),
            'receiver_country_code'     => pSQL($response->recipient->country_code),
            'dispatch_point_id'         => pSQL($dispatch_points_id),
            'receiver_country'          => pSQL($country_id),
            'tracking_number'           => pSQL($response->tracking_number),
            'sender_method'             => pSQL($response->sender_method),
            'recipient_method'          => pSQL($response->recipient_method),

            'declared_value_currency'   => pSQL($response->declared_value->currency),
            'declared_value_amount'     => pSQL($response->declared_value->amount),
            'declared_weight_amount'    => pSQL($response->declared_weight->amount),
            'declared_weight_unit'      => pSQL($response->declared_weight->unit),
        );
        if ($response->insurance) {
            $a['insurance_amount']        = pSQL($response->insurance->amount);
            $a['insurance_currency']      = pSQL($response->insurance->currency);
        }
        if ($response->declared_dimensions) {
            $a['declared_dimensions_height'] = pSQL($response->declared_dimensions->height);
            $a['declared_dimensions_length'] = pSQL($response->declared_dimensions->length);
            $a['declared_dimensions_unit'] = pSQL($response->declared_dimensions->unit);
            $a['declared_dimensions_width'] = pSQL($response->declared_dimensions->width);
        } else {
            $a['declared_dimensions_height'] = pSQL($sizesInCm['height']);
            $a['declared_dimensions_length'] = pSQL($sizesInCm['length']);
            $a['declared_dimensions_unit'] = pSQL('cm');
            $a['declared_dimensions_width'] = pSQL($sizesInCm['width']);
        }
        if ($response->recipient->address) {
            $a['receiver_building_no'] = pSQL($response->recipient->address->building_number);
                $a['receiver_city']       = pSQL($response->recipient->address->city);
                $a['receiver_flat_no']    = pSQL($response->recipient->address->flat_number);
                $a['receiver_post_code']  = pSQL($response->recipient->address->zip_code);
                $a['receiver_street']     = pSQL($response->recipient->address->street);

        }
        if ($response->sender->address) {
            $a['sender_building_no'] = pSQL($response->sender->address->building_number);
                $a['sender_city']        = pSQL($response->sender->address->city);
                $a['sender_street']      = pSQL($response->sender->address->street);
                $a['sender_flat_no']     = pSQL($response->sender->address->flat_number);
                $a['sender_post_code']   = pSQL($response->sender->address->zip_code);

        }

        if ($response->recipient->pop) {
            $a['target_machine_id'] = pSQL($response->recipient->pop->id);
                $a['size'] = pSQL($response->recipient->pop->size);

        }
        if ($response->sender->pop) {
            $a['source_machine_id'] = pSQL($response->sender->pop->id);
                $a['size'] = pSQL($response->sender->pop->size);

        }

        $database = Db::getInstance()->insert('inpost_packages', $a);
        return (bool)$database;
    }


    public static function getDispatchPointFieldsToEditValues($id)
    {
        $dispatchPoint = InpostDispatchPoints::getDispatchPointById($id);
        if ($dispatchPoint) {
            return array(
                'DISPATCH_COUNTRY' => $dispatchPoint['country'],
                'DISPATCH_POSTCODE' => $dispatchPoint['postcode'],
                'DISPATCH_CITY' => $dispatchPoint['city'],
                'DISPATCH_STREET' => $dispatchPoint['street'],
                'DISPATCH_BUILDING_NO' => $dispatchPoint['building_no'],
                'DISPATCH_FLAT_NO' => $dispatchPoint['flat_no'],
                'DISPATCH_PHONE_NO' => $dispatchPoint['phone_no'],
                'DISPATCH_EMAIL' => $dispatchPoint['email'],
                'DISPATCH_NAME' => $dispatchPoint['name'],
                'DISPATCH_COMMENTS' => $dispatchPoint['comments'],
                'DISPATCH_OFFICE_HOURS' => $dispatchPoint['office_hours'],
                'DISPATCH_HREF' => $dispatchPoint['href'],
                'INPOST_DISPATCH_POINT_SERVICE' => $dispatchPoint['inpost_service']


            );
        }
    }
    public static function getDispatchPointFieldsValues()
    {
        $country = Configuration::get('INPOST_COUNTRY');
        $countryId = 0;
        switch ($country) {
            case 1:
                $countryId = Db::getInstance()->getValue('SELECT id_country FROM '._DB_PREFIX_.'country WHERE iso_code = "PL"');
                break;
            case 2:
                $countryId = Db::getInstance()->getValue('SELECT id_country FROM '._DB_PREFIX_.'country WHERE iso_code = "FR"');
                break;
            case 3:
                $countryId = Db::getInstance()->getValue('SELECT id_country FROM '._DB_PREFIX_.'country WHERE iso_code = "IT"');
                break;
        }
        return array(
            'DISPATCH_COUNTRY'      => $countryId,
            'DISPATCH_POSTCODE'     => Tools::getValue('DISPATCH_POSTCODE'),
            'DISPATCH_CITY'         => Tools::getValue('DISPATCH_CITY'),
            'DISPATCH_STREET'       => Tools::getValue('DISPATCH_STREET'),
            'DISPATCH_BUILDING_NO'  => Tools::getValue('DISPATCH_BUILDING_NO'),
            'DISPATCH_FLAT_NO'      => Tools::getValue('DISPATCH_FLAT_NO'),
            'DISPATCH_PHONE_NO'     => Tools::getValue('DISPATCH_PHONE_NO'),
            'DISPATCH_EMAIL'        => Tools::getValue('DISPATCH_EMAIL'),
            'DISPATCH_NAME'         => Tools::getValue('DISPATCH_NAME'),
            'DISPATCH_COMMENTS'     => Tools::getValue('DISPATCH_COMMENTS'),
            'DISPATCH_OFFICE_HOURS' => Tools::getValue('DISPATCH_OFFICE_HOURS'),
            'DISPATCH_HREF'         => Tools::getValue('DISPATCH_HREF'),
            'INPOST_DISPATCH_POINT_SERVICE' => Tools::getValue('INPOST_DISPATCH_POINT_SERVICE')
        );
    }
    public static function saveDispatchPoint($dispatch_point)
    {
        $countryId = InpostModel::getPrestaCountryId();

        $currentId = Db::getInstance()->getValue("
          SELECT 
            id
          FROM "._DB_PREFIX_."inpost_dispatch_points 
          WHERE href = '" . pSQL(str_replace('v4/', '', $dispatch_point->_links->self->href)) ."'          
        ");

        if($currentId) {
            return Db::getInstance()->update('inpost_dispatch_points', array(
                    'country' => Tools::getValue('DISPATCH_COUNTRY') ? Tools::getValue('DISPATCH_COUNTRY') : $countryId,
                    'postcode' => Tools::getValue('DISPATCH_POSTCODE') ? Tools::getValue('DISPATCH_POSTCODE') : $dispatch_point->address->post_code,
                    'city' => Tools::getValue('DISPATCH_CITY') ? Tools::getValue('DISPATCH_CITY') : $dispatch_point->address->city,
                    'street' => Tools::getValue('DISPATCH_STREET') ? Tools::getValue('DISPATCH_STREET') : $dispatch_point->address->street,
                    'building_no' => Tools::getValue('DISPATCH_BUILDING_NO') ? Tools::getValue('DISPATCH_BUILDING_NO') : $dispatch_point->address->building_no,
                    'flat_no' => Tools::getValue('DISPATCH_FLAT_NO') ? Tools::getValue('DISPATCH_FLAT_NO') : $dispatch_point->address->flat_no,
                    'phone_no' => Tools::getValue('DISPATCH_PHONE_NO') ? Tools::getValue('DISPATCH_PHONE_NO') : $dispatch_point->phone,
                    'email' => Tools::getValue('DISPATCH_EMAIL') ? Tools::getValue('DISPATCH_EMAIL') : $dispatch_point->customer_email,
                    'name' => Tools::getValue('DISPATCH_NAME') ? Tools::getValue('DISPATCH_NAME') : $dispatch_point->name,
                    'comments' => Tools::getValue('DISPATCH_COMMENTS') ? Tools::getValue('comments') : $dispatch_point->comments,
                    'office_hours' => Tools::getValue('DISPATCH_OFFICE_HOURS') ? Tools::getValue('DISPATCH_OFFICE_HOURS') : $dispatch_point->office_hours,
                    'status' => strtoupper($dispatch_point->status),
                ), 'id='.(int)$currentId
            );
        } else {
            return Db::getInstance()->insert('inpost_dispatch_points', array(
                'country' => Tools::getValue('DISPATCH_COUNTRY') ? Tools::getValue('DISPATCH_COUNTRY') : $countryId,
                'postcode' => Tools::getValue('DISPATCH_POSTCODE') ? Tools::getValue('DISPATCH_POSTCODE') : $dispatch_point->address->post_code,
                'city' => Tools::getValue('DISPATCH_CITY') ? Tools::getValue('DISPATCH_CITY') : $dispatch_point->address->city,
                'street' => Tools::getValue('DISPATCH_STREET') ? Tools::getValue('DISPATCH_STREET') : $dispatch_point->address->street,
                'building_no' => Tools::getValue('DISPATCH_BUILDING_NO') ? Tools::getValue('DISPATCH_BUILDING_NO') : $dispatch_point->address->building_no,
                'flat_no' => Tools::getValue('DISPATCH_FLAT_NO') ? Tools::getValue('DISPATCH_FLAT_NO') : $dispatch_point->address->flat_no,
                'phone_no' => Tools::getValue('DISPATCH_PHONE_NO') ? Tools::getValue('DISPATCH_PHONE_NO') : $dispatch_point->phone,
                'email' => Tools::getValue('DISPATCH_EMAIL') ? Tools::getValue('DISPATCH_EMAIL') : $dispatch_point->customer_email,
                'name' => Tools::getValue('DISPATCH_NAME') ? Tools::getValue('DISPATCH_NAME') : $dispatch_point->name,
                'comments' => Tools::getValue('DISPATCH_COMMENTS') ? Tools::getValue('comments') : $dispatch_point->comments,
                'office_hours' => Tools::getValue('DISPATCH_OFFICE_HOURS') ? Tools::getValue('DISPATCH_OFFICE_HOURS') : $dispatch_point->office_hours,
                'href' => str_replace('v4/', '', $dispatch_point->_links->self->href),
                'status' => strtoupper($dispatch_point->status),
            ));
        }
    }

    public static function saveXBorderDispatchPoint($dispatch_point)
    {
      $x_border_id = Db::getInstance()->getValue('SELECT x_border_id FROM '._DB_PREFIX_.'inpost_dispatch_points WHERE x_border_id = '.$dispatch_point->id);
      if (!$x_border_id) {
        Db::getInstance()->update('inpost_dispatch_points', array(
            'x_border_id' => $dispatch_point->id
        ), 'name = "' . $dispatch_point->name . '"');
        $x_border_id = Db::getInstance()->getValue('SELECT x_border_id FROM '._DB_PREFIX_.'inpost_dispatch_points WHERE x_border_id = '.$dispatch_point->id);
        if (!$x_border_id) {
          $countryId = InpostModel::getPrestaCountryId();

          return Db::getInstance()->insert('inpost_dispatch_points', array(
             'country' => $countryId,
             'postcode' =>  $dispatch_point->address->zip_code,
             'city' => $dispatch_point->address->city,
             'street' => $dispatch_point->address->street,
             'building_no' => $dispatch_point->address->building_number,
             'flat_no' => $dispatch_point->address->flat_number,
             'phone_no' => '',
             'email' => '',
             'name' => $dispatch_point->name,
             'comments' => '',
             'office_hours' => '',
             'href' => '',
             'status' => strtoupper($dispatch_point->status),
             'x_border_id' => $dispatch_point->id
          ));
        }
      }
    }
    public static function updateDispatchPoint($dispatch_point)
    {
        $countryId = InpostModel::getPrestaCountryId();

        return Db::getInstance()->update('inpost_dispatch_points', array(
            'country' => Tools::getValue('DISPATCH_COUNTRY') ? Tools::getValue('DISPATCH_COUNTRY') : $countryId,
            'postcode' => Tools::getValue('DISPATCH_POSTCODE'),
            'city' => pSQL(Tools::getValue('DISPATCH_CITY')),
            'street' => pSQL(Tools::getValue('DISPATCH_STREET')),
            'building_no' => pSQL(Tools::getValue('DISPATCH_BUILDING_NO')),
            'flat_no' => pSQL(Tools::getValue('DISPATCH_FLAT_NO')),
            'phone_no' => pSQL(Tools::getValue('DISPATCH_PHONE_NO')),
            'email' => pSQL(Tools::getValue('DISPATCH_EMAIL')),
            'name' => pSQL(Tools::getValue('DISPATCH_NAME')),
            'comments' => pSQL(Tools::getValue('DISPATCH_COMMENTS')),
            'office_hours' => pSQL(Tools::getValue('DISPATCH_OFFICE_HOURS')),
            'href' => $dispatch_point->_links->self->href,
            'status' => $dispatch_point->status,
            'inpost_service' => Tools::getValue('INPOST_DISPATCH_POINT_SERVICE')
        ), 'href="'.$dispatch_point->_links->self->href.'"');
    }

    public static function connectParcelLockerWithCart($fields)
    {
        if (!isset($fields['x_border']))
            $fields['x_border'] = NULL;
        return Db::getInstance()->insert('inpost_parcel_lockers_orders', array(
            'parcel_locker' => $fields['parcel_locker'],
            'order_id' => '',
            'cart_id' => $fields['cart_id'],
            'x_border' => $fields['x_border'],
            'phone_no' => $fields['phone_no']
        ));
    }

    public static function addPhoneNoToParcelLockerOrder($fields)
    {
        return Db::getInstance()->update('inpost_parcel_lockers_orders', array(
            'phone_no' => $fields['phone_no'],
        ), 'cart_id = '.$fields['cart_id']);
    }

    public static function updateParcelLockerToOrder($fields)
    {
        return Db::getInstance()->update('inpost_parcel_lockers_orders', array(
            'order_id' => $fields['order_id'],

        ), 'cart_id='.$fields['cart_id']);
    }
    public static function checkIsXBorderOrder($order_id)
    {
        return Db::getInstance()->getValue("SELECT x_border FROM "._DB_PREFIX_."inpost_parcel_lockers_orders WHERE order_id =".(int)$order_id." ORDER BY id DESC");
    }
    public static function getSelectedParcel($order_id)
    {
        return Db::getInstance()->getValue("SELECT parcel_locker FROM "._DB_PREFIX_."inpost_parcel_lockers_orders WHERE order_id =".(int)$order_id." ORDER BY id DESC");
    }

    public static function getSelectedParcelForCart($cart_id)
    {
        return Db::getInstance()->getValue("SELECT parcel_locker FROM "._DB_PREFIX_."inpost_parcel_lockers_orders WHERE cart_id =".(int)$cart_id." ORDER BY id DESC");
    }
    public static function getParcelLockerPhoneNumberForCart($cart_id)
    {
        return Db::getInstance()->getValue("SELECT phone_no FROM "._DB_PREFIX_."inpost_parcel_lockers_orders WHERE cart_id =".(int)$cart_id." ORDER BY id DESC");
    }
    public static function getCountryNameById($country_id)
    {
        if ($country_id) {
            return Db::getInstance()->getValue('SELECT `name` FROM '._DB_PREFIX_.'country_lang WHERE id_country= '.$country_id." AND id_lang = ".Context::getContext()->language->id);
        }
        return false;
    }
    public static function getCountryIsoCodeById($country_id)
    {
        if ($country_id) {
            return Db::getInstance()->getValue('SELECT `iso_code` FROM '._DB_PREFIX_.'country WHERE id_country= '.$country_id);
        }
        return false;
    }
    public static function getCountryNameByIsoCode($iso_code)
    {
        if ($iso_code) {
            return Db::getInstance()->getValue('SELECT `name` FROM '._DB_PREFIX_.'country_lang icl LEFT JOIN '._DB_PREFIX_.'country ic ON icl.id_country=ic.id_country  WHERE iso_code= "'.$iso_code.'" AND id_lang = '.Context::getContext()->language->id);
        }
        return false;
    }

    public static function getCountryIdByName($name)
    {
        if ($name) {
            return Db::getInstance()->getValue('SELECT `id_country` FROM '._DB_PREFIX_.'country_lang WHERE `name` like "%'.$name.'%" AND id_lang = '.Context::getContext()->language->id);
        }
        return false;
    }

    public static function getOrderIdByParcelNo($parcel_no)
    {
        return Db::getInstance()->getValue('SELECT order_id FROM '._DB_PREFIX_.'inpost_packages WHERE parcel_no ="'.$parcel_no.'"');
    }


    public static function splitAddress($address1, $address2)
    {
        $row = array('address1' => $address1, 'address2' => $address2);
        $check = $row['address1'];
        $a2 = false;
        if (preg_match('#^(.*)(\d{2}-\d{3})\s*(.*)$#i', $check, $matches)
            or (preg_match('#^(.*)(\d{2}-\d{3})\s*(.*)$#i', $row['address2'], $matches) and $a2 = true)) {
            $row['postcode'] = $matches[2];
            if ($matches[3]) {
                $row['city'] = $matches[3];
            }
            if ($a2) {
                $row['address2'] = $matches[1];
            } else {
                $check = $matches[1];
            }
        }
        $row['adres'] = $row['address1'].' '.$row['address2'];
        if (preg_match('#^(.*?[a-ząćęłóńśźżĄĆĘŁÓŃŚŹŻ]{3,}.*?)(\d+\s*[a-z]?(?:/\d+\s*[a-z]?)*)\s*(?:(?:m|lok)\.?|,|/)\s*(.*?)\s*$#i', $check, $matches)
            or preg_match('#^(.*?[a-ząćęłóńśźżĄĆĘŁÓŃŚŹŻ]{3,}.*?)(\d+\s*[a-z]?)\s*(?:/\s*(\d+\s*[a-z]?)\s*)?$#i', $check, $matches)
        ) {
            $row['street'] = $matches[1];
            $row['building_no'] = $matches[2];
            $row['flat_no'] = empty($matches[3]) ? '' : $matches[3];
        }
        if ((!empty($row['building_no']) && Tools::strlen($row['building_no']) > 20) || (!empty($row['flat_no']) && Tools::strlen($row['flat_no']) > 10)) {
            $row['street'] = $row['address1'];
            $row['building_no'] = ' ';
            $row['flat_no'] = '';
        }
        if (empty($row['street']) && !empty($check)) {
            $row['street'] = $check;
            if (!isset($row['building_no'])) {
                $row['building_no'] = '';
            }
            if (!isset($row['flat_no'])) {
                $row['flat_no'] = '';
            }
        }
        if ((empty($row['building_no']) || !Tools::strlen(trim($row['building_no'])))
            && preg_match('#^\s*(\d+[a-z]*(?:[/m]\d+[a-z]*)?)\s+([a-z].*)#i', $address1, $matches)
            && !preg_match('#^\s*(\d+[a-z]*(?:[/m]\d+[a-z]*)?)\s+([a-z].*)#i', $matches[2].' '.$matches[1])
        ) {
            return self::splitAddress($matches[2].' '.$matches[1], $address2);
        }
        return $row;
    }

    public static function saveFreeShipping()
    {
        Configuration::updateValue('PARCELS_LOCKERS_FREE_SHIPPING', Tools::getValue('PARCELS_LOCKERS_FREE_SHIPPING'));
        Configuration::updateValue('PARCELS_LOCKERS_COD_FREE_SHIPPING', Tools::getValue('PARCELS_LOCKERS_COD_FREE_SHIPPING'));
    }

    public static function updatePackage($response)
    {
        Db::getInstance()->update('inpost_packages', array(
            'customer_reference'        => $response->customer_reference,
            'size'                      => $response->size,
        ), 'parcel_no ="'.$response->id.'"');
    }

    public static function insertData()
    {
        Db::getInstance()->insert('tab', array(
            'id_parent' => 0,
            'class_name' => 'AdminModules',
            'module' => 'inpost',
            'active' => 1,
            'hide_host_mode' => 0
        ));
        $tab_id = Db::getInstance()->Insert_ID();

        return Db::getInstance()->insert('tab_lang', array(
            'id_tab' => $tab_id,
            'id_lang' => Context::getContext()->language->id,
            'name' => 'InPost'
        ));
    }

    public static function importAvailableCrossBorderTypes($fields, $cron = false)
    {
        $weights = array(
            '1', '2', '5', '10','15','20','25'
        );


        if ($fields) {
            foreach ($fields as $field) {

                $a = Db::getInstance()->getValue("SELECT id FROM "._DB_PREFIX_."x_border_types WHERE from_country ='".$field->sender_country_code."' AND to_country = '".$field->recipient_country_code."' AND recipient_method ='".$field->recipient_method."'");
                if ($a || ($field->recipient_country_code == 'PL' && $field->sender_country_code == 'PL')) {
                    continue;
                }
                if ($cron === true) {
                    Configuration::updateValue('X_BORDER_NEW_ROUTE', true);
                }

                Db::getInstance()->insert('x_border_types', array(
                    'from_country' => $field->sender_country_code,
                    'to_country' => $field->recipient_country_code,
                    'recipient_method' => $field->recipient_method,
                    'sender_method' => $field->sender_method,
                    'insurance_amount' => $field->services[0]->insurance[0]->max_value->amount,
                    'insurance_currency' => $field->services[0]->insurance[0]->max_value->currency,
                    'insurance_cost_amount' => $field->services[0]->insurance[0]->price->amount,
                    'insurance_cost_currency' => $field->services[0]->insurance[0]->price->currency,

                ));

                $type_id = Db::getInstance()->Insert_ID();
                foreach ($weights as $weight) {
                    Db::getInstance()->insert('x_border_types_details', array(
                        'id_border_type' => $type_id,
                        'parcel_weight' => $weight,
                        'cod' => '',
                        'currency' => ''
                    ));
                }

            }
        }
    }

    public static function getXBorderPrices()
    {

        $order_by = Tools::getValue('OrderBy', 'from_country asc, to_country asc, recipient_method asc, sender_method');
        $order_way = Tools::getValue('OrderWay', 'asc');
        $filter_sender_country = Tools::getValue('cross_border_sender_country');
        $filter_receiver_country = Tools::getValue('cross_border_receiver_country');
        $sql = "SELECT * FROM "._DB_PREFIX_."x_border_types ixbt";
        $filters = [];
        if ($filter_receiver_country) {
            $filters[] = "ixbt.to_country like '%".$filter_receiver_country."%'";
        }
        if ($filter_sender_country) {
            $filters[] = "ixbt.from_country like '%".$filter_sender_country."%'";
        }
        if ($filters) {
            $sql .= ' WHERE '.implode(' AND ', $filters);
        }
        $sql .= " ORDER BY {$order_by} {$order_way}";

        $types = $types = Db::getInstance()->executeS($sql);

        foreach ($types as $key => &$type) {
            $type['from_country'] = InpostModel::getCountryNameByIsoCode($type['from_country']);
            $type['to_country'] = InpostModel::getCountryNameByIsoCode($type['to_country']);

            if ($type['recipient_method'] == 'ToDoor') {
                $type['recipient_method'] = 'Na adres';
            } else {
                $type['recipient_method'] = 'Do paczkomatu';
            }
            if ($type['sender_method'] == 'FromDoor') {
                $type['sender_method'] = 'Z adresu';
            } else {
                $type['sender_method'] = 'Z paczkomatu';
            }
            $type_Details = Db::getInstance()->executeS("SELECT * FROM "._DB_PREFIX_."x_border_types_details WHERE id_border_type =".$type['id']);

            foreach ($type_Details as $type_details_single) {
                $types[$key]['weight'][$type_details_single['parcel_weight']] = $type_details_single['parcel_price'];
            }

        }

        if (!Tools::getValue('OrderBy'))
        {
          $from_country = array();
          $to_country = array();
          $recipient_method = array();
          $sender_method = array();
          foreach ($types as $key => $row) {
            $from_country[$key]  = $row['from_country'];
            $to_country[$key] = $row['to_country'];
            $recipient_method[$key] = $row['recipient_method'];
            $sender_method[$key] = $row['sender_method'];
          }


          array_multisort($from_country, SORT_ASC, $to_country, SORT_ASC,$recipient_method, SORT_ASC, $sender_method, SORT_ASC, $types);
        } else {
          if ($order_way == 'asc') {
            $sort = SORT_ASC;
          } else {
            $sort = SORT_DESC;
          }

          $types = self::array_orderby($types, Tools::getValue('OrderBy'), $sort);
        }
        return $types;

    }
    public static function array_orderby()
    {
        $args = func_get_args();
        $data = array_shift($args);
        foreach ($args as $n => $field) {
            if (is_string($field)) {
                $tmp = array();
                foreach ($data as $key => $row)
                    $tmp[$key] = $row[$field];
                $args[$n] = $tmp;
                }
        }
        $args[] = &$data;
        call_user_func_array('array_multisort', $args);
        return array_pop($args);
    }
    public static function updateXPrices()
    {

        $prices = Tools::getValue('type');
        foreach ($prices as $id_type => $price) {
            foreach ($price as $weight => $price_value) {
                if ($price_value >= 0 && $price_value != "") {
                    Db::getInstance()->update('x_border_types_details', array(
                        'parcel_price' => (float) str_replace(',', '.', $price_value)
                    ), 'parcel_weight='.$weight.' AND id_border_type ='.$id_type);
                } else {

                    Db::getInstance()->update('x_border_types_details', array(
                    'parcel_price' => null
                    ), 'parcel_weight='.$weight.' AND id_border_type ='.$id_type, 0, true);
                }
            }
        }

    }


    public static function getPrestaCountryId()
    {
        $country = Configuration::get('INPOST_COUNTRY');
        $countryId = 0;
        switch ($country) {
            case 1:
                $countryId = Db::getInstance()->getValue('SELECT id_country FROM '._DB_PREFIX_.'country WHERE iso_code = "PL"');
                break;
            case 2:
                $countryId = Db::getInstance()->getValue('SELECT id_country FROM '._DB_PREFIX_.'country WHERE iso_code = "FR"');
                break;
            case 3:
                $countryId = Db::getInstance()->getValue('SELECT id_country FROM '._DB_PREFIX_.'country WHERE iso_code = "IT"');
                break;
        }

        return $countryId;
    }


    public static function checkNeedSendFromMachine($packages)
    {
        return Db::getInstance()->executeS('SELECT parcel_no, tracking_number
          FROM '._DB_PREFIX_.'inpost_packages
          WHERE source_machine_id IS NOT NULL
          AND source_machine_id <> ""
          AND (parcel_no IN("'.implode('","', $packages).'")
            OR tracking_number IN ("'.implode('","', $packages).'")
            )
        ');
    }
    public static function getReturnUrl()
    {

        if (Configuration::get('INPOST_AVAILABLE_SERVICES_RETURNS')) {
            return Configuration::get('INPOST_PARCERLS_LOCKERS_RETURNS_URL');
        }

        return false;

    }
    public function hookDisplayTop()
    {
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            $this->context->controller->addJS($this->_path . 'views/js/1.5/front_hook.js');
        } else {
            $this->context->controller->addJS($this->_path . 'views/js/front_hook.js');
        }
        $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 static function updateAvailableCrossBorderTypes($fields)
    {
        $weights = array(
            '1', '2', '5', '10','15','20','25'
        );


        if ($fields) {
            foreach ($fields as $field) {
                $a = Db::getInstance()->getValue("SELECT id FROM "._DB_PREFIX_."x_border_types WHERE from_country ='".$field->sender_country_code."' AND to_country = '".$field->recipient_country_code."' AND recipient_method ='".$field->recipient_method."'");
                if ($a) {
                    continue;
                }

                Db::getInstance()->insert('x_border_types', array(
                    'from_country' => $field->sender_country_code,
                    'to_country' => $field->recipient_country_code,
                    'recipient_method' => $field->recipient_method,
                    'sender_method' => $field->sender_method,
                    'insurance_amount' => $field->services->insurance[0]->max_value->amount,
                    'insurance_currency' => $field->services[0]->insurance[0]->max_value->currency,
                    'insurance_cost_amount' => $field->services[0]->insurance[0]->price->currency,
                    'insurance_cost_currency' => $field->services[0]->insurance[0]->price->currency,

                ));

                $type_id = Db::getInstance()->Insert_ID();
                foreach ($weights as $weight) {
                    Db::getInstance()->insert('x_border_types_details', array(
                        'id_border_type' => $type_id,
                        'parcel_weight' => $weight,
                        'parcel_price' => null,
                        'cod' => '',
                        'currency' => ''
                    ));
                }

            }
        }
    }
    public static function getCustomerPhone($order_id)
    {
        return Db::getInstance()->getValue("SELECT phone_no FROM "._DB_PREFIX_."inpost_parcel_lockers_orders WHERE order_id =".(int)$order_id." ORDER BY id DESC");
    }

    public static function checkTaxExist($tax_group_id)
    {
        return Db::getInstance()->getValue('SELECT id_tax_rules_group FROM ' . _DB_PREFIX_ . 'tax_rules_group WHERE id_tax_rules_group =' . $tax_group_id);
    }

    public static function saveParcelsLockersCartValuePercent()
    {
        Configuration::updateValue('INPOST_PERCENT_CART_VALUE_COD', Tools::getValue('PERCENT_OF_CART_VALUE'));
    }

    public static function addTrackingNumberToShipment($package_id, $tracking_number)
    {
        if ($package_id) {
            Db::getInstance()->update('inpost_packages', array(
                'tracking_number' => $tracking_number
            ), 'parcel_no = "' . $package_id . '"');
        }
    }

    public static function getAllXBorderPackagesWithProcessingStatus()
    {
        return DB::getInstance()->ExecuteS('SELECT * FROM '._DB_PREFIX_.'inpost_packages WHERE status = "Processing" AND (tracking_number IS NULL OR tracking_number = "")');
    }
    public static function changeStatusAfterDelivery($order_id)
    {
      if (Configuration::get('INPOST_DEFAULT_STATUS_AFTER_PARCEL_DELIVERY')) {
          $order = new Order($order_id);
          $order_state = new OrderState(Configuration::get('INPOST_DEFAULT_STATUS_AFTER_PARCEL_DELIVERY'));
          $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_PARCEL_DELIVERY'), $order, $use_existings_payment);
              $history->addWithemail();

          }


      }
    }
}
