<?php
/**
 *
 * NOTICE OF LICENSE
 *
 * @author     Artneo
 * @copyright  InPost
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 *
 *
 */

if (!defined('_PS_VERSION_')) {
    exit;
}

class InpostDeliveryModulesCore extends ObjectModel
{
    public $id;

    public $module_name;

    public $id_module;

    public $reference;

    const FILE = 'carrier';
    public static $definition = array(
        'table' => 'inpost_delivery_modules',
        'primary' => 'id',
        'multilang_shop' => true,
        'multishop' => true,
        'fields' => array(
            'id'    =>  array('type'    => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
            'module_name'               =>  array('type' => self::TYPE_STRING),
            'id_module'                 =>  array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
            'reference'                 =>  array('type' => self::TYPE_DATE, 'validate' => 'isUnsignedInt'),

        )
    );

    public static function getReferenceByIdCarrier($id_carrier)
    {
        return DB::getInstance()->getValue('
			SELECT `reference`
			FROM `'._DB_PREFIX_.'inpost_delivery_modules`
			WHERE `reference` = "'.(int)$id_carrier.'"
		');
    }

    public static function getIdCarrierByReference($id_reference)
    {
        return DB::getInstance()->getValue('
			SELECT id_module
			FROM `'._DB_PREFIX_.'inpost_delivery_modules`
			WHERE `reference` = "'.(int)$id_reference.' LIMIT 1"
		');
    }
    public static function getModulesDescriptions()
    {
      $inpost = Module::getInstanceByName('inpost');
      if ((int)Configuration::get('INPOST_COUNTRY') === 1) {
        $parcelsLockers = $inpost->l(Configuration::get('INPOST_PL_DESC_PL'), self::FILE);
        $parcelsLockersCod = $inpost->l(Configuration::get('INPOST_PL_DESC_PLC'), self::FILE);
        $xBorder = $inpost->l('Thanks to InPost Cross Border service you are able to collect your parcel in Parcel Locker or received them at home address. Services is available in 15 European Countries.', self::FILE);
        $xBorderCourier = $inpost->l('Thanks to InPost Cross Border service you are able to collect your parcel in Parcel Locker or received them at home address. Services is available in 15 European Countries.', self::FILE);
      } elseif ((int)Configuration::get('INPOST_COUNTRY') === 2) {
        $parcelsLockers = Configuration::get('INPOST_FR_DESC_PL');
        $parcelsLockersCod = Configuration::get('INPOST_FR_DESC_PLC');
        $xBorder = Configuration::get('X_BORDER_FR_DESC');
        $xBorderCourier = '';
      } elseif ((int)Configuration::get('INPOST_COUNTRY') === 3) {
        $parcelsLockers = Configuration::get('INPOST_IT_DESC_PL');
        $parcelsLockersCod = Configuration::get('INPOST_IT_DESC_PLC');
        $xBorder = Configuration::get('X_BORDER_IT_DESC');
        $xBorderCourier = '';
      } else {
        $parcelsLockers = '';
        $parcelsLockersCod = '';
        $xBorder = '';
        $xBorderCourier = '';
      }
      return array(
        'PARCELS_LOCKERS' => $parcelsLockers,
        'PARCELS_LOCKERS_COD' => $parcelsLockersCod,
        'X_BORDER' => $xBorder,
        'X_BORDER_COURIER' => $xBorderCourier
      );
    }
    public static function getIdModules()
    {
        $sql = "SELECT id_module
                FROM "._DB_PREFIX_."inpost_delivery_modules
                WHERE module_name = 'PARCELS_LOCKERS'
                ORDER BY id DESC";
        $sql2 = "SELECT id_module
                FROM "._DB_PREFIX_."inpost_delivery_modules
                WHERE module_name = 'PARCELS_LOCKERS_COD'
                ORDER BY id DESC";
        $sqlCrossBorderCourier = "SELECT id_module
                FROM "._DB_PREFIX_."inpost_delivery_modules
                WHERE module_name = 'CROSSBORDER_COURIER'
                ORDER BY id DESC";
        $sqlCrossBorderParcel = "SELECT id_module
                                  FROM "._DB_PREFIX_."inpost_delivery_modules
                                  WHERE module_name = 'CROSSBORDER_PARCEL'
                                  ORDER BY id DESC";
        $a = DB::getInstance()->getValue($sql);
        $b = DB::getInstance()->getValue($sql2);
        $crossBorderCourier = DB::getInstance()->getValue($sqlCrossBorderCourier);
        $crossBorderParcel = DB::getInstance()->getValue($sqlCrossBorderParcel);
        return array(
            'PARCELS_LOCKERS' => $a ? $a : '0',
            'PARCELS_LOCKERS_COD' => $b ? $b : '0',
            'CROSSBORDER_COURIER' => $crossBorderCourier ? $crossBorderCourier : '0',
            'CROSSBORDER_PARCEL' => $crossBorderParcel ? $crossBorderParcel : '0'
        );

    }


    /**
     * @param $cartTotalCost
     * @param $cartTotalWeight
     * @return float
     * @todo-damian podzielic na mniejsze metody
     */

    public static function calculateParcelsLockersPrice($cartTotalCost, $cartTotalWeight, $currency_id, $country)
    {
        $modules = self::getIdModules();
        $carrier_tax = Tax::getCarrierTaxRate($modules['PARCELS_LOCKERS'], $country);
		$currencyDefault = Configuration::get('PS_CURRENCY_DEFAULT');

        /**
         * free shipping
         */
        $freeShippingFrom = Configuration::get('INPOST_PLFS');

        if ($freeShippingFrom >= 0 && $freeShippingFrom) {
			if ((int)$currencyDefault !== (int)$currency_id) {
				$freeShippingFrom = Tools::convertPriceFull((float)str_replace(',', '.', $freeShippingFrom), null, new Currency($currency_id));
			}

            if ($cartTotalCost > $freeShippingFrom) {
				//var_dump('calculateParcelsLockersPrice 1');
                return 0.00;
            }
        }
        /**
         * Price Flat
         */
        $priceRulesFlat = InpostModel::parcelsLockersGetFlatPrice();
        if ((int)$priceRulesFlat['status'] === 1) {
            $price = (float)str_replace(',', '.', $priceRulesFlat['cost']);
        }


        /**
         * Price Rules
         */
        $priceRules = InpostModel::getParcelLockersAppropriatePrice($cartTotalCost);
        if ($priceRules['cost'] >= 0 && (int)$priceRules['status'] === 1) {
            $price =  (float)str_replace(',', '.', $priceRules['cost']);
        }


        /**
         * Weight Rules
         */
        $priceRulesWeight = InpostModel::getParcelLockersAppropriatePriceWeight($cartTotalWeight);
        if ($priceRulesWeight['cost'] >= 0 && (int)$priceRulesWeight['status'] === 1) {
            $price =  (float)str_replace(',', '.', $priceRulesWeight['cost']);
        }

        if (Tools::getIsset($price) && Tools::getIsset($carrier_tax) && !Tax::excludeTaxeOption()) {
            $price = $price / (1+ ($carrier_tax / 100));
        }
		
		//var_dump($currencyDefault, $currency_id, Tools::getIsset($price), $price);
		// && Tools::getIsset($price)
        if ((int)$currencyDefault === (int)$currency_id) {
            return $price;
        }
        if (Tools::getIsset($price)) {
            return Tools::convertPriceFull((float)str_replace(',', '.', $price), null, new Currency($currency_id));
        }
		
        return false;
    }

    /**
     * @param $cartTotalCost
     * @param $cartTotalWeight
     * @return float
     * @todo-damian podzielic na mniejsze metody
     */
    public static function calculateParcelsLockersCodPrice($cartTotalCost, $cartTotalWeight, $currency_id, $country)
    {
        $modules = self::getIdModules();
        $carrier_tax = Tax::getCarrierTaxRate($modules['PARCELS_LOCKERS_COD'], $country);
		$currencyDefault = Configuration::get('PS_CURRENCY_DEFAULT');

        /**
         * free shipping
         */
        $freeShippingFrom = (int)Configuration::get('INPOST_PLCOSFS');
		if ($freeShippingFrom >= 0 && $freeShippingFrom) {
			if ((int)$currencyDefault !== (int)$currency_id) {
				$freeShippingFrom = Tools::convertPriceFull((float)str_replace(',', '.', $freeShippingFrom), null, new Currency($currency_id));
			}

			if ($cartTotalCost > $freeShippingFrom) {
				return 0.00;
			}
		}

        /**
         * Price Flat
         */
        $priceRulesFlat = InpostModel::parcelsLockersCodGetFlatPrice();
        if ((int)$priceRulesFlat['status'] === 1) {
            $price = (float)str_replace(',', '.', $priceRulesFlat['cost']);
        }

        /**
         * Price Rules
         */
        $priceRules = InpostModel::getParcelLockersCodAppropriatePrice($cartTotalCost);
        if ($priceRules['cost'] >= 0 && (int)$priceRules['status'] === 1) {
            $price = (float)str_replace(',', '.', $priceRules['cost']);
        }


        /**
         * Weight Rules and percentage cart value
         */
        $priceRulesWeight = InpostModel::getParcelLockersCodAppropriatePriceWeight($cartTotalWeight);

        if ($priceRulesWeight['cost'] >= 0 && (int)$priceRulesWeight['status'] === 1) {
            $price = (float)str_replace(',', '.', $priceRulesWeight['cost']);
        }
        if (Tools::getIsset($price) && Configuration::get('INPOST_PERCENT_CART_VALUE_COD'))
            $price += Configuration::get('INPOST_PERCENT_CART_VALUE_COD')/100 * $cartTotalCost;
        if (Tools::getIsset($price) && Tools::getIsset($carrier_tax) && !Tax::excludeTaxeOption()) {
            $price = $price / (1+ $carrier_tax / 100);
        }
        $currencyDefault = Configuration::get('PS_CURRENCY_DEFAULT');

        if ((int)$currencyDefault === (int)$currency_id && Tools::getIsset($price)) {
            return $price;
        }

        if (Tools::getIsset($price)) {
            return Tools::convertPriceFull((float)str_replace(',', '.', $price), null, new Currency($currency_id));
        }
        return false;
    }

    public static function getSuitableParcelSize($weight)
    {
        $array = [
            1,
            2,
            5,
            10,
            15,
            20,
            25
        ];
        sort($array);
        foreach ($array as $a) {
            if ($a >= $weight) {
                return $a;
            }
        }
        return end($array); // or return NULL;

    }

    public static function calculateCrossBorderCourierPrice($cartTotalWeight, $countryIsoCode, $currency_id, $country)
    {
        $modules = self::getIdModules();
        $carrier_tax = Tax::getCarrierTaxRate($modules['CROSSBORDER_COURIER'], $country);
        
        $apiCode = constant('InpostConnector::INPOST_COUNTRY_' . Configuration::get('INPOST_COUNTRY'));
        if ($apiCode !== 'PL') {
            return false;
        }
        $weightParcel = self::getSuitableParcelSize($cartTotalWeight);
        $price = Db::getInstance()->getValue("SELECT btd.parcel_price
                                                FROM " . _DB_PREFIX_ . "x_border_types bt
                                                LEFT JOIN " . _DB_PREFIX_ . "x_border_types_details btd
                                                ON bt.id=btd.id_border_type
                                                WHERE from_country = '" . $apiCode . "'
                                                AND to_country= '" . $countryIsoCode . "'
                                                AND recipient_method = 'ToDoor'
                                                AND parcel_weight='" . $weightParcel . "'");

        if (Tools::getIsset($price) && Tools::getIsset($carrier_tax) && !Tax::excludeTaxeOption()) {
            $price = $price / (1+ ($carrier_tax / 100));
        }

        if($price > 0) {
			$currencyDefault = Configuration::get('PS_CURRENCY_DEFAULT');

			if ((int)$currencyDefault === (int)$currency_id && Tools::getIsset($price)) {
				return $price;
			}

			if (Tools::getIsset($price)) {
				return Tools::convertPriceFull((float)str_replace(',', '.', $price), null, new Currency($currency_id));
			}
		}

        return false;
    }
    public static function calculateCrossBorderParcelPrice($cartTotalWeight, $countryIsoCode, $currency_id, $country)
    {
        $modules = self::getIdModules();
        $carrier_tax = Tax::getCarrierTaxRate($modules['CROSSBORDER_PARCEL'], $country);
        $apiCode = constant('InpostConnector::INPOST_COUNTRY_'.Configuration::get('INPOST_COUNTRY'));

        //SHIPTMEN IN CROSSBORDER TO PARCELS ONLY FROM POLAND
        if ($apiCode !== 'PL') {
            return false;
        }
        //SHIPMENT ONLY TO Slovakia and Czech Republic
        if ($countryIsoCode !== 'SK' && $countryIsoCode !== 'CZ') {
            return false;
        }

        $weightParcel = self::getSuitableParcelSize($cartTotalWeight);
        if ($weightParcel > 20) {
            return false;
        }
        $price = Db::getInstance()->getValue("SELECT btd.parcel_price
                                                FROM " . _DB_PREFIX_ . "x_border_types bt
                                                LEFT JOIN " . _DB_PREFIX_ . "x_border_types_details btd
                                                ON bt.id=btd.id_border_type
                                                WHERE from_country = '" . $apiCode . "'
                                                AND to_country= '" . $countryIsoCode . "'
                                                AND recipient_method = 'ToParcelMachine'
                                                AND parcel_weight='" . $weightParcel . "'");

        if (Tools::getIsset($price) && Tools::getIsset($carrier_tax) && !Tax::excludeTaxeOption()) {
            $price = $price / (1+ ($carrier_tax / 100));
        }

        if($price > 0) {
			$currencyDefault = Configuration::get('PS_CURRENCY_DEFAULT');

			if ((int)$currencyDefault === (int)$currency_id && Tools::getIsset($price)) {
				return $price;
			}

			if (Tools::getIsset($price)) {
				return Tools::convertPriceFull((float)str_replace(',', '.', $price), null, new Currency($currency_id));
			}
		}

        return false;

    }
    public static function createParcelLockersCarrier()
    {
        $country = Configuration::get('INPOST_COUNTRY');
        $moduleIds = self::getIdModules();
        $delay = array();
        if (!empty($moduleIds['PARCELS_LOCKERS'])) {
            return false;
        }
        $zones = ZoneCore::getZones();
        $groups = GroupCore::getGroups(Context::getContext()->language->id);
        $groups_a = [];
        foreach ($groups as $group) {
            $groups_a[] = $group['id_group'];
        }

        $carrier = new Carrier();
        if ($country == 1) {
            $name = 'Paczkomaty InPost';
        } elseif ($country == 2) {
            $name = "Abricolis InPost 24/7 (Consignes)";
        } elseif ($country == 3) {
            $name = "InPost Locker 24/7";
        } else {
          $name = "InPost Parcel Locker";
        };
        $carrier->name = $name;
        $carrier->active = 1;
        $carrier->is_free = 0;
        $carrier->shipping_handling = 1;
        $carrier->shipping_external = 1;
        $carrier->shipping_method = 2;
        $carrier->max_width = 60;
        $carrier->max_height = 80;
        $carrier->max_depth = 90;
        $carrier->max_weight = 10;
        $carrier->grade = 0;
        $carrier->is_module = 1;
        $carrier->need_range = 1;
        $carrier->range_behavior = false;
        $carrier->external_module_name = "inpost";

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

        if ((int)$country === 1) {
            $carrier->url = "https://twoj.inpost.pl/pl/znajdz-przesylke?parcel=@";
        }
        if ((int)$country === 2) {
            $carrier->url = "https://inpost24.fr/fr/track-parcel?parcel=@";
        }
        if ((int)$country === 3) {
            $carrier->url = "https://inpost24.it/it/track-parcel?parcel=@";
        }

        foreach (Language::getLanguages(false) as $language) {
            $delay[$language['id_lang']] = " ";
        }

        $carrier->delay = $delay;
        $carrier->save();
        if (!copy(INPOST_IMG_DIR.'/inpost-logo_65.png', _PS_SHIP_IMG_DIR_.'/'.(int)$carrier->id.'.jpg')) {
            return false;
        }
        $inpostGlobalCarrier = new InpostDeliveryModulesCore();

        $inpostGlobalCarrier->id_module = $carrier->id;
        $inpostGlobalCarrier->reference = $carrier->id;
        $inpostGlobalCarrier->module_name = 'PARCELS_LOCKERS';
        $inpostGlobalCarrier->save();
        foreach ($zones as $zone) {
            $carrier->addZone($zone['id_zone']);
        }
        if (version_compare(_PS_VERSION_, '1.6', '>=')) {
            $carrier->setGroups($groups_a);
        } else {
            self::setGroups($groups_a, $carrier->id);
        }
        $rangePrice = new RangePriceCore();
        $rangePrice->id_carrier = $carrier->id;
        $rangePrice->delimiter1 = 0.00;
        $rangePrice->delimiter2 = 999999.00;
        $rangePrice->add(true, true);
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            $fRange = $carrier->getRangeObject();
            $fRange->id_carrier = (int)$carrier->id;
            $fRange->delimiter1 = 0;
            $fRange->delimiter2 = 1;
            $fRange->save();
        }
    }

    public static function createParcelLockersCodCarrier()
    {
        $country = Configuration::get('INPOST_COUNTRY');
        $moduleIds = self::getIdModules();
        $delay = array();
        if (!empty($moduleIds['PARCELS_LOCKERS_COD'])) {
            return false;
        }

        $zones = ZoneCore::getZones();
        $groups = GroupCore::getGroups(Context::getContext()->language->id);
        $groups_a = [];
        foreach ($groups as $group) {
            $groups_a[] = $group['id_group'];
        }
        /**
         * COD
         */
        $carrier = null;
        $carrier = new Carrier();
        if ($country == 1) {
            $name = 'Paczkomaty InPost (za pobraniem)';
        } elseif ($country == 3) {
            $name = "Locker InPost (pagamento in contrassegno)";
        } else {
            $name = "InPost Parcel Locker COD";
        }
        $carrier->name = $name;
        $carrier->active = 1;
        $carrier->is_free = 0;
        $carrier->shipping_handling = 1;
        $carrier->shipping_external = 1;
        $carrier->shipping_method = 2;
        $carrier->max_width = 60;
        $carrier->max_height = 80;
        $carrier->max_depth = 90;
        $carrier->max_weight = 10;
        $carrier->grade = 0;
        $carrier->is_module = 1;
        $carrier->need_range = 1;
        $carrier->range_behavior = false;
        $carrier->external_module_name = "inpost";

        if ((int)$country === 1) {
            $carrier->url = "https://twoj.inpost.pl/pl/znajdz-przesylke?parcel=@";
        }
        if ((int)$country === 2) {
            $carrier->url = "https://inpost24.fr/fr/track-parcel?parcel=@";
        }
        if ((int)$country === 3) {
            $carrier->url = "https://inpost24.it/it/track-parcel?parcel=@";
        }
        foreach (Language::getLanguages(false) as $language) {
            $delay[$language['id_lang']] = " ";
        }
        $carrier->delay = $delay;
        $carrier->save();
        if (!copy(INPOST_IMG_DIR.'/inpost-logo_65.png', _PS_SHIP_IMG_DIR_.'/'.(int)$carrier->id.'.jpg')) {
            return false;
        }
        $inpostGlobalCarrier = new InpostDeliveryModulesCore();
        $inpostGlobalCarrier->id_module = $carrier->id;
        $inpostGlobalCarrier->reference = $carrier->id;
        $inpostGlobalCarrier->module_name = 'PARCELS_LOCKERS_COD';

        $inpostGlobalCarrier->save();
        foreach ($zones as $zone) {
            $carrier->addZone($zone['id_zone']);
        }
        if (version_compare(_PS_VERSION_, '1.6', '>=')) {
            $carrier->setGroups($groups_a);
        } else {
            self::setGroups($groups_a, $carrier->id);
        }

        $rangePrice = new RangePriceCore();
        $rangePrice->id_carrier = $carrier->id;
        $rangePrice->delimiter1 = 0.00;
        $rangePrice->delimiter2 = 999999.00;
        $rangePrice->add(true, true);
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            $fRange = $carrier->getRangeObject();
            $fRange->id_carrier = (int)$carrier->id;
            $fRange->delimiter1 = 0;
            $fRange->delimiter2 = 1;
            $fRange->save();
        }
    }

    public static function deleteCarriers()
    {
        return Db::getInstance()->update('carrier', array(
            'deleted' => 1
        ), 'external_module_name = "inpost"');
    }

    public static function createCrossBorderParcelCarriers()
    {
        $moduleIds = self::getIdModules();
        $delay = array();
        if (!empty($moduleIds['CROSSBORDER_PARCEL'])) {
            return false;
        }

        $zones = ZoneCore::getZones();
        $groups = GroupCore::getGroups(Context::getContext()->language->id);
        $groups_a = [];
        foreach ($groups as $group) {
            $groups_a[] = $group['id_group'];
        }
        /**
         * COD
         */
        $carrier = null;
        $carrier = new Carrier();
        //$inpost = Module::getInstanceByName('inpost');
        $carrier->name = "Paczkomaty InPost Cross Border";
        $carrier->active = 1;
        $carrier->is_free = 0;
        $carrier->shipping_handling = 1;
        $carrier->shipping_external = 1;
        $carrier->shipping_method = 2;
        $carrier->max_width = 60;
        $carrier->max_height = 80;
        $carrier->max_depth = 90;
        $carrier->max_weight = 10;
        $carrier->grade = 0;
        $carrier->is_module = 1;
        $carrier->need_range = 1;
        $carrier->range_behavior = false;
        $carrier->external_module_name = "inpost";
        $country = Configuration::get('INPOST_COUNTRY');
        if ((int)$country === 1) {
            $carrier->url = "https://twoj.inpost.pl/pl/przesylki/cross-border?parcel=@";
        }
        if ((int)$country === 2) {
            $carrier->url = "https://inpost24.fr/fr/suivi-du-colis?parcel=@";
        }
        if ((int)$country === 3) {
            $carrier->url = "https://inpost24.it/it/rintraccia-il-pacco?parcel=@";
        }
        foreach (Language::getLanguages(false) as $language) {
            $delay[$language['id_lang']] = " ";
        }
        $carrier->delay = $delay;
        $carrier->save();
        if (!copy(INPOST_IMG_DIR.'/inpost-logo_65.png', _PS_SHIP_IMG_DIR_.'/'.(int)$carrier->id.'.jpg')) {
            return false;
        }
        $inpostGlobalCarrier = new InpostDeliveryModulesCore();
        $inpostGlobalCarrier->id_module = $carrier->id;
        $inpostGlobalCarrier->reference = $carrier->id;
        $inpostGlobalCarrier->module_name = 'CROSSBORDER_PARCEL';

        $inpostGlobalCarrier->save();
        foreach ($zones as $zone) {
            $carrier->addZone($zone['id_zone']);
        }
        if (version_compare(_PS_VERSION_, '1.6', '>=')) {
            $carrier->setGroups($groups_a);
        } else {
            self::setGroups($groups_a, $carrier->id);
        }
        $rangePrice = new RangePriceCore();
        $rangePrice->id_carrier = $carrier->id;
        $rangePrice->delimiter1 = 0.00;
        $rangePrice->delimiter2 = 999999.00;
        $rangePrice->add(true, true);
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            $fRange = $carrier->getRangeObject();
            $fRange->id_carrier = (int)$carrier->id;
            $fRange->delimiter1 = 0;
            $fRange->delimiter2 = 1;
            $fRange->save();
        }
    }

    public static function createCrossBorderCourierCarriers()
    {
        $moduleIds = self::getIdModules();
        $delay = array();
        if (!empty($moduleIds['CROSSBORDER_COURIER'])) {
            return false;
        }

        $zones = ZoneCore::getZones();
        $groups = GroupCore::getGroups(Context::getContext()->language->id);
        $groups_a = [];
        foreach ($groups as $group) {
            $groups_a[] = $group['id_group'];
        }
        /**
         * COD
         */
        $carrier = null;
        $carrier = new Carrier();
        $carrier->name = "Kurier InPost Cross Border";
        $carrier->active = 1;
        $carrier->is_free = 0;
        $carrier->shipping_handling = 1;
        $carrier->shipping_external = 1;
        $carrier->shipping_method = 2;
        $carrier->max_width = 60;
        $carrier->max_height = 80;
        $carrier->max_depth = 90;
        $carrier->max_weight = 10;
        $carrier->grade = 0;
        $carrier->is_module = 1;
        $carrier->need_range = 1;
        $carrier->range_behavior = false;
        $carrier->external_module_name = "inpost";
        $country = Configuration::get('INPOST_COUNTRY');
        if ((int)$country === 1) {
            $carrier->url = "https://twoj.inpost.pl/pl/przesylki/cross-border?parcel=@";
        }
        if ((int)$country === 2) {
            $carrier->url = "https://inpost24.fr/fr/track-parcel?parcel=@";
        }
        if ((int)$country === 3) {
            $carrier->url = "https://inpost24.it/it/track-parcel?parcel=@";
        }
        foreach (Language::getLanguages(false) as $language) {
            $delay[$language['id_lang']] = " ";
        }
        $carrier->delay = $delay;
        $carrier->save();
        if (!copy(INPOST_IMG_DIR.'/inpost-logo_65.png', _PS_SHIP_IMG_DIR_.'/'.(int)$carrier->id.'.jpg')) {
            return false;
        }
        $inpostGlobalCarrier = new InpostDeliveryModulesCore();
        $inpostGlobalCarrier->id_module = $carrier->id;
        $inpostGlobalCarrier->reference = $carrier->id;
        $inpostGlobalCarrier->module_name = 'CROSSBORDER_COURIER';

        $inpostGlobalCarrier->save();
        foreach ($zones as $zone) {
            $carrier->addZone($zone['id_zone']);
        }
        if (version_compare(_PS_VERSION_, '1.6', '>=')) {
            $carrier->setGroups($groups_a);
        } else {
            self::setGroups($groups_a, $carrier->id);
        }
        $rangePrice = new RangePriceCore();
        $rangePrice->id_carrier = $carrier->id;
        $rangePrice->delimiter1 = 0.00;
        $rangePrice->delimiter2 = 999999.00;
        $rangePrice->add(true, true);
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            $fRange = $carrier->getRangeObject();
            $fRange->id_carrier = (int)$carrier->id;
            $fRange->delimiter1 = 0;
            $fRange->delimiter2 = 1;
            $fRange->save();
        }

    }
    public static function updateTaxGroupForInpostCarriers($tax_group)
    {
        $shops = Shop::getShops(true, null, true);
        $modules = self::getIdModules();

        $values = array();
        if ($modules['PARCELS_LOCKERS']) {
            Db::getInstance()->delete('carrier_tax_rules_group_shop', 'id_carrier ='.$modules['PARCELS_LOCKERS']);
            foreach ($shops as $id_shop) {
                $values[] = array(
                    'id_carrier' => (int)$modules['PARCELS_LOCKERS'],
                    'id_tax_rules_group' => (int)$tax_group,
                    'id_shop' => (int)$id_shop,
                );
            }
        }
        if ($modules['PARCELS_LOCKERS_COD']) {
            Db::getInstance()->delete('carrier_tax_rules_group_shop', 'id_carrier ='.$modules['PARCELS_LOCKERS_COD']);
            foreach ($shops as $id_shop) {
                $values[] = array(
                    'id_carrier' => (int)$modules['PARCELS_LOCKERS_COD'],
                    'id_tax_rules_group' => (int)$tax_group,
                    'id_shop' => (int)$id_shop,
                );
            }
        }
        if ($modules['CROSSBORDER_COURIER']) {
          Db::getInstance()->delete('carrier_tax_rules_group_shop', 'id_carrier ='.$modules['CROSSBORDER_COURIER']);
          foreach ($shops as $id_shop) {
              $values[] = array(
                  'id_carrier' => (int)$modules['CROSSBORDER_COURIER'],
                  'id_tax_rules_group' => (int)$tax_group,
                  'id_shop' => (int)$id_shop,
              );
          }
        }
        if ($modules['CROSSBORDER_PARCEL']) {
          Db::getInstance()->delete('carrier_tax_rules_group_shop', 'id_carrier ='.$modules['CROSSBORDER_PARCEL']);
          foreach ($shops as $id_shop) {
              $values[] = array(
                  'id_carrier' => (int)$modules['CROSSBORDER_PARCEL'],
                  'id_tax_rules_group' => (int)$tax_group,
                  'id_shop' => (int)$id_shop,
              );
          }
        }

        Cache::clean(
            'carrier_id_tax_rules_group_'.(int)$modules['PARCELS_LOCKERS_COD'].'_'.(int)Context::getContext()->shop->id
        );
        Cache::clean(
            'carrier_id_tax_rules_group_'.(int)$modules['PARCELS_LOCKERS'].'_'.(int)Context::getContext()->shop->id
        );
        return Db::getInstance()->insert('carrier_tax_rules_group_shop', $values);

    }
    public static function setGroups($groups, $carrier_id)
    {
        if (!is_array($groups) || !count($groups)) {
            return true;
        }
        $sql = 'INSERT INTO '._DB_PREFIX_.'carrier_group (id_carrier, id_group) VALUES ';
        foreach ($groups as $id_group) {
            $sql .= '('.(int)$carrier_id.', '.(int)$id_group.'),';
        }

        return Db::getInstance()->execute(rtrim($sql, ','));
    }
}
