<?php

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

if (!include(_PS_MODULE_DIR_ . 'mbeshipping' . '/lib/pclzip.lib.php')) {
    die("Failed to include '/lib/pclzip.lib.php' (Check permissions)");
}

require_once(_PS_MODULE_DIR_ . 'mbeshipping' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'custom' . DIRECTORY_SEPARATOR . 'Ws.php');


class MbeShipping extends CarrierModule
{

    CONST PREFIX = _DB_PREFIX_;

    protected $_module_name = 'mbeshipping'; // not change

    protected $_upload_dir = _PS_MODULE_DIR_ . 'mbeshipping' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR;

    protected $_module_url = __PS_BASE_URI__ . 'modules/mbeshipping/';

    public $_carriers = array();
    public $id_carrier = null;

    private $pricesMbeLoaded = false;

    public function __construct()
    {
        $this->name = $this->_module_name;
        $this->tab = 'shipping_logistics';
        $this->version = '1.6.2';
        $this->author = 'MBE Worldwide S.p.A.';

        $this->bootstrap = true;

        $this->ps_versions_compliancy['min'] = '1.4';
        //$this->ps_versions_compliancy['max'] = '1.6';

        parent::__construct();

        if (!file_exists($this->_upload_dir)) {
            mkdir($this->_upload_dir, 0777, true);  //create directory if not exist
        }

        /* Backward compatibility */
        if (version_compare(_PS_VERSION_, '1.5', '<')) {
            require(_PS_MODULE_DIR_ . $this->name . '/backward_compatibility/backward.php');
        }

        $this->displayName = 'Mail Boxes ETC';
        $this->description = $this->l('Mail Boxes Etc. Online MBE Plugin integration for main Ecommerce platforms');
    }

    ###########################################################################
    ## Installation
    ###########################################################################

    public function install()
    {
        if (!parent::install() || !$this->installTab() || !$this->installTracking() || !$this->installOverride() || !$this->installHook() || !$this->installRatesTable() || !$this->installCsvPackageTable() || !$this->installCsvPackageProductTable()) {
            return false;
        }

        if (file_exists(_PS_ROOT_DIR_ . '/cache/class_index.php')) {
            unlink(_PS_ROOT_DIR_ . '/cache/class_index.php');
        }

        return true;
    }

    public function installTracking()
    {
        if (version_compare(_PS_VERSION_, '1.5', '<')) {
            Db::getInstance()->ExecuteS('ALTER TABLE ' . _DB_PREFIX_ . 'orders MODIFY shipping_number VARCHAR(4000)');
        }
        else {
            Db::getInstance()->execute('ALTER TABLE ' . _DB_PREFIX_ . 'order_carrier MODIFY tracking_number VARCHAR(4000)');
        }
        return true;
    }

    public function installRatesTable()
    {
        $helper = new Mbe_Shipping_Helper_Rates();
        return $helper->installRatesTable();
    }

    public function installCsvPackageTable()
    {
        $helper = new Mbe_Shipping_Helper_Package();
        return $helper->installCsvPackageTable();
    }

    public function installCsvPackageProductTable()
    {
        $helper = new Mbe_Shipping_Helper_PackageProduct();
        return $helper->installCsvPackageProductTable();
    }

    public function installTab()
    {
        $tab = new Tab();
        $tab->active = 1;
        $tab->class_name = 'AdminMbeShipping';
        $tab->name = array();
        foreach (Language::getLanguages(true) as $lang) {
            $tab->name[$lang['id_lang']] = $this->l('MBE shipments list');
        }

        if (_PS_VERSION_ >= 1.5) {
            $tab->id_parent = (int)Tab::getIdFromClassName('AdminParentShipping');
        }
        else {
            $tab->id_parent = (int)Tab::getIdFromClassName('AdminShipping');
        }

        $tab->module = $this->name;

        return $tab->add();
    }

    public function installHook()
    {
        if (version_compare(_PS_VERSION_, '1.5', '<')) {
            if (!$this->registerHook('postUpdateOrderStatus')) {
                return false;
            }
        }
        else {
            if (!$this->registerHook('actionOrderStatusPostUpdate')) {
                return false;
            }
        }

        /*ACCESS POINT*/
        if (version_compare(_PS_VERSION_, '1.7', '<')) {
            if (!$this->registerHook('extraCarrier')) {
                return false;
            }
        }
        else {

            if (!$this->registerHook('displayCarrierExtraContent')) {
                return false;
            }
        }

        if (!$this->registerHook('actionValidateOrder')) {
            return false;
        }
        /**/

        return true;
    }

    public function installOverride()
    {
        $result = true;
        if (version_compare(_PS_VERSION_, '1.5', '<')) {
            $carrierCopy = copy(__DIR__ . '/override/classes/Carrier.php', _PS_ROOT_DIR_ . '/override/classes/Carrier.php');
            $result = $result && $carrierCopy;
        }
        return $result;
    }


    ################################################################################
    ## Uninstallation
    #################################################################################


    public function uninstall()
    {
        if (!parent::uninstall() || !$this->uninstallTracking() || !$this->uninstallTab() || !$this->deleteCarriers() || !$this->uninstallRatesTable() || !$this->uninstallCsvPackageTable() || !$this->uninstallCsvPackageProductTable()) {
            return false;
        }
        $this->uninstallOverride();

        /*ACCESS POINT*/
        if (version_compare(_PS_VERSION_, '1.7', '<')) {
            if (!$this->unregisterHook('extraCarrier')) {
                return false;
            }
        }
        else {

            if (!$this->unregisterHook('displayCarrierExtraContent')) {
                return false;
            }
        }
        /**/

        return true;
    }

    public function uninstallTracking()
    {
        if (version_compare(_PS_VERSION_, '1.5', '<')) {
            Db::getInstance()->ExecuteS('ALTER TABLE ' . _DB_PREFIX_ . 'orders MODIFY shipping_number VARCHAR(32)');
        }
        else {
            Db::getInstance()->execute('ALTER TABLE ' . _DB_PREFIX_ . 'order_carrier MODIFY tracking_number VARCHAR(64)');
        }
        return true;
    }

    public function uninstallOverride()
    {
        $result = true;
        if (file_exists(_PS_ROOT_DIR_ . '/cache/class_index.php')) {
            unlink(_PS_ROOT_DIR_ . '/cache/class_index.php');
        }
        /*$o = new Order();
        if ($o->mbe_module && file_exists(_PS_ROOT_DIR_ . '/override/classes/order/Order.php')) {
            $result = $result && unlink(_PS_ROOT_DIR_ . '/override/classes/order/Order.php');
        }
        if ($o->mbe_module && file_exists(_PS_ROOT_DIR_ . '/override/classes/Order.php')) {
            $result = $result && unlink(_PS_ROOT_DIR_ . '/override/classes/Order.php');
        }
        $c = new Carrier();
        if ($c->mbe_module && file_exists(_PS_ROOT_DIR_ . '/override/classes/Carrier.php')) {
            $result = $result && unlink(_PS_ROOT_DIR_ . '/override/classes/Carrier.php');
        }*/
        return $result;
    }

    public function uninstallTab()
    {
        $id_tab = (int)Tab::getIdFromClassName('AdminMbeShipping');
        if ($id_tab) {
            $tab = new Tab($id_tab);
            return $tab->delete();
        }
        else {
            return false;
        }
    }

    protected function deleteCarriers()
    {
        $result = true;
        $results = Db::getInstance()->executeS('SELECT id_carrier FROM `' . _DB_PREFIX_ . 'carrier` where external_module_name = "' . $this->_module_name . '"');
        $idCarriers = array();
        foreach ($results as $r) {
            $idCarriers[] = $r['id_carrier'];
        }
        if (!empty($idCarriers)) {
            $result &= Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'carrier` where id_carrier IN (' . implode(',', $idCarriers) . ')');
            $result &= Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'carrier_zone` where id_carrier IN (' . implode(',', $idCarriers) . ')');
            $result &= Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'delivery` where id_carrier IN (' . implode(',', $idCarriers) . ')');
            $result &= Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'range_price` where id_carrier IN (' . implode(',', $idCarriers) . ')');
            $result &= Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'range_weight` where id_carrier IN (' . implode(',', $idCarriers) . ')');
        }
        return $result;
    }

    public function uninstallRatesTable()
    {
        $helper = new Mbe_Shipping_Helper_Rates();
        return $helper->uninstallRatesTable();
    }

    public function uninstallCsvPackageTable()
    {
        $helper = new Mbe_Shipping_Helper_Package();
        return $helper->uninstallCsvPackageTable();
    }

    public function uninstallCsvPackageProductTable()
    {
        $helper = new Mbe_Shipping_Helper_PackageProduct();
        return $helper->uninstallCsvPackageProductTable();
    }

    ###########################################################################
    ## Plugin configuration
    ###########################################################################


    public function validateCsvFileAndInsert($filePath, &$output)
    {
        $helper = new Mbe_Shipping_Helper_Csv();

        $rates = $helper->readFile($filePath);

        //VALIDATE

        $errors = false;
        $i = 1;

        $allowedShipmentServices = Configuration::get('allowed_shipment_services');
        $allowedShipmentServicesArray = explode('-', $allowedShipmentServices);
        $maxShipmentWeight = Configuration::get('max_shipment_weight');


        foreach ($rates as $rate) {
            if (strlen($rate["country"]) > 2) {
                $output .= $this->displayError(sprintf($this->l('File upload error: row %d: "%s", COUNTRY column. Use destination Country in 2 character ISO format (e.g. IT for Italy, ES for Spain, DE for Germany)"'), $i, $rate["country"]));
                $errors = true;
            }

            if (!in_array($rate["delivery_type"], $allowedShipmentServicesArray)) {
                $output .= $this->displayError(sprintf($this->l('File upload error: row %d: "%s", SHIPMENT TYPE column. Input code is not a valid MBE Service'), $i, $rate["delivery_type"]));
                $errors = true;
            }

            if ($maxShipmentWeight) {
                if ($rate["weight_from"] > $maxShipmentWeight) {
                    $output .= $this->displayError(sprintf($this->l('File upload error: row %d: "%s", WEIGHT column. Input weight exceeds allowed'), $i, $rate["weight_from"]));
                    $errors = true;
                }
                if ($rate["weight_to"] > $maxShipmentWeight) {
                    $output .= $this->displayError(sprintf($this->l('File upload error: row %d: "%s", WEIGHT column. Input weight exceeds allowed'), $i, $rate["weight_to"]));
                    $errors = true;
                }
            }
            $i++;
        }

        if ($errors) {
            return false;
        }

        //INSERT
        $ratesHelper = new Mbe_Shipping_Helper_Rates();
        $truncateResult = $ratesHelper->truncate();

        if (!$truncateResult) {
            $this->displayError($this->l('Error executing truncate query '));
        }

        foreach ($rates as $rate) {
            $insertResult = $ratesHelper->insertRate($rate["country"], $rate["region"], $rate["city"], $rate["zip"], $rate["zip_to"], $rate["weight_from"], $rate["weight_to"], $rate["price"], $rate["delivery_type"]);

            if (!$insertResult) {
                $this->displayError($this->l('Error executing query '));
            }
        }

    }

    public function validateCsvPackageFileAndInsert($filePath, &$output)
    {
        $helper = new Mbe_Shipping_Helper_Csv();

        $packages = $helper->readFile($filePath);

        $PackageHelper = new Mbe_Shipping_Helper_Package();
        $truncateResult = $PackageHelper->truncate();

        if (!$truncateResult) {
            $this->displayError($this->l('Error executing truncate query '));
        }

        foreach ($packages as $package) {
            $insertResult = $PackageHelper->insertCsvPackage($package["max_weight"], $package["length"], $package["width"], $package["height"], $package["package_label"], $package["package_code"]);

            if (!$insertResult) {
                $this->displayError($this->l('Error executing query '));
            }
        }
    }

    public function validateCsvPackageProductFileAndInsert($filePath, &$output)
    {
        $helper = new Mbe_Shipping_Helper_Csv();

        $packageProducts = $helper->readFile($filePath);

        $PackageProductHelper = new Mbe_Shipping_Helper_PackageProduct();
        $truncateResult = $PackageProductHelper->truncate();

        if (!$truncateResult) {
            $this->displayError($this->l('Error executing truncate query '));
        }

        foreach ($packageProducts as $packageProduct) {
            $insertResult = $PackageProductHelper->insertCsvPackageProduct($packageProduct["custom_package"], $packageProduct["single_parcel"], $packageProduct["product_sku"],  $packageProduct["package_code"]);

            if (!$insertResult) {
                $this->displayError($this->l('Error executing query '));
            }
        }
    }

    public function getContent()
    {
        $output = null;

        if(isset($_GET['downloadlogs']) && $_GET['downloadlogs'] === "1")
        {
            $logs_path = $this->local_path.'log/';
            $path = $logs_path . 'compressed.zip';
            if (file_exists($path)) {
                unlink($path);
            }
            $values = array();
            $files = glob($logs_path.'/*');
            foreach ($files as $f) {
                $paths = explode('/', $f);
                $values[] = end($paths);
            }
            chdir($logs_path);
            $archive = new PclZip($path);
            $response = $archive->create($values);
            if ($response == 0) {
                die("[ERROR] PclZip : " . $archive->errorInfo(true));
            }

            if (headers_sent()) {
                echo 'HTTP header already sent';
            }
            else {
                if (!is_file($path)) {
                    header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
                    echo 'File not found';
                }
                else {
                    if (!is_readable($path)) {
                        header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
                        echo 'File not readable';
                    }
                    else {
                        header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
                        header("Content-Type: application/zip");
                        header("Content-Transfer-Encoding: Binary");
                        header("Content-Length: " . filesize($path));
                        header("Content-Disposition: attachment; filename=\"" . basename($path) . "\"");
                        ob_clean();
                        flush();
                        readfile($path);
                        exit;
                    }
                }
            }
            die;
        }

        if(isset($_GET['deletelogs']) && $_GET['deletelogs'] === "1")
        {
            $logs_path = $this->local_path.'log/';
            $files = glob($logs_path.'/*');
            foreach($files as $file){
                if(is_file($file))
                    unlink($file);
            }
        }


        if (Tools::isSubmit('submit' . $this->name)) {
            if (version_compare(_PS_VERSION_, '1.6', '<')) {
                $values = $_POST;
            }
            else {
                $values = Tools::getAllValues();
            }

            $ws = new Mbe_Shipping_Model_Ws();
            $customer = $ws->getCustomer(true);
            Configuration::updateValue('MBECustomer', json_encode($customer));

            if ($_FILES['shipments_csv'] && $_FILES['shipments_csv']['name'] && $_FILES['shipments_csv']['tmp_name']) {
                $path = $_FILES['shipments_csv']['name'];
                $ext = pathinfo($path, PATHINFO_EXTENSION);
                if ($ext == "csv") {
                    $nowDate = new DateTime();
                    $fileName = date_format($nowDate, 'Y-m-d_H-i-s') . '_' . 'mbe_csv.csv';
                    $filePath = $this->_upload_dir . $fileName;

                    if (!file_exists($this->_upload_dir)) {
                        if (!mkdir($this->_upload_dir, 0777, true)) {
                            $output .= $this->displayError($this->l('The "upload" folder is not created'));
                        }
                    }

                    move_uploaded_file($_FILES['shipments_csv']['tmp_name'], $filePath);

                    // VALIDATE AND INSERT FILE
                    $this->validateCsvFileAndInsert($filePath, $output);

                    //save configuration containing the file uploaded and saved into database
                    Configuration::updateValue("shipments_csv", $fileName);

                }
                else {
                    $output .= $this->displayError($this->l('File upload error: only CSV format is allowed'));
                }
            }

            if (array_key_exists('mbe_shipping_packages_csv', $_FILES) && $_FILES['mbe_shipping_packages_csv'] && $_FILES['mbe_shipping_packages_csv']['name'] && $_FILES['mbe_shipping_packages_csv']['tmp_name']) {
                $path = $_FILES['mbe_shipping_packages_csv']['name'];
                $ext = pathinfo($path, PATHINFO_EXTENSION);
                if ($ext == "csv") {
                    $nowDate = new DateTime();
                    $fileName = date_format($nowDate, 'Y-m-d_H-i-s') . '_' . 'mbe_shipping_packages_csv.csv';
                    $filePath = $this->_upload_dir . $fileName;

                    if (!file_exists($this->_upload_dir)) {
                        if (!mkdir($this->_upload_dir, 0777, true)) {
                            $output .= $this->displayError($this->l('The "upload" folder is not created'));
                        }
                    }

                    move_uploaded_file($_FILES['mbe_shipping_packages_csv']['tmp_name'], $filePath);

                    // VALIDATE AND INSERT FILE
                    $this->validateCsvPackageFileAndInsert($filePath, $output);

                    //save configuration containing the file uploaded and saved into database
                    Configuration::updateValue("mbe_shipping_packages_csv", $fileName);

                }
                else {
                    $output .= $this->displayError($this->l('File upload error: only CSV format is allowed'));
                }
            }

            if (array_key_exists('mbe_shipping_packages_product_csv', $_FILES) && $_FILES['mbe_shipping_packages_product_csv'] && $_FILES['mbe_shipping_packages_product_csv']['name'] && $_FILES['mbe_shipping_packages_product_csv']['tmp_name']) {
                $path = $_FILES['mbe_shipping_packages_product_csv']['name'];
                $ext = pathinfo($path, PATHINFO_EXTENSION);
                if ($ext == "csv") {
                    $nowDate = new DateTime();
                    $fileName = date_format($nowDate, 'Y-m-d_H-i-s') . '_' . 'mbe_shipping_packages_product_csv.csv';
                    $filePath = $this->_upload_dir . $fileName;

                    if (!file_exists($this->_upload_dir)) {
                        if (!mkdir($this->_upload_dir, 0777, true)) {
                            $output .= $this->displayError($this->l('The "upload" folder is not created'));
                        }
                    }

                    move_uploaded_file($_FILES['mbe_shipping_packages_product_csv']['tmp_name'], $filePath);

                    // VALIDATE AND INSERT FILE
                    $this->validateCsvPackageProductFileAndInsert($filePath, $output);

                    //save configuration containing the file uploaded and saved into database
                    Configuration::updateValue("mbe_shipping_packages_product_csv", $fileName);

                }
                else {
                    $output .= $this->displayError($this->l('File upload error: only CSV format is allowed'));
                }
            }


            foreach ($values as $key => $value) {
                if (!$key || empty($key) || !Validate::isGenericName($key)) {
                    $output .= $this->displayError($this->l('Invalid Configuration value'));
                }
                else {
                    if (!in_array($key, array('shipments_csv')) && !in_array($key, array('mbe_shipping_packages_csv')) && !in_array($key, array('mbe_shipping_packages_product_csv'))) {
                        if (is_array($value)) {
                            Configuration::updateValue($key, implode('-', $value));
                        }
                        else {
                            Configuration::updateValue($key, $value);
                        }
                    }
                }
            }

            if (is_null($output)) {
                $output .= $this->displayConfirmation($this->l('Settings updated'));
            }
        }
        return $output . $this->displayForm();
    }

    public function displayForm()
    {
        global $currentIndex, $cookie;

        if (version_compare(_PS_VERSION_, '1.5', '<')) {
            $curIndex = $currentIndex;
        }
        else {
            $curIndex = AdminController::$currentIndex;
        }

        // Get default language
        $default_lang = (int)Configuration::get('PS_LANG_DEFAULT');


        $ws = new Mbe_Shipping_Model_Ws();
        $availableShipping = $ws->getAllowedShipmentServices();

        // $serviceOptions
        if ($ws->isCustomerActive()) {
            if ($availableShipping) {
                $result = array();
                $val = array();
                foreach ($availableShipping as $key => $array) {
                    $result[$key] = array('id_option' => $array['value'], 'name' => $array['label']);
                    $val[] = $array['value'];
                }
                $serviceOptions = array('query' => $result, 'id' => 'id_option', 'name' => 'name');
            }
            else {
                $serviceOptions = array(
                    'query' => array(
                        array('id_option' => 'express', 'name' => $this->l('Set ws parameters and save to retrieve available shipment types'))),
                    'id'    => 'id_option',
                    'name'  => 'name',
                );
            }
        }
        else {
            $serviceOptions = array(
                'query' => array(
                    array('id_option' => '', 'name' => $this->l('Your user is not active'))),
                'id'    => 'id_option',
                'name'  => 'name',
            );
        }

        $customLabels = array();
        $customInputs = array();
        $allowed_shipment_services = Configuration::get('allowed_shipment_services');
        $val=$allowed_shipment_services;
        if ($val) {
            $values = explode('-', $val);
            if (!empty($values)) {
                foreach ($availableShipping as $t) {
                    if (in_array($t['value'], $values)) {
                        $val = str_replace('+', 'plus', $t['value']);
                        $customInputs[] = array('type' => 'text', 'label' => $t['label'] . ' ' . $this->l('free shipping threshold') . ' ' . $this->l('Domestic'), 'name' => 'mbelimit_' . strtolower($val), 'required' => true, 'class' => 'fixed-width-xl');
                        $customInputs[] = array('type' => 'text', 'label' => $t['label'] . ' ' . $this->l('free shipping threshold') . ' ' . $this->l('Rest of the world'), 'name' => 'mbelimit_' . strtolower($val) . '_ww', 'required' => true, 'class' => 'fixed-width-xl');
                        foreach (Language::getLanguages() as $lang) {
                            $customInputs[] = array(
                                'type' => 'text',
                                'label' => $t['label'] . ' ' . $this->l('Delay' ) . ' ' . $lang['name'],
                                'name' => 'mbeshippingdelay_' . substr(md5($t['label'] . '_' . $lang['iso_code']), 0, 15),
                                'required' => true,
                                'class' => 'fixed-width-xl',
                                'max-length' => 128,
                            );
                        }
                    }
                }

                foreach ($availableShipping as $t) {
                    if (in_array($t['value'], $values)) {
                        $customLabels[] = array(
                            'type' => 'text',
                            'label' => $this->l('Custom name for') . ' ' . $t['label'],
                            'name' => 'mbe_custom_label_' . strtolower(str_replace('+','p',$t['value'])),
                            'required' => false,
                            'desc'     => $this->l('Insert the custom name for the shipment method. Leave blank if you don\'t want to change the default value'),
                            'class' => 'fixed-width-xl',
                        );

                    }
                }
            }
        }

        $customMapping = array();
        $enabled_custom_mapping = Configuration::get(Mbe_Shipping_Helper_Data::XML_PATH_SHIPMENT_CUSTOM_MAPPING);
        if($enabled_custom_mapping === "1") {
            if (version_compare(_PS_VERSION_, '1.5', '<')) {
                global $cookie;
                $defaultMethods = Carrier::getCarriers($cookie->id_lang);
            }
            else {
                $defaultMethods = Carrier::getCarriers(Context::getContext()->language->id);
            }

            $customMapping = [];
            $selectedOptions = [];
            foreach ( $availableShipping as $key=>$value ) {
                $index = array_search($value['value'], array_column($availableShipping, 'value'));
                if (isset($availableShipping[$index]['label'])) {
                    $selectedOptions[] = $availableShipping[$index];
                }
            }
            unset($value);
            foreach ( $defaultMethods as $default_method ) {
                if ( isset( $default_method['id_carrier'] )) {
                    $customMapping[] = array(
                        'type' => 'select',
                        'label' => $this->l('Custom mapping for') . ' ' . $default_method['name'],
                        'name' => 'mbe_custom_mapping_' . strtolower( $default_method['id_carrier'] ),
                        'required' => false,
                        'options'  => array(
                            'query' => ( array_merge( [[ 'value' => ' ' , 'label' => ' ' ]], $selectedOptions ) ),
                            'id'    => 'value',
                            'name'  => 'label',
                        ),
                        'class' => 'fixed-width-xl',
                        'desc'     => $this->l('Select the custom mapping for the default shipping method. Leave blank if you don\'t want to map it'),
                    );
                }
            }
        }

        // Shipment type options
        $shipmentTypeOptions = array(
            'query' => array(
                array('id_option' => 'GENERIC', 'name' => $this->l('Generic'))),
            'id'    => 'id_option',
            'name'  => 'name',
        );
        $customer = $ws->getCustomer();
        if ($customer && $customer->Permissions->canChooseMBEShipType) {
            array_push($shipmentTypeOptions['query'], array('id_option' => 'ENVELOPE', 'name' => $this->l('Envelope')));
        }


        // Closure mode options
        $closureModeOptions = array(
            'query' => array(
                array('id_option' => Mbe_Shipping_Helper_Data::MBE_CLOSURE_MODE_AUTOMATICALLY, 'name' => $this->l('Automatically')),
                array('id_option' => Mbe_Shipping_Helper_Data::MBE_CLOSURE_MODE_MANUALLY, 'name' => $this->l('Manually')),
            ),
            'id'    => 'id_option',
            'name'  => 'name',
        );

        // Closure mode options
        $creationModeOptions = array(
            'query' => array(
                array('id_option' => Mbe_Shipping_Helper_Data::MBE_CREATION_MODE_AUTOMATICALLY, 'name' => $this->l('Automatically')),
                array('id_option' => Mbe_Shipping_Helper_Data::MBE_CREATION_MODE_MANUALLY, 'name' => $this->l('Manually')),
            ),
            'id'    => 'id_option',
            'name'  => 'name',
        );

        $csvModeOptions = array(
            'query' => array(
                array('id_option' => Mbe_Shipping_Helper_Data::MBE_CSV_MODE_DISABLED, 'name' => $this->l('Disabled')),
                array('id_option' => Mbe_Shipping_Helper_Data::MBE_CSV_MODE_TOTAL, 'name' => $this->l('Total')),
                array('id_option' => Mbe_Shipping_Helper_Data::MBE_CSV_MODE_PARTIAL, 'name' => $this->l('Partial')),
            ),
            'id'    => 'id_option',
            'name'  => 'name',
        );

        $insuranceModeOptions = array(
            'query' => array(
                array('id_option' => Mbe_Shipping_Helper_Data::MBE_INSURANCE_WITH_TAXES, 'name' => $this->l('With Taxes')),
                array('id_option' => Mbe_Shipping_Helper_Data::MBE_INSURANCE_WITHOUT_TAXES, 'name' => $this->l('Without Taxes')),
            ),
            'id'    => 'id_option',
            'name'  => 'name',
        );


        // Closure time options
        $closureTimeOptions = array(
            'query' => array(),
            'id'    => 'id_option',
            'name'  => 'name',
        );
        for ($i = 0; $i < 24; $i++) {

            $current = array('id_option' => '0 ' . $i . ' * * *', 'name' => $i . ':00');
            array_push($closureTimeOptions['query'], $current);
            $currentHalf = array('id_option' => '30 ' . $i . ' * * *', 'name' => $i . ':30');
            array_push($closureTimeOptions['query'], $currentHalf);
        }


        $csvFiles = array();
        if (Configuration::get("shipments_csv")) {
            $csvFiles[] = array(
                'file'         => Configuration::get("shipments_csv"),
                'download_url' => $this->_module_url . 'uploads/' . Configuration::get("shipments_csv"),
            );
        }
        $csvFileTemplate = sprintf('<a href="%s" target="_blank">' . $this->l('Download template file') . '</a>', $this->_module_url . 'uploads/mbe_csv_template.csv');

        $csvPackageFiles = array();
        if (Configuration::get("mbe_shipping_packages_csv")) {
            $csvPackageFiles[] = array(
                'file'         => Configuration::get("mbe_shipping_packages_csv"),
                'download_url' => $this->_module_url . 'uploads/' . Configuration::get("mbe_shipping_packages_csv"),
            );
        }
        $csvPackageFileTemplate = sprintf('<a href="%s" target="_blank">' . $this->l('Download template file') . '</a>', $this->_module_url . 'uploads/mbe_package_csv_template.csv');

        $csvPackageProductFiles = array();
        if (Configuration::get("mbe_shipping_packages_product_csv")) {
            $csvPackageProductFiles[] = array(
                'file'         => Configuration::get("mbe_shipping_packages_product_csv"),
                'download_url' => $this->_module_url . 'uploads/' . Configuration::get("mbe_shipping_packages_product_csv"),
            );
        }
        $csvPackageProductFileTemplate = sprintf('<a href="%s" target="_blank">' . $this->l('Download template file') . '</a>', $this->_module_url . 'uploads/mbe_package_product_csv_template.csv');


        // Init Fields form array
        $fields_form[0]['form'] = array(
            'buttons' => array(
                '0' => array(
                    'type' => 'button',
                    'title' => $this->l('Delete debug files'),
                    'name' => 'btnDeleteLogs',
                    'icon' => 'process-icon-delete',
                    'class' => 'pull-right',
                    'href' => $curIndex . '&configure=' . $this->name . '&deletelogs=1&token=' . Tools::getAdminTokenLite('AdminModules'),
                ),
                '1' => array(
                    'type' => 'button',
                    'title' => $this->l('Download debug files'),
                    'name' => 'btnDownloadLogs',
                    'icon' => 'process-icon-download-alt',
                    'class' => 'pull-right',
                    'href' => $curIndex . '&configure=' . $this->name . '&downloadlogs=1&token=' . Tools::getAdminTokenLite('AdminModules'),
                ),
            ),
            'legend' => array(
                'title' => $this->l('Settings'),
            ),
            'input'  => array(
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Debug'),
                    'name'     => 'mbe_debug',
                    'desc'     => $this->l('Activate Debug mode to save MBE e-Link logs'),
                    'options'  => array(
                        'query' => array(array('id_option' => 1, 'name' => $this->l('Yes')), array('id_option' => 0, 'name' => $this->l('No'))),
                        'id'    => 'id_option',
                        'name'  => 'name',
                    ),
                    'required' => true,
                ),
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Enabled'),
                    'name'     => 'mbe_active',
                    'options'  => array(
                        'query' => array(array('id_option' => 1, 'name' => $this->l('Yes')), array('id_option' => 0, 'name' => $this->l('No'))),
                        'id'    => 'id_option',
                        'name'  => 'name',
                    ),
                    'required' => true,
                ),
                array(
                    'type'  => 'select',
                    'label' => $this->l('Country'),
                    'name'  => 'mbecountry',
                    'desc'  => $this->l('Select your MBE Center\'s country'),

                    'options'  => array(
                        'query' => array(
                            array('id_option' => 'IT', 'name' => $this->l('Italy')),
                            array('id_option' => 'ES', 'name' => $this->l('Spain')),
                            array('id_option' => 'DE', 'name' => $this->l('Germany')),
                            array('id_option' => 'FR', 'name' => $this->l('France')),
                            array('id_option' => 'AT', 'name' => $this->l('Austria')),
							array('id_option' => 'PL', 'name' => $this->l('Polonia')),
                            array('id_option' => 'HR', 'name' => $this->l('Croatia'))),
                        'id'    => 'id_option',
                        'name'  => 'name',
                    ),
                    'required' => true,
                ),
                array(
                    'type'     => 'text',
                    'label'    => $this->l('OnlineMBE web-service URL'),
                    'desc'     => $this->l('Please contact the MBE center'),
                    'name'     => 'url',
                    'required' => true,
                    'class'    => 'fixed-width-xl',
                ),
                array(
                    'type'     => 'text',
                    'label'    => $this->l('OnlineMBE Username'),
                    'name'     => 'username',
                    'required' => true,
                    'class'    => 'fixed-width-xl',
                ),
                array(
                    'type'     => 'text',
                    'label'    => $this->l('OnlineMBE web-service passphrase (provided by MBE Center)'),
                    'name'     => 'password',
                    'required' => true,
                    'class'    => 'fixed-width-xl',
                ),
                array(
                    'type'     => 'text',
                    'label'    => $this->l('MBE shipping description'),
                    'name'     => 'title',
                    'required' => true,
                    'class'    => 'fixed-width-xl',
                ),
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Default shipment type'),
                    'name'     => 'default_shipment_type',
                    'options'  => $shipmentTypeOptions,
                    'required' => true,
                ),
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Select MBE Services available to your Customers'),
                    'name'     => (version_compare(_PS_VERSION_, '1.6', '<') && version_compare(_PS_VERSION_, '1.5', '>')) ? 'allowed_shipment_services[]' : 'allowed_shipment_services',
                    'options'  => $serviceOptions,
                    'multiple' => true,
                    'required' => true,
                ),
            ),
        );
        if (!empty($customLabels)) {
            $fields_form[0]['form']['input'] = array_merge($fields_form[0]['form']['input'], $customLabels);
        }

        $otherFields=array(
            array(
                'type'     => 'select',
                'label'    => $this->l('Default shipping methods mapping'),
                'name'     => 'mbe_enable_custom_mapping',
                'options'  => array(
                    'query' => array(array('id_option' => 1, 'name' => $this->l('Yes')), array('id_option' => 0, 'name' => $this->l('No'))),
                    'id'    => 'id_option',
                    'name'  => 'name',
                ),
                'desc' => $this->l( 'Enable the function to map default shipping methods to MBE services (MBE methods will not be available on the frontend)'),
                'required' => true,
            ),
        );
        $fields_form[0]['form']['input'] = array_merge($fields_form[0]['form']['input'], $otherFields);

        if (!empty($customMapping)) {
            $fields_form[0]['form']['input'] = array_merge($fields_form[0]['form']['input'], $customMapping);
        }

        $otherFields=array(
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Shipment configuration mode'),
                    'name'     => 'shipment_configuration_mode',
                    'options'  => array(
                        'query' => array(
                            array('id_option' => '1', 'name' => $this->l('Create one Shipment per Item')),
                            array('id_option' => '2', 'name' => $this->l('Create one Shipment per shopping cart (parcels calculated based on weight)')),
                            array('id_option' => '3', 'name' => $this->l('Create one Shipment per shopping cart with one parcel per Item'))),
                        'id'    => 'id_option',
                        'name'  => 'name',
                    ),
                    'desc'     => $this->l('WARNING: activating the option \'Create one Shipment per Item\' with COD payment, the shopping cart\'s amount will be split and charged evenly on each shipment (based on number of items, not on their value)'),
                    'required' => true,
                ),
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Csv for standard packages'),
                    'name'     => 'mbe_shipping_use_packages_csv',
                    'options'  => array(
                        'query' => array(array('id_option' => 1, 'name' => $this->l('Yes')), array('id_option' => 0, 'name' => $this->l('No'))),
                        'id'    => 'id_option',
                        'name'  => 'name',
                    ),
                    'desc'     => $this->l('Load the standard packages via csv file'),
                    'required' => true,
                ),
        );
        $fields_form[0]['form']['input'] = array_merge($fields_form[0]['form']['input'], $otherFields);

        $mbe_shipping_use_packages_csv = Configuration::get('mbe_shipping_use_packages_csv');
        if (!empty($mbe_shipping_use_packages_csv) && $mbe_shipping_use_packages_csv == '1') {
            $customePackage=array(
                array(
                    'type'     => 'file',
                    'label'    => $this->l('Packages via csv - File upload'),
                    'name'     => 'mbe_shipping_packages_csv',
                    'required' => false,
                    'files'    => $csvPackageFiles,
                    'desc'     => $csvPackageFileTemplate,
                ),
                array(
                    'type'     => 'file',
                    'label'    => $this->l('Packages for products via csv - File upload'),
                    'name'     => 'mbe_shipping_packages_product_csv',
                    'required' => false,
                    'files'    => $csvPackageProductFiles,
                    'desc'     => $csvPackageProductFileTemplate,
                ),
            );
            $fields_form[0]['form']['input'] = array_merge($fields_form[0]['form']['input'], $customePackage);
        }

        $otherFields=array(
                array(
                    'type'     => 'text',
                    'label'    => $this->l('Default Package Length'),
                    'name'     => 'default_length',
                    'required' => true,
                    'class'    => 'fixed-width-xl',
                ),
                array(
                    'type'     => 'text',
                    'label'    => $this->l('Default Package Width'),
                    'name'     => 'default_width',
                    'required' => true,
                    'class'    => 'fixed-width-xl',
                ),
                array(
                    'type'     => 'text',
                    'label'    => $this->l('Default Package Height'),
                    'name'     => 'default_height',
                    'required' => true,
                    'class'    => 'fixed-width-xl',
                ),
                array(
                    'type'     => 'text',
                    'label'    => $this->l('Maximum Package Weight'),
                    'desc'     => $this->l('Check if any limitation is applied with your MBE Center'),
                    'name'     => 'max_package_weight',
                    'required' => true,
                    'class'    => 'fixed-width-xl',
                ),
                array(
                    'type'     => 'text',
                    'label'    => $this->l('Maximum shipment weight'),
                    'name'     => 'max_shipment_weight',
                    'required' => true,
                    'class'    => 'fixed-width-xl',
                ),
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Markup - Application rule'),
                    'name'     => 'handling_type',
                    'options'  => array(
                        'query' => array(
                            array('id_option' => 'P', 'name' => $this->l('Percentage')),
                            array('id_option' => 'F', 'name' => $this->l('Fixed amount'))),
                        'id'    => 'id_option',
                        'name'  => 'name',
                    ),
                    'required' => true,
                ),
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Handling Applied'),
                    'name'     => 'handling_action',
                    'options'  => array(
                        'query' => array(
                            array('id_option' => 'S', 'name' => $this->l('Shipment')),
                            array('id_option' => 'P', 'name' => $this->l('Parcel'))),
                        'id'    => 'id_option',
                        'name'  => 'name',
                    ),
                    'required' => true,
                ),
                array(
                    'type'     => 'text',
                    'label'    => $this->l('Handling Fee'),
                    'name'     => 'handling_fee',
                    'required' => true,
                    'class'    => 'fixed-width-xl',
                ),
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Markup - Apply rounding'),
                    'name'     => 'handling_fee_rounding',
                    'options'  => array(
                        'query' => array(
                            array('id_option' => '1', 'name' => $this->l('No rounding')),
                            array('id_option' => '2', 'name' => $this->l('Round up or down automatically')),
                            array('id_option' => '3', 'name' => $this->l('Always round down')),
                            array('id_option' => '4', 'name' => $this->l('Always round up'))),
                        'id'    => 'id_option',
                        'name'  => 'name',
                    ),
                    'required' => true,
                ),
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Markup - Rounding unit (in €)'),
                    'name'     => 'handling_fee_rounding_amount',
                    'options'  => array(
                        'query' => array(
                            array('id_option' => '1', 'name' => '1'),
                            array('id_option' => '2', 'name' => '0.5')),
                        'id'    => 'id_option',
                        'name'  => 'name',
                    ),
                    'required' => true,
                ),
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Ship to Applicable Countries'),
                    'name'     => 'sallowspecific',
                    'options'  => array(
                        'query' => array(
                            array('id_option' => '0', 'name' => $this->l('All Allowed Countries')),
                            array('id_option' => '1', 'name' => $this->l('Specific Countries'))),
                        'id'    => 'id_option',
                        'name'  => 'name',
                    ),
                    'required' => true,
                ),
                array(
                    'type'          => 'select',
                    'label'         => $this->l('Country'),
                    'name'          => (version_compare(_PS_VERSION_, '1.6', '<') && version_compare(_PS_VERSION_, '1.5', '>')) ? 'specificcountry[]' : 'specificcountry',
                    'required'      => false,
                    'default_value' => (int)$this->context->country->id,
                    'col'           => 4,
                    'options'       => array(
                        'query' => Country::getCountries($this->context->language->id),
                        'id'    => 'iso_code',
                        'name'  => 'name',
                    ),
                    'multiple'      => true,
                ),
                array(
                    'type'     => 'select',
                    'label'    => $this->l('OnlineMBE daily shipments closure - Mode'),
                    'name'     => 'shipments_closure_mode',
                    'required' => false,
                    'options'  => $closureModeOptions,
                ),
                array(
                    'type'     => 'select',
                    'label'    => $this->l('Shipments creation in OnlineMBE - Mode'),
                    'name'     => 'shipments_creation_mode',
                    'required' => false,
                    'options'  => $creationModeOptions,
                ),
//                array(
//                    'type' => 'select',
//                    'label' => $this->l('OnlineMBE daily time shipments closure (automatic mode only)'),
//                    'name' => 'shipments_closure_time',
//                    'required' => false,
//                    'options' => $closureTimeOptions,
//                    'class' => 'size-class'
//                )

                //http://stackoverflow.com/questions/27205564/prestashop-helper-form-file-type
                array(
                    'type'     => 'file',
                    'label'    => $this->l('Custom prices via csv - File upload'),
                    'name'     => 'shipments_csv',
                    'required' => false,
                    'files'    => $csvFiles,
                    'desc'     => $csvFileTemplate,
                ),

                array(
                    'type'     => 'hidden',
                    'label'    => $this->l('Csv Template'),
                    'name'     => 'shipments_csv_template',
                    'required' => false,
                ),


                array(
                    'type'     => 'select',
                    'label'    => $this->l('Custom prices via csv - File mode'),
                    'name'     => 'shipments_csv_mode',
                    'required' => false,
                    'options'  => $csvModeOptions,
                ),

                array(
                    'type'     => 'text',
                    'label'    => $this->l('Custom prices via csv - Min price for insurance extra-service'),
                    'name'     => 'mbe_shipments_csv_insurance_min',
                    'required' => false,
                    'class'    => 'fixed-width-xl',
                ),

                array(
                    'type'     => 'text',
                    'label'    => $this->l('Custom prices via csv - % for insurance extra-service price calculation'),
                    'name'     => 'mbe_shipments_csv_insurance_per',
                    'required' => false,
                    'class'    => 'fixed-width-xl',
                ),

                array(
                    'type'     => 'select',
                    'label'    => $this->l('Insurance extra-service - Declared value calculation'),
                    'name'     => 'mbe_shipments_ins_mode',
                    'required' => false,
                    'options'  => $insuranceModeOptions,
                ),
                array(
                    'type' => 'select',
                    'label' => $this->l('Automatically sets the order as shipped'),
                    'desc'     => $this->l('When the MBE shipment is closed if the order is in "Payment accepted" status will be automatically set as "Shipped" and notified to the customer.'),
                    'name' => 'mbe_auto_change_order_status',
                    'options' => array(
                        'query' => array(array('id_option' => 1, 'name' => $this->l('Yes')), array('id_option' => 0, 'name' => $this->l('No'))),
                        'id' => 'id_option',
                        'name' => 'name',
                    ),
                    'required' => false,
                ),
            );

        $fields_form[0]['form']['input'] = array_merge($fields_form[0]['form']['input'], $otherFields);
        /*$mbe_uap=0;
        if ($customer && $allowed_shipment_services) {
            $values = explode('-', $allowed_shipment_services);
            if (!empty($values)) {
                if (in_array('MDP', $values)) {
                    $mbe_uap=1;
                }
            }
        }

        Configuration::updateValue("mbe_uap", $mbe_uap);*/

        if (empty($customInputs)) {
            $optionsKey = 'desc';
            $options = 'Free shipping Thresholds';
        }
        else {
            $optionsKey = 'input';
            $options = $customInputs;
        }

        $fields_form[1]['form'] = array(
            'legend'    => array(
                'title' => $this->l('MBE Shipping - Free shipping Thresholds & Translations'),
            ),
            $optionsKey => $options,
            'submit'    => array(
                'title' => $this->l('Save'),
                'class' => 'button',
            ),
        );

        $helper = new HelperForm();

        // Module, token and currentIndex
        $helper->module = $this;
        $helper->name_controller = $this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->currentIndex = $curIndex . '&configure=' . $this->name;


        // Language
        $helper->default_form_language = $default_lang;
        $helper->allow_employee_form_lang = $default_lang;


        // Title and toolbar
        $helper->title = $this->displayName;
        $helper->show_toolbar = true;        // false -> remove toolbar
        $helper->toolbar_scroll = true;      // yes - > Toolbar is always visible on the top of the screen.
        $helper->submit_action = 'submit' . $this->name;

        $helper->toolbar_btn = array(
            'save' =>
                array(
                    'desc' => $this->l('Save'),
                    'href' => $curIndex . '&configure=' . $this->name . '&save' . $this->name . '&token=' . Tools::getAdminTokenLite('AdminModules'),
                ),
            'back' => array(
                'href' => $curIndex . '&token=' . Tools::getAdminTokenLite('AdminModules'),
                'desc' => $this->l('Back to list'),
            )
        );


        // Load current value
        foreach ($fields_form as $form) {
            if (isset($form['form']['input'])) {
                foreach ($form['form']['input'] as $v) {
                    $values[] = ($v['name']);
                }
            }
            foreach ($values as $key => $value) {
                if (in_array($value, array('specificcountry', 'specificcountry[]', 'allowed_shipment_services', 'allowed_shipment_services[]'))) {
                    if (in_array($value, array('specificcountry[]', 'allowed_shipment_services[]'))) {
                        $helper->fields_value[$value] = explode('-', Configuration::get(substr($value, 0, -2)));
                    }
                    else {
                        $helper->fields_value[$value . '[]'] = explode('-', Configuration::get($value));
                    }
                }
                else {
                    $helper->fields_value[$value] = Configuration::get($value);
                }
            }
        }

        return $helper->generateForm($fields_form);
    }

    ###################################################################
    ## Price management
    ###################################################################

    public function getOrderShippingCostExternal($cart)
    {
        return $this->getOrderShippingCost($cart, 0);
    }

    public function getOrderShippingCost($cart, $shipping_cost)
    {
        //maybe use cache
        //$cache_id = spl_object_hash($cart);
        if (!$this->pricesMbeLoaded) {
            $this->getPricesMbe($cart);
            $this->pricesMbeLoaded = true;
        }
        $result = 0;
        if (!empty($this->_carriers)) {
            if( array_key_exists($this->id_carrier, $this->_carriers)) {
                $price_in_euro = $this->_carriers[(string)$this->id_carrier]['price'];
                $currency = new Currency($cart->id_currency);
                if (version_compare(_PS_VERSION_, '1.5', '<')) {
                    $result = Tools::ps_round($price_in_euro * (float)$currency->conversion_rate, 2);
                } else {
                    $result = Tools::convertPriceFull($price_in_euro, null, $currency);
                }
            }
            else
                return false;
        }
        return $result;

    }


    public function getPricesMbe($cart)
    {
        if (!isset($_SESSION['loggedin']) && (isset($cart->id_address_delivery) || isset($cart['cart']) && isset($cart['cart']->id_address_delivery))) {
            if (version_compare(_PS_VERSION_, '1.5', '<')) {
                global $cookie;
                $carriers = Carrier::getCarriers($cookie->id_lang, false, false, false, null, CarrierCore::PS_CARRIERS_ONLY, $cart);
            }
            else {
                $carriers = Carrier::getCarriers($this->context->language->id, false, false, false, null, CarrierCore::PS_CARRIERS_ONLY, $cart);
            }
            foreach ($carriers as $carrier) {
                $this->_carriers[$carrier['id_carrier']] = $carrier;
            }
            return true;
        }
    }

    public function hookPostUpdateOrderStatus($params)
    {
        $this->hookActionOrderStatusPostUpdate($params);
    }

    public function hookActionOrderStatusPostUpdate($params)
    {
        // 2 è lo stato del pagamento accettato. (Inserire qui altri stati) todo: fix with constant if exists
        $helper = new Mbe_Shipping_Helper_Data();

        if ($helper->isEnabled() && Configuration::get('shipments_creation_mode') == Mbe_Shipping_Helper_Data::MBE_CREATION_MODE_AUTOMATICALLY) {
            $order_id = (int)$params['id_order'];
            $order = new Order($order_id);


            $cashOnDeliveryModuleName = $helper->getCashOnDeliveryModuleName();
            if ((in_array($params['newOrderStatus']->id, array(2)) && $order->module != $cashOnDeliveryModuleName) || (in_array($params['newOrderStatus']->id, array(3)) && $order->module == $cashOnDeliveryModuleName)) {
                $cart = new Cart($order->id_cart);
                $carrier = new Carrier($order->id_carrier);

                //if ($carrier->external_module_name == 'mbeshipping') {
                if( $helper->isMbeShipping($order)){
                    if (version_compare(_PS_VERSION_, '1.5', '<')) {
                        $service = Configuration::get('carrier_' . $order->id_carrier);
                        //$service empty custom mapping is enabled. Get the service by ctsom mapping
                        if(!$service || $service==='')
                        {
                            $service = $helper->getCustomMappingService($carrier->id);
                        }
                        $orderHelper = new Mbe_Shipping_Helper_Order();
                        $orderHelper->addShipping($order, $service);
                    }
                    else {
                        $this->getPricesMbe($cart);
                        $carrierCheck = $this->_carriers[$order->id_carrier];
                        if (is_array($carrierCheck)) {
                            $service = Configuration::get('carrier_' . $order->id_carrier);
                            //$service empty custom mapping is enabled. Get the service by ctsom mapping
                            if(!$service || $service==='')
                            {
                                $service = $helper->getCustomMappingService($carrier->id);
                            }
                            $orderHelper = new Mbe_Shipping_Helper_Order();
                            $orderHelper->addShipping($order, $service);
                        }
                    }
                }

            }
        }
    }

    /*ACCESS POINT*/
    private function createContent($params)
    {
        try {
            $helper = new Mbe_Shipping_Helper_Data();

            $context = $this->context;

            $cart = isset($params['cart']) ? $params['cart'] : $context->cart;

            $carrier = isset($params['carrier']) ? $params['carrier'] : new Carrier($cart->id_carrier);

            if (version_compare(_PS_VERSION_, '1.7', '<')) {
              $carrierName = $carrier->name;
              $carrierId=$carrier->id;
            }
            else {
                $carrierName = $carrier['name'];
                $carrierId=$carrier['id'];
            }

            $uapList=null;
            $mbe_uap = false;

            if (strpos(strtolower($carrierName), '(mdp)') !== false || $helper->isMBEDeliveryPoint($carrierName)) {

                //$mbe_uap_conf = Configuration::get('mbe_uap');

                //if($mbe_uap_conf) {

                    $address = new Address($cart->id_address_delivery);
                    $iso_code = Country::getIsoById($address->id_country);
                    /*$cartTotalWeight = $helper->convertWeight($cart->getTotalWeight());
                    $weightOk  = (( $cartTotalWeight<= MBE_UAP_WEIGHT_LIMIT) && ($cartTotalWeight <= $helper->getMaxPackageWeight()));
                    $countryOK = in_array($iso_code, MBE_UAP_ALLOWED_COUNTRIES_LIST);

                    $shipmentConfigurationMode = $helper->getShipmentConfigurationMode();

                    $products=$cart->getProducts();
                    $oneParcel=false;
                    switch ($shipmentConfigurationMode) {
                        //SHIPMENT_CONFIGURATION_MODE_ONE_SHIPMENT_PER_ITEM
                        case 1:
                            $oneParcel=true;
                            foreach ($products as $p) {
                                if($p['weight']>MBE_UAP_WEIGHT_LIMIT) {
                                    $oneParcel = false;
                                    breack;
                                }
                            }
                            break;
                        //SHIPMENT_CONFIGURATION_MODE_ONE_SHIPMENT_PER_SHOPPING_CART_SINGLE_PARCEL
                        case 2:
                            $oneParcel = $weightOk;
                            break;
                        //SHIPMENT_CONFIGURATION_MODE_ONE_SHIPMENT_PER_SHOPPING_CART_MULTI_PARCEL
                        case 3:
                            $total_quantity=0;
                            foreach ($products as $p) {
                                $total_quantity +=$p['quantity'];
                            }
                            $oneParcel = $total_quantity==1 && $weightOk;
                            break;
                    }*/

                    //if ( $oneParcel && $countryOK ) {
                        $mbe_uap=true;
                        $uapList = Mbe_Shipping_Helper_Ups_Uap::getUapList(array(
                            'AddressLine1' =>  $address->address1,
                            'PostcodePrimaryLow' => $address->postcode,
                            'PoliticalDivision2' => $address->city,
                            'PoliticalDivision1' =>  State::getNameById($address->id_state),
                            'CountryCode' => $iso_code,
                            'language' => 'IT',
                            'MaximumListSize' => '20',
                            'SearchRadius' => '20'
                        ));
                    //}
                //}
            }

            $this->context->smarty->assign(
                array(
                    'mbe_uap'      => $mbe_uap,
                    'uapList'      => $uapList,
                    'carrierId' => $carrierId,
                    'suap' => base64_encode(serialize($uapList))
                ));
        }
        catch (Exception $e) {
            //$this->log('CREATE CONTENT SMARTY EXCEPTION');
            //$this->log($e->getMessage());
        }
    }

    public function hookDisplayCarrierExtraContent($params)
    {
       $this->createContent($params);
        return $this->display(__FILE__, 'mbe_access_point_shipping.tpl');
    }

    public function hookExtraCarrier($params)
    {
        $this->createContent($params);
        return $this->display(__FILE__, 'mbe_access_point_shipping-16.tpl');
    }

    public function hookActionValidateOrder($params)
    {
        $context = $this->context;

        try {
            $mbeUap = null;

            //if (_PS_VERSION_ >= 1.7) {
                /*if($context->cookie->__isset('mbe_mdp') ) {
                    $mbeUap = $context->cookie->__get('mbe_mdp');
                }*/
            if (session_status() == PHP_SESSION_NONE) {
                session_start();
            }

            if (session_status() == PHP_SESSION_ACTIVE && isset($_SESSION['mbe_mdp'])) {
                $mbeUap = $_SESSION['mbe_mdp'];
                unset($_SESSION['mbe_mdp']);
            } elseif (isset($_COOKIE['mbe_mdp'])) {
                $mbeUap = $_COOKIE['mbe_mdp'];
                unset($_COOKIE['mbe_mdp']);
            }
           /* }
            else
            {
                if(isset($_COOKIE['mbe_mdp'])) {
                    $mbeUap = $_COOKIE['mbe_mdp'];
                }
            }*/
            if($mbeUap!=null) {
                $mbeUap = unserialize(base64_decode($mbeUap));

                $cart = isset($params['cart']) ? $params['cart'] : null;
                $order = isset($params['order']) ? $params['order'] : null;
                //$carrier = new Carrier($cart->id_carrier);
                $service = Configuration::get('carrier_' . $cart->id_carrier);
                if ($service && $service == 'MDP') {

                    $address_delivery = new Address($cart->id_address_delivery);

                    $uapOrderAddress=new Address();
                    $uapOrderAddress->id_customer = $address_delivery->id_customer;
                    $uapOrderAddress->company = $mbeUap['ConsigneeName'];
                    $uapOrderAddress->address1 = str_replace("\n"," ",$mbeUap['AddressLine']);
                    $uapOrderAddress->city = $mbeUap['PoliticalDivision2'];
                    $uapOrderAddress->id_state = $address_delivery->id_state;
                    $uapOrderAddress->id_country = $address_delivery->id_country;
                    $uapOrderAddress->postcode = $mbeUap['PostcodePrimaryLow'];
                    $uapOrderAddress->other = 'UAP';


                    $uapOrderAddress->firstname = $address_delivery->firstname;
                    $uapOrderAddress->lastname = $address_delivery->lastname;

                    $uapOrderAddress->phone = strlen($address_delivery->phone) > 0 ? $address_delivery->phone : $address_delivery->phone_mobile;

                    $uapOrderAddress->alias='UAP-' . $mbeUap['PublicAccessPointID'] . '-Cart' .  $cart->id;

                    $uapOrderAddress->save();

                    $cart->id_address_delivery = $uapOrderAddress->id;
                    $cart->update();

                    $order->id_address_delivery = $uapOrderAddress->id;
                    $order->update();

                    $uapOrderAddress->delete();
                }

            }
        }

        catch (Exception $e) {
            //$this->log('CREATE CONTENT SMARTY EXCEPTION');
            //$this->log($e->getMessage());
        }
        /*if (_PS_VERSION_ >= 1.7) {
            $context->cookie->__unset('mbe_mdp');
        }
        else
        {
            setcookie("mbe_mdp", "", time()-3600);
        }*/
    }
    /**/

}
