<?php // NOSONAR
if (!defined('_PS_VERSION_')) {
    exit();
}

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

include_once(dirname( __FILE__ )  . '/chilexpress_oficial_api.php');
include_once(dirname( __FILE__ )  . '/controllers/admin/ChilexpressOrderController.php');
include_once(dirname( __FILE__ )  . '/classes/ChilexpressOficialApiCache.php');

define('CXP_CHILEXPRESS_ORDER', 'ChilexpressOrder');
define('CXP_API_KEY_GEOREFERENCIA_VALUE','api_key_georeferencia_value');
define('CXP_API_KEY_GENERACION_OT_VALUE','api_key_generacion_ot_value');
define('CXP_API_KEY_COTIZADOR_VALUE','api_key_cotizador_value');
define('CXP_API_KEY_GEOREFERENCIA_ENABLED','api_key_georeferencia_enabled');
define('CXP_API_KEY_GENERACION_OT_ENABLED','api_key_generacion_ot_enabled');
define('CXP_API_KEY_COTIZADOR_ENABLED','api_key_cotizador_enabled');
define('CXP_AMBIENTE', 'ambiente');
define('CXP_REGION_ORIGEN', 'region_origen');
define('CXP_ARTICULOS_TIENDA', 'articulos_tienda');
define('CXP_COMUNA_ORIGEN', 'comuna_origen');
define('CXP_COMUNA_DESTINO', 'comuna_destino');
define('CXP_NUMERO_TCC_ORIGEN', 'numero_tcc_origen');
define('CXP_RUT_MARKETPLACE_REMITENTE', 'rut_marketplace_remitente');
define('CXP_REGION_DEVOLUCION', 'region_devolucion');
define('CXP_COMUNA_DEVOLUCION', 'comuna_devolucion');
define('CXP_ADMINMODULES', 'AdminModules');
define('CXP_ID_FORM', 'id_form');
define('CXP_LEGEND', 'legend');
define('CXP_TITLE', 'title');
define('CXP_INPUT', 'input');
define('CXP_SWITCH', 'switch');
define('CXP_LABEL', 'label');
define('CXP_MODULES_CONTACTFORM_ADMIN', 'Modules.Contactform.Admin');

/// 
define('CXP_IS_BOOL', 'is_bool');
define('CXP_REQUIRED', 'required');
define('CXP_VALUES', 'values');
define('CXP_VALUE', 'value');
define('CXP_ADMIN_GLOBAL', 'Admin.Global');
define('CXP_HABILITADO', 'Habilitado');
define('CXP_DESHABILITADO', 'Deshabilitado');
define('CXP_MODULES_BANNER_ADMIN', 'Modules.Banner.Admin');
define('CXP_SELECT', 'select');
define('CXP_OPTIONS', 'options');
define('CXP_QUERY', 'query');
define('CXP_SUBMIT', 'submit');
define('CXP_GUARDAR', 'Guardar');
define('CXP_CLASS', 'class');
define('CXP_BTN_BTN_DEFAULT_PULL_RIGHT', 'btn btn-default pull-right');
define('CXP_NOMBRE_REMITENTE', 'nombre_remitente');
define('CXP_TELEFONO_REMITENTE', 'telefono_remitente');
define('CXP_EMAIL_REMITENTE', 'email_remitente');
define('CXP_RUT_SELLER_REMITENTE', 'rut_seller_remitente');
define('CXP_CALLE_DEVOLUCION', 'calle_devolucion');
define('CXP_NUMERO_CALLE_DEVOLUCION', 'numero_calle_devolucion');
define('CXP_COMPLEMENTO_DEVOLUCION', 'complemento_devolucion');
define('CXP_ID_CARRIER', 'id_carrier');
define('CXP_CARRIER', 'carrier');
define('CXP_DELIVERY', 'delivery');
define('CXP_ID_ZONE', 'id_zone');
define('CXP_ID_PRODUCT', 'id_product');
define('CXP_CART_QUANTITY', 'cart_quantity');
define('CXP_WIDTH', 'width');
define('CXP_HEIGHT', 'height');
define('CXP_DEPTH', 'depth');
define('CXP_WEIGHT', 'weight');
define('CXP_TOTAL', 'total');
define('CXP_SERVICETYPECODE', 'serviceTypeCode');
define('CXP_SERVICEVALUE', 'serviceValueDiscount');
define('CXP_FIELDS', 'fields');
define('CXP_TEXT_CENTER', 'text-center');
define('CXP_ALIGN', 'align');
define('CXP_FIXED_WIDTH_XS', 'fixed-width-xs');
define('CXP_FILTER_KEY', 'filter_key');
define('CXP_CARRIER_NAME', 'carrier_name');
define('CXP_TRACKING_NUMBER', 'tracking_number');
define('CXP_ID_ORDER', 'id_order');
define('CXP_ORDER_ID_EQ', '&order_id=');
define('CXP_A_HREF', '<a href="');
define('CXP_ORDER', 'order');
define('CXP_ADMIN_INTERNATIONAL_NOTIFICATION', 'Admin.International.Notification');
define('CXP_DIAS_PREPARACION_PEDIDOS', 'dias_preparacion_pedidos');
define('CXP_REGIONES_HABILITADAS', 'regiones_habilitadas');
define('CXP_COMUNAS_HABILITADAS', 'comunas_habilitadas');
define('CXP_PRIORIDAD_SERVICIOS', 'prioridad_servicios');

define('CXP_PRODUCT_DEFAULT_WIDTH', 'product_default_width');
define('CXP_PRODUCT_DEFAULT_HEIGHT', 'product_default_height');
define('CXP_PRODUCT_DEFAULT_DEPTH', 'product_default_depth');
define('CXP_PRODUCT_DEFAULT_WEIGHT', 'product_default_weight');

define('CXP_PORCENTAJE_DESCUENTO', 'porcentaje_descuento');

define('CXP_CORTE_HORARIO', 'corte_horario_ampm');
define('CXP_DIAS_SEMANA_AMPM', 'dias_semana_ampm');

use PrestaShop\PrestaShop\Core\Grid\Action\Bulk\Type\SubmitBulkAction;

class Chilexpress_Oficial extends CarrierModule // NOSONAR 
{
    public $id_carrier; // BUGFIX 9.0.0 // https://github.com/PrestaShop/PrestaShop/issues/38207

    protected $_errors = array();

    public function __construct()
    {
        $this->name = 'chilexpress_oficial';
        $this->tab = 'shipping_logistics';
        $this->version = '1.4.0';
        $this->author = 'Chilexpress';
        $this->need_instance = 1;
        $this->ps_versions_compliancy = array('min' => '1.7.1.0', 'max' => _PS_VERSION_); // NOSONAR
        $this->limited_countries = array('cl');
        $this->bootstrap = true;
        $this->id_carrier = true;

        /*
            2) PRIORITARIO: 1 dia (día sig habil hasta 11 am)
            3) EXPRESS: 1 dia
            4) EXTENDIDO: 1 - 2 dias
            5) EXTREMOS: 2 - 3 dias
            8) AM/PM: 0 dias (mismo día hasta 22 hrs)
            41) ENC. GRANDES: 2 días hábiles, entre 11:00 y 19:00 hrs
            42) ENC. GRANDES EXTENDIDO: 6 días hábiles, entre 11:00 y 19:00 hrs
            53) BASICO: 3 dias
			54) BASICO: 4 dias
			55) BASICO: 5 dias
            56) EXTREMOS: 12 dias

        */

        $this->carriers_list = array(
            'CHILEXPRESS_OFCL_DHSP' => 'PRIORITARIO',
            'CHILEXPRESS_OFCL_DHS'  => 'EXPRESS',
            'CHILEXPRESS_OFCL_DHSS' => 'EXTENDIDO',
            'CHILEXPRESS_OFCL_3DH'  => 'EXTREMOS',
            'CHILEXPRESS_OFCL_EDS'  => 'ENTREGA DIA SABADO',
            'CHILEXPRESS_OFCL_BIG1' => 'ENC. GRANDES',
            'CHILEXPRESS_OFCL_BIG2' => 'ENC. GRANDES EXTENDIDO',
            'CHILEXPRESS_OFCL_MDAP' => 'AM/PM',
            'CHILEXPRESS_OFCL_BSC3' => 'BASICO',
            'CHILEXPRESS_OFCL_BSC4' => 'BASICO',
            'CHILEXPRESS_OFCL_BSC5' => 'BASICO',
            'CHILEXPRESS_OFCL_EX12' => 'EXTREMO SUR'
        );

        $this->carriers_serviceTypeCode = array(
            'CHILEXPRESS_OFCL_DHSP' => 2,
            'CHILEXPRESS_OFCL_DHS'  => 3,
            'CHILEXPRESS_OFCL_DHSS' => 4,
            'CHILEXPRESS_OFCL_3DH'  => 5,
            'CHILEXPRESS_OFCL_MDAP' => 8,
            'CHILEXPRESS_OFCL_EDS'  => 11,
            'CHILEXPRESS_OFCL_BIG1' => 41,
            'CHILEXPRESS_OFCL_BIG2' => 42,
            'CHILEXPRESS_OFCL_BSC3' => 53,
            'CHILEXPRESS_OFCL_BSC4' => 54,
            'CHILEXPRESS_OFCL_BSC5' => 55,
            'CHILEXPRESS_OFCL_EX12' => 56
        );

        $this->api = new Chilexpress_Oficial_API();

        parent::__construct();

        $this->displayName = $this->l('Chilexpress Oficial', $this->name);
        $this->description = $this->l('Agrega soporte oficial para Chilexpress en Prestashop agregando soporte de calculo de costos de envio y generación de OTs.', 'chilexpress_oficial');

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

        $this->db = Db::getInstance(_PS_USE_SQL_SLAVE_);
        $this->id_lang_default = Configuration::get('PS_LANG_DEFAULT');
    }


    public function installTab(){
        $id_tab = (int)Tab::getIdFromClassName('Chilexpress');
        if (!$id_tab) {
            $tab = new Tab();
            $tab->active = 1;
            $tab->class_name = 'Chilexpress';
            $tab->name = array();
            foreach (Language::getLanguages(true) as $lang) {
                $tab->name[$lang['id_lang']] = 'Chilexpress Oficial';
            }
            $tab->id_parent = (int) Tab::getIdFromClassName('AdminParentModulesSf');
            $tab->module = $this->name;
            $tab->visible = false;
            return $tab->add();
        } else {
            return true;
        }
    }

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

    public function install()
    {
        if (Shop::isFeatureActive()) {
            Shop::setContext(Shop::CONTEXT_ALL);
        }
        if (!parent::install()) {
            return false;
        }
        // Execute module install SQL statements
        $sql_file = dirname(__FILE__).'/install/install.sql';
        if (!$this->loadSQLFile($sql_file)) {
            return false;
        }

        $coberturas = $this->preloadRegionsCommunes();

        return
            $this->checkAndAddChileanStatesOnInstall() &&
            $this->installTab() &&
            $this->installCarriers() && 
            $this->changeFormatAddress() &&
            $this->registerHook('actionAdminControllerSetMedia') &&
            $this->registerHook('displayBackOfficeHeader') &&
            $this->registerHook('displayBackOfficeTop') &&
            $this->registerHook('displayHeader') &&
            $this->registerHook('updateCarrier') &&
            $this->registerHook('actionAdminCustomersListingFieldsModifier') &&
            $this->registerHook('actionAdminOrdersListingFieldsModifier') &&
            $this->registerHook('actionOrderGridDefinitionModifier') &&
            $this->registerHook('actionOrderGridDataModifier') &&
            $this->registerHook('actionOrderGridQueryBuilderModifier') &&
            $this->registerHook('displayCarrierExtraContent') &&
            $this->registerHook('displayAdminOrderContentShip') &&  
            Configuration::updateValue('chilexpress_oficial_url', 'wlsdMpnDBn8') && 
            Configuration::updateValue(CXP_API_KEY_GEOREFERENCIA_VALUE, 'a6979b4160c6465f85776f43b6c40ffb') &&
            Configuration::updateValue(CXP_API_KEY_GEOREFERENCIA_ENABLED, true) &&
            Configuration::updateValue(CXP_AMBIENTE, 'staging') &&
            Configuration::updateValue(CXP_API_KEY_GENERACION_OT_VALUE, '5a77a19b76a24297ba01c158286641b7') && 
            Configuration::updateValue(CXP_API_KEY_COTIZADOR_VALUE, 'f25fbe75153b4f8e908e11fb5c958a1d') && 
            Configuration::updateValue(CXP_API_KEY_GENERACION_OT_ENABLED, true) && 
            Configuration::updateValue(CXP_API_KEY_COTIZADOR_ENABLED, true) && 
            Configuration::updateValue(CXP_REGION_ORIGEN, 'RM') &&
            Configuration::updateValue(CXP_ARTICULOS_TIENDA, '5') &&
            Configuration::updateValue(CXP_COMUNA_ORIGEN, 'STGO') && 
            Configuration::updateValue(CXP_NUMERO_TCC_ORIGEN, '18578680') && 
            Configuration::updateValue(CXP_RUT_MARKETPLACE_REMITENTE, '96756430') && 
            Configuration::updateValue(CXP_REGION_DEVOLUCION, 'RM') && 
            Configuration::updateValue(CXP_COMUNA_DEVOLUCION, 'STGO') && 
            Configuration::updateValue(CXP_REGIONES_HABILITADAS, $coberturas['regiones_habilitadas']) && 
            Configuration::updateValue(CXP_COMUNAS_HABILITADAS, $coberturas['comunas_habilitadas']) && 
            Configuration::updateValue(CXP_PRIORIDAD_SERVICIOS, 2) && 
            Configuration::updateValue(CXP_DIAS_PREPARACION_PEDIDOS, '0') && 
            Configuration::updateValue(CXP_PRODUCT_DEFAULT_WIDTH, '1') && 
            Configuration::updateValue(CXP_PRODUCT_DEFAULT_HEIGHT, '1') && 
            Configuration::updateValue(CXP_PRODUCT_DEFAULT_DEPTH, '1') && 
            Configuration::updateValue(CXP_PRODUCT_DEFAULT_WEIGHT, '1') && 
            Configuration::updateValue(CXP_PORCENTAJE_DESCUENTO, '0') && 
            Configuration::updateValue(CXP_CORTE_HORARIO, '12') &&
            Configuration::updateValue(CXP_DIAS_SEMANA_AMPM, json_encode( array(1,2,3,4,5) ) );
    }

    public function hookActionAdminControllerSetMedia()
    {
        if (!Module::isEnabled($this->name)) {
            return;
        }   
        
        // Necesitamos activar que modulos en especifico contendran nuestro js
        $controller = Dispatcher::getInstance()->getController();
        if ($controller == CXP_ADMINMODULES || $controller == 'AdminOrders' || $controller == 'adminaddresses') {
            if (method_exists($this->context->controller, 'addJquery')) {
                $this->context->controller->addJquery();
            }
            $this->context->controller->addJs($this->_path.'views/js/'.$this->name.'.js');
        }
    }

    public function uninstall() // NOSONAR
    {
        if (!parent::uninstall())
        {
            return false;
        }

        // Execute module install SQL statements
        $sql_file = dirname(__FILE__).'/install/uninstall.sql';
        if (!$this->loadSQLFile($sql_file))
        {
            return false;
        }

        if (!$this->uninstallTab())
        {
            return false;
        }
        
        return $this->uninstallCarriers();
    }

    public function postProcess()
    {
        
        return parent::postProcess();
    }

    public function displayForm() // NOSONAR
    { 
        $this->checkAndAddChileanStatesOnInstall();
        $articulos_query = array();
        $regiones_query = array();
        $comunas_origen_query = array();
        $comunas_devolucion_query = array();
        $regiones = $this->api->obtener_regiones();
        foreach($regiones as $region_id => $region_nombre) {
            $regiones_query[] = array('id' => $region_id, 'name' => $region_nombre);
        }
        $articulos = $this->api->obtener_categorias_articulos();
        foreach($articulos as $art_id => $art_nombre) {
            $articulos_query[] = array('id' => $art_id, 'name' => $art_nombre);
        }
        $ro = Configuration::get(CXP_REGION_ORIGEN);
        $rd = Configuration::get(CXP_REGION_DEVOLUCION);

        $comunas_origen = $this->api->obtener_comunas_desde_region(isset($ro)?$ro:'R1');
        $comunas_devolucion = $this->api->obtener_comunas_desde_region(isset($rd)?$rd:'R1');
        
        foreach($comunas_origen as $comuna_id => $comuna_nombre) {
            $comunas_origen_query[] = array('id' => $comuna_id, 'name' => $comuna_nombre);
        }
        foreach($comunas_devolucion as $comuna_id => $comuna_nombre) {
            $comunas_devolucion_query[] = array('id' => $comuna_id, 'name' => $comuna_nombre);
        }

        $strHtml = $this->regionComunasHabilitadasRender($regiones);

        $fields_form = array(
            array(
                'form' => array(
                    CXP_ID_FORM => 'modules_chilexpress',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Habilitación de Módulos')
                    ),
                    CXP_INPUT => array(
                        array(
                            'type' => CXP_SWITCH,
                            CXP_LABEL => $this->trans(
                                'Habilitar módulo de Georeferencia',
                                [],
                                CXP_MODULES_CONTACTFORM_ADMIN
                            ),
                            'desc' => $this->trans(
                                "Necesitas este módulo para poder obtener información actualizada de Regiones y Comunas, crea tu API KEY en https://developers.wschilexpress.com/product#product=georeference",
                                [],
                                CXP_MODULES_CONTACTFORM_ADMIN
                            ),
                            'name' => CXP_API_KEY_GEOREFERENCIA_ENABLED,
                            CXP_IS_BOOL => true,
                            CXP_REQUIRED => true,
                            CXP_VALUES => array(
                                array(
                                    'id' => CXP_API_KEY_GEOREFERENCIA_ENABLED . '_on',
                                    CXP_VALUE => 1,
                                    CXP_LABEL => $this->trans(CXP_HABILITADO, [], CXP_ADMIN_GLOBAL)
                                ),
                                array(
                                    'id' => CXP_API_KEY_GEOREFERENCIA_ENABLED . '_off',
                                    CXP_VALUE => 0,
                                    CXP_LABEL => $this->trans(CXP_DESHABILITADO, [], CXP_ADMIN_GLOBAL)
                                )
                            )
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('API KEY Georeferencia', array(), CXP_MODULES_BANNER_ADMIN),
                            'desc' => $this->l('Puedes encontrar esta Api Key, bajo el producto Coberturas en tu página de perfil: https://developers.wschilexpress.com/developer'),
                            'name' => CXP_API_KEY_GEOREFERENCIA_VALUE,
                            'lang' => false,
                            'size' => 20,
                            CXP_REQUIRED => false
                        ),
                        array(
                            'type' => CXP_SWITCH,
                            CXP_LABEL => $this->trans(
                                'Habilitar módulo de generación de OT',
                                [],
                                CXP_MODULES_CONTACTFORM_ADMIN
                            ),
                            'desc' => $this->trans(
                                "Necesitas este módulo para poder obtener generar Ordenes de Transporte e Imprimir tus etiquetas, crea tu API KEY en https://developers.wschilexpress.com/product#product=transportorders",
                                [],
                                CXP_MODULES_CONTACTFORM_ADMIN
                            ),
                            'name' => CXP_API_KEY_GENERACION_OT_ENABLED,
                            CXP_IS_BOOL => true,
                            CXP_REQUIRED => true,
                            CXP_VALUES => array(
                                array(
                                    'id' => CXP_API_KEY_GENERACION_OT_ENABLED . '_on',
                                    CXP_VALUE => 1,
                                    CXP_LABEL => $this->trans(CXP_HABILITADO, [], CXP_ADMIN_GLOBAL)
                                ),
                                array(
                                    'id' => CXP_API_KEY_GENERACION_OT_ENABLED . '_off',
                                    CXP_VALUE => 0,
                                    CXP_LABEL => $this->trans(CXP_DESHABILITADO, [], CXP_ADMIN_GLOBAL)
                                )
                            )
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('API KEY Órdenes de transporte', array(), CXP_MODULES_BANNER_ADMIN),
                            'desc' => $this->l('Puedes encontrar esta Api Key, bajo el producto Envíos en tu página de perfil: https://developers.wschilexpress.com/developer'),
                            'name' => CXP_API_KEY_GENERACION_OT_VALUE,
                            'lang' => false,
                            'size' => 20,
                            CXP_REQUIRED => false
                        ),
                        array(
                            'type' => CXP_SWITCH,
                            CXP_LABEL => $this->trans(
                                'Habilitar módulo de cotización',
                                [],
                                CXP_MODULES_CONTACTFORM_ADMIN
                            ),
                            'desc' => $this->trans(
                                "Necesitas este módulo para poder obtener generar Ordenes de Transporte e Imprimir tus etiquetas, crea tu API KEY en https://developers.wschilexpress.com/product#product=rating",
                                [],
                                CXP_MODULES_CONTACTFORM_ADMIN
                            ),
                            'name' => CXP_API_KEY_COTIZADOR_ENABLED,
                            CXP_IS_BOOL => true,
                            CXP_REQUIRED => true,
                            CXP_VALUES => array(
                                array(
                                    'id' => CXP_API_KEY_COTIZADOR_ENABLED . '_on',
                                    CXP_VALUE => 1,
                                    CXP_LABEL => $this->trans(CXP_HABILITADO, [], CXP_ADMIN_GLOBAL)
                                ),
                                array(
                                    'id' => CXP_API_KEY_COTIZADOR_ENABLED . '_off',
                                    CXP_VALUE => 0,
                                    CXP_LABEL => $this->trans(CXP_DESHABILITADO, [], CXP_ADMIN_GLOBAL)
                                )
                            )
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('API KEY Módulo de Cotización', array(), CXP_MODULES_BANNER_ADMIN),
                            'desc' => $this->l('Puedes encontrar esta Api Key, bajo el producto Cotizador en tu página de perfil: https://developers.wschilexpress.com/developer'),
                            'name' => CXP_API_KEY_COTIZADOR_VALUE,
                            'lang' => false,
                            'size' => 20,
                            CXP_REQUIRED => false
                        ),
                        array(
                            CXP_LABEL => $this->trans('Ambiente', array(), 'Modules.Dashactivity.Admin'),
                            'desc' => $this->l('Elige el ambiente de Staging para hacer las pruebas con tu plugin, y el ambiente de production una vez estas seguro(a) que todo funciona correctamente.'),
                            'name' => CXP_AMBIENTE,
                            'type' => CXP_SELECT,
                            CXP_OPTIONS => array(
                                CXP_QUERY => array(
                                    array('id' => 'staging', 'name' => 'Staging'),
                                    array('id' => 'production', 'name' => 'Production'),
                                ),
                                'id' => 'id',
                                'name' => 'name',
                            ),
                        )
                           
                    ),
                    CXP_SUBMIT => array(
                        CXP_TITLE => $this->l(CXP_GUARDAR),
                        CXP_CLASS => CXP_BTN_BTN_DEFAULT_PULL_RIGHT
                    )
                )
            ),

            array(
                'form' => array(
                    CXP_ID_FORM => 'datos_tienda_chilexpress',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Datos de la tienda')
                    ),
                    CXP_INPUT => array(
                        array(
                            'type' => CXP_SELECT,
                            CXP_OPTIONS => array(
                                CXP_QUERY =>$articulos_query,
                                'id' => 'id',
                                'name' => 'name',
                            ),
                            CXP_LABEL => $this->trans('Descripción de articulos de la tienda', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_ARTICULOS_TIENDA,
                            'lang' => false,
                            CXP_REQUIRED => true
                        ),
                    ),
                    CXP_SUBMIT => array(
                        CXP_TITLE => $this->l(CXP_GUARDAR),
                        CXP_CLASS => CXP_BTN_BTN_DEFAULT_PULL_RIGHT
                    )
                )
            ),
            array(
                'form' => array(
                    CXP_ID_FORM => 'general_chilexpress',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Datos de Origen')
                    ),
                    CXP_INPUT => array(
                        array(
                            'type' => CXP_SELECT,
                            CXP_OPTIONS => array(
                                CXP_QUERY =>$regiones_query,
                                'id' => 'id',
                                'name' => 'name',
                            ),
                            CXP_LABEL => $this->trans('Región de Origen', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_REGION_ORIGEN,
                            'lang' => false,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => CXP_SELECT,
                            CXP_OPTIONS => array(
                                CXP_QUERY => $comunas_origen_query,
                                'id' => 'id',
                                'name' => 'name',
                            ),
                            CXP_LABEL => $this->trans('Código de comuna de origen', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_COMUNA_ORIGEN,
                            'lang' => false,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('Número TCC', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_NUMERO_TCC_ORIGEN,
                            'lang' => false,
                            'size' => 20,
                            CXP_REQUIRED => true
                        )
                    ),
                    CXP_SUBMIT => array(
                        CXP_TITLE => $this->l(CXP_GUARDAR),
                        CXP_CLASS => CXP_BTN_BTN_DEFAULT_PULL_RIGHT
                    )
                )
            ),
            array(
                'form' => array(
                    CXP_ID_FORM => 'general_chilexpress2',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Datos del Remitente')
                    ),
                    CXP_INPUT => array(
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('Nombre', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_NOMBRE_REMITENTE,
                            'lang' => false,
                            'size' => 20,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('Teléfono', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_TELEFONO_REMITENTE,
                            'lang' => false,
                            'size' => 6,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => 'text',
                            'prefix'=>'<i class="icon-envelope-o"></i>',
                            CXP_LABEL => $this->trans('E-mail', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_EMAIL_REMITENTE,
                            'lang' => false,
                            'size' => 20,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('RUT Seller', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_RUT_SELLER_REMITENTE,
                            'lang' => false,
                            'size' => 20,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('RUT Marketplace', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_RUT_MARKETPLACE_REMITENTE,
                            'lang' => false,
                            'size' => 20,
                            CXP_REQUIRED => true
                        )
                    ),
                    CXP_SUBMIT => array(
                        CXP_TITLE => $this->l(CXP_GUARDAR),
                        CXP_CLASS => CXP_BTN_BTN_DEFAULT_PULL_RIGHT
                    )
                )
            ),
            array(
                'form' => array(
                    CXP_ID_FORM => 'general_chilexpress3',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Dirección de Devolución')
                    ),
                    CXP_INPUT => array(
                        array(
                            'type' => CXP_SELECT,
                            CXP_OPTIONS => array(
                                CXP_QUERY => $regiones_query,
                                'id' => 'id',
                                'name' => 'name',
                            ),
                            CXP_LABEL => $this->trans('Región de Devolución', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_REGION_DEVOLUCION,
                            'lang' => false,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => CXP_SELECT,
                            CXP_OPTIONS => array(
                                CXP_QUERY => $comunas_devolucion_query,
                                'id' => 'id',
                                'name' => 'name',
                            ),
                            CXP_LABEL => $this->trans('Código Comuna', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_COMUNA_DEVOLUCION,
                            'lang' => false,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('Calle Devolución', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_CALLE_DEVOLUCION,
                            'lang' => false,
                            'size' => 20,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('Número de la Dirección', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_NUMERO_CALLE_DEVOLUCION,
                            'lang' => false,
                            'size' => 20,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('Complemento', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_COMPLEMENTO_DEVOLUCION,
                            'lang' => false,
                            'size' => 20,
                            CXP_REQUIRED => true
                        )
                    ),
                    CXP_SUBMIT => array(
                        CXP_TITLE => $this->l(CXP_GUARDAR),
                        CXP_CLASS => CXP_BTN_BTN_DEFAULT_PULL_RIGHT
                    )
                )
            ),
            array(
                'form' => array(
                    CXP_ID_FORM => 'general_chilexpress4',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Días adicionales para la preparación de los pedidos.')
                    ),
                    CXP_INPUT => array(
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('N° Días', array(), CXP_MODULES_BANNER_ADMIN),
                            'desc' => 'La cantidad de días ingresados en este parámetro se adicionará a la promesa de entrega de los métodos de envíos por Chilexpress.',
                            'name' => CXP_DIAS_PREPARACION_PEDIDOS,
                            'lang' => false,
                            'size' => 10,
                            CXP_REQUIRED => true
                        )
                    ),
                    CXP_SUBMIT => array(
                        CXP_TITLE => $this->l(CXP_GUARDAR),
                        CXP_CLASS => CXP_BTN_BTN_DEFAULT_PULL_RIGHT
                    )
                )
            ),
            array(
                'form' => array(
                    CXP_ID_FORM => 'general_chilexpress5',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Prioridad de los métodos de envío.')
                    ),
                    CXP_INPUT => array(
                        array(
                            CXP_LABEL =>  $this->trans('Tipo de prioridad de los métodos de envío.', array(), CXP_MODULES_BANNER_ADMIN),                               
                            'desc' => '
                                Los servicios Chilexpress que pertenecen al método "Entrega el mismo día" son: </br>
                                <b>AMPM</b> [ Hoy (hasta las 22:00 hrs) ] </br> </br>

                                Los servicios Chilexpress que pertenecen al método "Entrega desde el día siguiente" son: </br>
                                <b>PRIORITARIO</b> [1 día hábil] (hasta las 11:00 hrs) / <b>EXPRESS</b> [1 día hábil] (hasta las 19:00 hrs) / <b>EXTENDIDO</b> [1 a 2 días hábiles] / <b>EXTREMO</b> [2 a 3 días hábiles] </br> </br>

                                *Recuerda que la fecha de entrega de los servicios Chilexpress está sujeta a la fecha de admisión en sucursal o del retiro.
                                </br></br>

                                **Para operar con el método de entrega el mismo día (<b>AMPM</b>) solicita a tu ejecutivo la activación del servicio en tu TCC.
                            ',
                            'name' => CXP_PRIORIDAD_SERVICIOS,
                            'type' => CXP_SELECT,
                            CXP_OPTIONS => array(
                                'query' => array(
                                    array(
                                        'id_option' => 1,
                                        'name'      => 'Entrega el mismo día'
                                    ),
                                    array(
                                        'id_option' => 2,
                                        'name'      => 'Entrega desde el día siguiente'
                                    ),
                                    array(
                                        'id_option' => 0,
                                        'name'      => 'Ambos'
                                    ),
                                ),                          
                                'id'    => 'id_option',                           
                                'name'  => 'name'                               
                            )
                        )
                    ),
                    CXP_SUBMIT => array(
                        CXP_TITLE => $this->l(CXP_GUARDAR),
                        CXP_CLASS => CXP_BTN_BTN_DEFAULT_PULL_RIGHT
                    )
                )
            ),
            array(
                'form' => array(
                    CXP_ID_FORM => 'general_chilexpress6',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Habilitar Regiones y Comunas.')
                    ),
                    CXP_INPUT => array(
                        array(
                            'type'         => 'html',
                            'name'         => 'regiones-y-comunas',
                            'html_content' => $strHtml
                        )
                    ),
                    CXP_SUBMIT => array(
                        CXP_TITLE => $this->l(CXP_GUARDAR),
                        CXP_CLASS => CXP_BTN_BTN_DEFAULT_PULL_RIGHT
                    )
                )
            ),
            array(
                'form' => array(
                    CXP_ID_FORM => 'general_chilexpress7',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Pedidos Chilexpress.')
                    ),
                    CXP_INPUT => array(
                        array(
                            'type'         => 'html',
                            'name'         => 'pedidos-chilexpress',
                            'html_content' => $this->tablaPedidosRender()
                        )
                    ),
                )
            ),
            array(
                'form' => array(
                    CXP_ID_FORM => 'general_chilexpress8',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Dimensiones Producto.')
                    ),
                    CXP_INPUT => array(
                        array(
                            'type'         => 'html',
                            'name'         => 'productos-chilexpress',
                            'html_content' => $this->tablaProductosRender()
                        )
                    ),
                )
            ),
            array(
                'form' => array(
                    CXP_ID_FORM => 'general_chilexpress9',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Dimensiones y peso por defecto.')
                    ),
                    CXP_INPUT => array(
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('Ancho', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_PRODUCT_DEFAULT_WIDTH,
                            'lang' => false,
                            'size' => 5,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('Alto', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_PRODUCT_DEFAULT_HEIGHT,
                            'lang' => false,
                            'size' => 5,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('Largo', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_PRODUCT_DEFAULT_DEPTH,
                            'lang' => false,
                            'size' => 5,
                            CXP_REQUIRED => true
                        ),
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('Peso', array(), CXP_MODULES_BANNER_ADMIN),
                            'name' => CXP_PRODUCT_DEFAULT_WEIGHT,
                            'lang' => false,
                            'size' => 5,
                            CXP_REQUIRED => true
                        )
                    ),
                    CXP_SUBMIT => array(
                        CXP_TITLE => $this->l(CXP_GUARDAR),
                        CXP_CLASS => CXP_BTN_BTN_DEFAULT_PULL_RIGHT
                    )
                )
            ),
            array(
                'form' => array(
                    CXP_ID_FORM => 'general_chilexpress10',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Descuento a los métodos de envío Chilexpress (%).')
                    ),
                    CXP_INPUT => array(
                        array(
                            'type' => 'text',
                            CXP_LABEL => $this->trans('Descuento (%)', array(), CXP_MODULES_BANNER_ADMIN),
                            'desc' => '
                                Ofrece a tu comprador una rebaja a la tarifa de los métodos de envíos Chilexpress, mediante
                                un porcentaje de descuento, desde el 0% hasta el 100%. Donde cero refleja una tarifa sin
                                descuento y cien representa un envío gratuito.
                                <br/><br/>
                                *Recuerda que la tarifa con descuento configurada en tu tienda, no representará el cobro
                                del servicio Chilexpress en el proceso de facturación. Nuestro proceso solo reconoce
                                descuentos establecidos mediantes acuerdos comerciales.
                            ',
                            'name' => CXP_PORCENTAJE_DESCUENTO,
                            'id'   => 'input_porcentaje_descuento',
                            'lang' => false,
                            'size' => 3,
                            CXP_REQUIRED => true
                        )
                    ),
                    CXP_SUBMIT => array(
                        CXP_TITLE => $this->l(CXP_GUARDAR),
                        CXP_CLASS => CXP_BTN_BTN_DEFAULT_PULL_RIGHT
                    )
                )
            ),
            array(
                'form' => array(
                    CXP_ID_FORM => 'general_chilexpress11',
                    CXP_LEGEND => array(
                        CXP_TITLE => $this->l('Opciones método entrega el mismo día.')
                    ),
                    'description' => '
                        Los servicios Chilexpress que pertenecen al método "Entrega el mismo día" son:
                        <b>AMPM</b> [ Hoy (hasta las 22:00 hrs) ] <br><br>

                        Para operar con el método de entrega el mismo día (AMPM) solicita a tu ejecutivo la
                        activación del servicio en tu TCC. <br><br>

                        Recuerda que la admisión de este tipo de envíos en sucursales Chilexpress es hasta las
                        13:00 horas, de Lunes a Viernes. Y no pueden ser admitidos en puntos Pick Up y
                        Agentes Autorizados.
                    ',
                    CXP_INPUT => array(
                        array(
                            CXP_LABEL => $this->trans('Corte horario (hrs)', array(), CXP_MODULES_BANNER_ADMIN),
                            'desc' => '
                                La hora seleccionada permitirá restringir la visualización del servicio AMPM en el carro de compra.
                            ',
                            'type' => CXP_SELECT,
                            'name' => 'corte-horario',
                            CXP_OPTIONS => array(
                                'query' => array(
                                    array(
                                        'id_option' => 10,
                                        'name'      => 'Hasta 10:00 horas'
                                    ),
                                    array(
                                        'id_option' => 11,
                                        'name'      => 'Hasta 11:00 horas'
                                    ),
                                    array(
                                        'id_option' => 12,
                                        'name'      => 'Hasta 12:00 horas'
                                    ),
                                ),                          
                                'id'    => 'id_option',                           
                                'name'  => 'name'                               
                            ),
                            'name' => CXP_CORTE_HORARIO,
                            'id'   => 'input_corte_horario',
                            CXP_REQUIRED => true
                        ),
                        array(
                            CXP_LABEL => $this->trans('Días de la semana', array(), CXP_MODULES_BANNER_ADMIN),
                            'desc' => '
                                Selecciona los días de la semana que quieras ofrecer servicio AMPM en el carro de compra.
                            ',
                            'type'         => 'html',
                            'name'         => 'dias-semana',
                            'html_content' => $this->diasSemanaAMPM(),
                            CXP_REQUIRED => true
                        )
                    ),
                    CXP_SUBMIT => array(
                        CXP_TITLE => $this->l(CXP_GUARDAR),
                        CXP_CLASS => CXP_BTN_BTN_DEFAULT_PULL_RIGHT
                    )
                )
            )
        );

        // < load helperForm >
        $helper = new HelperForm();

        // < module, token and currentIndex >
        $helper->module = $this;
        $helper->name_controller = $this->name;
        $helper->token = Tools::getAdminTokenLite(CXP_ADMINMODULES);
        // $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false, [], ['configure' => $this->name]);

        // < title and toolbar >
        $helper->title = $this->displayName;
        $helper->show_toolbar = false;        // false -> remove toolbar
        $helper->toolbar_scroll = false;      // yes - > Toolbar is always visible on the top of the screen.
        $helper->submit_action = CXP_SUBMIT.$this->name;
        $helper->toolbar_btn = array(
            'save' =>
                array(
                    'desc' => $this->l('Save'),
                    'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
                        '&token='.Tools::getAdminTokenLite(CXP_ADMINMODULES),
                ),
            'back' => array(
                'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite(CXP_ADMINMODULES),
                'desc' => $this->l('Back to list')
            )
        );

        // < load current value >
        $helper->fields_value[CXP_API_KEY_GEOREFERENCIA_VALUE] = Configuration::get(CXP_API_KEY_GEOREFERENCIA_VALUE);
        $helper->fields_value[CXP_API_KEY_GENERACION_OT_VALUE] = Configuration::get(CXP_API_KEY_GENERACION_OT_VALUE);
        $helper->fields_value[CXP_API_KEY_COTIZADOR_VALUE] = Configuration::get(CXP_API_KEY_COTIZADOR_VALUE);
        
        $helper->fields_value[CXP_API_KEY_GEOREFERENCIA_ENABLED] = Configuration::get(CXP_API_KEY_GEOREFERENCIA_ENABLED);
        $helper->fields_value[CXP_API_KEY_GENERACION_OT_ENABLED] = Configuration::get(CXP_API_KEY_GENERACION_OT_ENABLED);
        $helper->fields_value[CXP_API_KEY_COTIZADOR_ENABLED] = Configuration::get(CXP_API_KEY_COTIZADOR_ENABLED);
        $helper->fields_value[CXP_AMBIENTE] = Configuration::get(CXP_AMBIENTE);

        $helper->fields_value[CXP_ARTICULOS_TIENDA] = Configuration::get(CXP_ARTICULOS_TIENDA);

        $helper->fields_value[CXP_REGION_ORIGEN] = Configuration::get(CXP_REGION_ORIGEN);
        $helper->fields_value[CXP_COMUNA_ORIGEN] = Configuration::get(CXP_COMUNA_ORIGEN);
        $helper->fields_value[CXP_NUMERO_TCC_ORIGEN] = Configuration::get(CXP_NUMERO_TCC_ORIGEN);

        $helper->fields_value[CXP_NOMBRE_REMITENTE] = Configuration::get(CXP_NOMBRE_REMITENTE);
        $helper->fields_value[CXP_TELEFONO_REMITENTE] = Configuration::get(CXP_TELEFONO_REMITENTE);
        $helper->fields_value[CXP_EMAIL_REMITENTE] = Configuration::get(CXP_EMAIL_REMITENTE);
        $helper->fields_value[CXP_RUT_SELLER_REMITENTE] = Configuration::get(CXP_RUT_SELLER_REMITENTE);
        $helper->fields_value[CXP_RUT_MARKETPLACE_REMITENTE] = Configuration::get(CXP_RUT_MARKETPLACE_REMITENTE);

        $helper->fields_value[CXP_REGION_DEVOLUCION] = Configuration::get(CXP_REGION_DEVOLUCION);
        $helper->fields_value[CXP_COMUNA_DEVOLUCION] = Configuration::get(CXP_COMUNA_DEVOLUCION);
        $helper->fields_value[CXP_CALLE_DEVOLUCION] = Configuration::get(CXP_CALLE_DEVOLUCION);
        $helper->fields_value[CXP_NUMERO_CALLE_DEVOLUCION] = Configuration::get(CXP_NUMERO_CALLE_DEVOLUCION);
        $helper->fields_value[CXP_COMPLEMENTO_DEVOLUCION] = Configuration::get(CXP_COMPLEMENTO_DEVOLUCION);

        $helper->fields_value[CXP_DIAS_PREPARACION_PEDIDOS] = ( Configuration::get(CXP_DIAS_PREPARACION_PEDIDOS) ) ? Configuration::get(CXP_DIAS_PREPARACION_PEDIDOS) : '0';

        $helper->fields_value[CXP_PRIORIDAD_SERVICIOS] = Configuration::get(CXP_PRIORIDAD_SERVICIOS);

        $helper->fields_value[CXP_PRODUCT_DEFAULT_WIDTH] = ( Configuration::get(CXP_PRODUCT_DEFAULT_WIDTH) ) ? Configuration::get(CXP_PRODUCT_DEFAULT_WIDTH) : '1';
        $helper->fields_value[CXP_PRODUCT_DEFAULT_HEIGHT] = ( Configuration::get(CXP_PRODUCT_DEFAULT_HEIGHT) ) ? Configuration::get(CXP_PRODUCT_DEFAULT_HEIGHT) : '1';
        $helper->fields_value[CXP_PRODUCT_DEFAULT_DEPTH] = ( Configuration::get(CXP_PRODUCT_DEFAULT_DEPTH) ) ? Configuration::get(CXP_PRODUCT_DEFAULT_DEPTH) : '1';
        $helper->fields_value[CXP_PRODUCT_DEFAULT_WEIGHT] = ( Configuration::get(CXP_PRODUCT_DEFAULT_WEIGHT) ) ? Configuration::get(CXP_PRODUCT_DEFAULT_WEIGHT) : '1';

        $helper->fields_value[CXP_PORCENTAJE_DESCUENTO] = ( Configuration::get(CXP_PORCENTAJE_DESCUENTO) ) ? Configuration::get(CXP_PORCENTAJE_DESCUENTO) : '0';

        $helper->fields_value[CXP_CORTE_HORARIO] = ( Configuration::get(CXP_CORTE_HORARIO) ) ? Configuration::get(CXP_CORTE_HORARIO) : '12';

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

    private function tablaPedidosRender()
    {
        global $cookie;
        
        $request = 'SELECT 

                        o.id_order AS id_pedido, o.date_add AS fecha_pedido, " " AS ot, " " AS certificado, 
                        CONCAT(c.name, " - ", cl.delay) AS servicio, o.total_shipping AS costo_servicio,
                        CONCAT(cu.firstname, " ", cu.lastname) AS cliente

                    FROM `' . _DB_PREFIX_ . 'orders` AS o
                    INNER JOIN `' . _DB_PREFIX_ . 'carrier` AS c ON o.id_carrier = c.id_carrier
                    INNER JOIN `' . _DB_PREFIX_ . 'carrier_lang` AS cl ON c.id_carrier = cl.id_carrier
                    INNER JOIN `' . _DB_PREFIX_ . 'customer` AS cu ON o.id_customer = cu.id_customer
                    WHERE c.external_module_name = "chilexpress_oficial"
                    AND cl.id_lang = "'.$this->id_lang_default.'"
                    -- AND o.current_state = 2
                    ORDER BY o.id_order DESC';

        $result = $this->db->executeS($request);

        $strHtml = '
                    <input type="hidden" id="urlCxpOrderController" name="urlCxpOrderController" value="'.$this->context->link->getAdminLink('ChilexpressOrder').'" />
                    <table id="tablaPedidosCxp" class="display" style="width:100%">
                        <thead>
                            <tr>
                                <!--<th><input type="checkbox" /></th>-->
                                <th>N° Pedido</th>
                                <th>Destinatario</th>
                                <th>Fecha Pedido</th>
                                <th>Orden Transporte</th>
                                <th>N° Certificado</th>
                                <th>Servicio</th>
                                <th>Costo Envio</th>
                                <th>Etiqueta</th>
                            </tr>
                        </thead>
                        <tbody>';

                        foreach ($result as $key => $value)
                        {
                            $fecha = new DateTime($value["fecha_pedido"]);
                            $pedido = '#'.$value["id_pedido"];
                            $actions = $this->orderStatusActionsButton($value["id_pedido"]);
                            
                            $transportOrderNumber = '';
                            $id_order_carrier = (int) Db::getInstance()->getValue('
                                    SELECT `id_order_carrier`
                                    FROM `'._DB_PREFIX_.'order_carrier`
                                    WHERE `id_order` = '.(int)$value["id_pedido"]
                            );
                            if ($id_order_carrier) {
                                $order_carrier = new OrderCarrier((int) $id_order_carrier);
                                if (isset($order_carrier->tracking_number)) {
                                    $transportOrderNumber = $order_carrier->tracking_number;
                                }
                            }

                            $cxpOrderMeta = $this->getChilexpressOrdermeta( $value["id_pedido"] );
                            $certificateNumber = '';
                            if (isset($cxpOrderMeta) && count($cxpOrderMeta) > 0) {
                                $certificateNumber = $cxpOrderMeta[0]['certificateNumber'];
                            }

                            $numbers = explode(",", $transportOrderNumber);
                            $out = array();
                            foreach ($numbers as $number)
                            {
                                $out[] = '<a href="javascript:;" data-tracking-code="'.$number.'" data-orderid="'.$value["id_pedido"].'">'.$number.'</a>';
                            }

                            $version_parts = explode('.', _PS_VERSION_);
                            if (count($version_parts) >= 3 && $version_parts[0] >= 1 && $version_parts[1] >= 7 && $version_parts[2] >= 7) {
                                // newer than 1.7.7
                                $link = new Link();
                                $linkOrder = ($link->getAdminLink('AdminOrders', true, [], ['id_order' => (int) $value["id_pedido"], 'vieworder' => 1]));
                            } else {
                                // older than 1.7.7
                                $linkOrder = ($this->context->link->getAdminLink('AdminOrders', true, [], ['id_order' => (int) $value["id_pedido"], 'vieworder' => 1]) . '&amp;id_order='.(int) $value["id_pedido"].'&amp;vieworder');
                                        
                            }

                            if($transportOrderNumber != '')
                            {
                                $currencyCode = 'CLP';
                                if (isset($this->iso_code)) {
                                    $currencyCode = $this->iso_code;
                                }
                                $strHtml = $strHtml.'
                                <tr>
                                    <!--<th><input type="checkbox" class="pedidos" name="pedidos[]" value="'.$value["id_pedido"].'" /></th>-->
                                    <td><a href="'.$linkOrder.'">'.$pedido.'</a></td>
                                    <td>'.$value["cliente"].'</td>
                                    <td>'.$fecha->format('d-m-Y').'</td>
                                    <td>'.implode('<br />', $out).'</td>
                                    <td><a href="#" class="numero-ce" data-id_order="'.$value["id_pedido"].'" data-numero_ce="'.$certificateNumber.'">'.$certificateNumber.'</a></td>
                                    <td>'.$value["servicio"].'</td>
                                    <td>'.Context::getContext()->currentLocale->formatPrice($value["costo_servicio"], $currencyCode).'</td>
                                    <td>'.$actions.'</td>
                                </tr>
                                ';
                            }
                        }
                            

        $strHtml = $strHtml. '</tbody> </table>';

        return $strHtml;
    }

    private function tablaProductosRender()
    {
        $request = 'SELECT 

                        p.id_product, pl.name, p.height, p.width, p.depth, p.weight

                    FROM `' . _DB_PREFIX_ . 'product` AS p
                    INNER JOIN `' . _DB_PREFIX_ . 'product_lang` AS pl ON p.id_product = pl.id_product
                    WHERE pl.id_lang = "'.$this->id_lang_default.'"';

        $result = $this->db->executeS($request);

        $strHtml = '<table id="tablaProductosCxp" class="display" style="width:100%">
                        <thead>
                            <tr>
                                <th></th>
                                <th>Nombre Producto</th>
                                <th>Ancho</th>
                                <th>Alto</th>
                                <th>Largo</th>
                                <th>Peso</th>
                                <th>Entrega en el mismo día</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>';

                        foreach ($result as $key => $value)
                        {
                            $product = new Product((int)$value['id_product'], false, $this->id_lang_default);
                            $img = $product->getCover($product->id);
                            $link = new Link();
                            $url = Context::getContext()->link->getAdminLink('AdminProducts', true, ['id_product' => $product->id]);
                            $img_url = $link->getImageLink(isset($product->link_rewrite) ? $product->link_rewrite : $product->name, (int)$img['id_image']);

                            $ancho = ( floatval($value['width']) ) ? $value['width'] : Configuration::get(CXP_PRODUCT_DEFAULT_WIDTH);
                            $alto = ( floatval($value['height']) ) ? $value['height'] : Configuration::get(CXP_PRODUCT_DEFAULT_HEIGHT);
                            $largo = ( floatval($value['depth']) ) ? $value['depth'] : Configuration::get(CXP_PRODUCT_DEFAULT_DEPTH);
                            $peso = ( floatval($value['weight']) ) ? $value['weight'] : Configuration::get(CXP_PRODUCT_DEFAULT_WEIGHT);

                            $_servicio_ampm = (bool) $this->getChilexpressProductmeta( $product->id, '_service_ampm' );
                            $_enabled_ampm = ( $_servicio_ampm != '' ) ? 'checked' : '';

                            $strHtml = $strHtml.'
                            <tr>
                                <th><img src="http://'.$img_url.'" width="50" height="50" /></th>
                                <td><a href="'.$url.'">'.$value['name'].'</a></td>
                                <td><input type="number" style="width: 80px;" step="any" min="0.1" id="input_ancho_'.$value['id_product'].'" value="'.number_format($ancho, 2).'" /></td>
                                <td><input type="number" style="width: 80px;" step="any" min="0.1" id="input_alto_'.$value['id_product'].'" value="'.number_format($alto, 2).'" /></td>
                                <td><input type="number" style="width: 80px;" step="any" min="0.1" id="input_largo_'.$value['id_product'].'" value="'.number_format($largo, 2).'" /></td>
                                <td><input type="number" style="width: 80px;" step="any" min="0.1" id="input_peso_'.$value['id_product'].'" value="'.number_format($peso, 2).'" /></td>
                                <td style="text-align: center;"><input type="checkbox" id="input_servicio_ampm_'.$value['id_product'].'" value="true" '.$_enabled_ampm.' /></td>
                                <td><button type="button" class="btn-asignar-dimension" data-product_id="'.$value['id_product'].'" >Asignar</button></td>
                            </tr>
                            ';
                        }
                            

        $strHtml = $strHtml. '</tbody> </table>';

        return $strHtml;
    }

    public function diasSemanaAMPM(){

        $dias_semana_ampm = json_decode(Configuration::get(CXP_DIAS_SEMANA_AMPM), true);

        $lunes = ( in_array(1, $dias_semana_ampm) ) ? 'checked' : '';
        $martes = ( in_array(2, $dias_semana_ampm) ) ? 'checked' : '';
        $miercoles = ( in_array(3, $dias_semana_ampm) ) ? 'checked' : '';
        $jueves = ( in_array(4, $dias_semana_ampm) ) ? 'checked' : '';
        $viernes = ( in_array(5, $dias_semana_ampm) ) ? 'checked' : '';

        $strHtml = '
            <ul class="dias-semana-ampm">
                <li><input type="checkbox" name="'.CXP_DIAS_SEMANA_AMPM.'[]" value="1" '.$lunes.' /> Lunes</li>
                <li><input type="checkbox" name="'.CXP_DIAS_SEMANA_AMPM.'[]" value="2" '.$martes.' /> Martes</li>
                <li><input type="checkbox" name="'.CXP_DIAS_SEMANA_AMPM.'[]" value="3" '.$miercoles.' /> Miércoles</li>
                <li><input type="checkbox" name="'.CXP_DIAS_SEMANA_AMPM.'[]" value="4" '.$jueves.' /> Jueves</li>
                <li><input type="checkbox" name="'.CXP_DIAS_SEMANA_AMPM.'[]" value="5" '.$viernes.' /> Viernes</li>
            </ul>
        ';

        return $strHtml;
    }

    public function regionComunasHabilitadasRender( $regiones ){
        $regiones_habilitadas = json_decode(Configuration::get(CXP_REGIONES_HABILITADAS), true);
        $comunas_habilitadas = json_decode(Configuration::get(CXP_COMUNAS_HABILITADAS), true);
    
        $strHtml = '';

        $strHtml = $strHtml . '<div class="container-regiones-comunas">';
        $strHtml = $strHtml . '<ul>';
        $strHtml = $strHtml . '<li class="check-todo"><input type="checkbox" id="check_todo" /> TODO </li>';

        foreach ($regiones as $region_id => $region) 
        {
            $marcadoR = 'checked';
            if ( Configuration::hasKey(CXP_REGIONES_HABILITADAS) && !in_array($region_id, $regiones_habilitadas) )
            {
                $marcadoR = '';
            }

            $strHtml = $strHtml . '<li><input type="checkbox" class="checkboxes check-region" id="'.$region_id.'" name="'.CXP_REGIONES_HABILITADAS.'[]" value="'.$region_id.'" '.$marcadoR.' /> <span class="nombre-region" id="'.$region_id.'">'.$region.'</span></li>';
            $strHtml = $strHtml . '<ul class="ul-comunas hijo-'.$region_id.'" style="display:none;">';

            $comunas = $this->api->obtener_comunas_desde_region($region_id);

            foreach ($comunas as $comuna_id => $comuna) 
            {
                $marcadoC = 'checked';
                if ( Configuration::hasKey(CXP_COMUNAS_HABILITADAS) && !in_array($comuna_id, $comunas_habilitadas) )
                {
                    $marcadoC = '';    
                }
                
                $strHtml = $strHtml . '<li><input type="checkbox" class="checkboxes check-comuna check-comuna-'.$region_id.'" data-region_padre="'.$region_id.'" name="'.CXP_COMUNAS_HABILITADAS.'[]" value="'.$comuna_id.'" '.$marcadoC.' /> '.$comuna.' </li>';
            }

            $strHtml = $strHtml . '</ul>';
        }

        $strHtml = $strHtml . '</ul>';
        $strHtml = $strHtml . '</div>';
        
        return $strHtml;
    }

    public function getChilexpressOrdermeta( $id_order ){
        $request = 'SELECT * FROM `' . _DB_PREFIX_ . 'chilexpress_oficial_ordermeta` WHERE id_order = "'.$id_order.'"';
        $result = $this->db->executeS($request);
        return $result;
    }

    public function getChilexpressProductmeta( $id_product, $metaKey = '' ){
        
        $request = 'SELECT meta_key, meta_value FROM `' . _DB_PREFIX_ . 'chilexpress_oficial_productmeta` WHERE id_product = "'.$id_product.'"';
        
        if($metaKey != '')
            $request = $request.' AND meta_key = "'.$metaKey.'"';

        $result = $this->db->executeS($request);

        $rows = array();
        foreach ($result as $key => $value) {
            $rows[] = array(
                $value["meta_key"] => $value["meta_value"]
            );
        }

        $_meta_value = '';
        foreach ($rows as $key => $row) {
            if(array_key_exists($metaKey, $row) && $row[$metaKey] != '')
                $_meta_value = $row[$metaKey];
        }
        return $_meta_value;
    }

    public function orderStatusActionsButton( $id_order ) {

        $actions = array();

        $result = $this->getChilexpressOrdermeta( $id_order );

        if(!$result || count($result) == 0){
            $actions = CXP_A_HREF.$this->context->link->getAdminLink(CXP_CHILEXPRESS_ORDER).CXP_ORDER_ID_EQ.$id_order.'&action=generar_ot" data-confirm-message="" data-toggle="pstooltip" data-placement="top" data-original-title="Generar OT" class="btn tooltip-link js-link-row-action dropdown-item inline-dropdown-item"><i class="material-icons">settings</i></a>';
        }

        if($result && count($result) > 0) {
            $actions = CXP_A_HREF.$this->context->link->getAdminLink(CXP_CHILEXPRESS_ORDER).CXP_ORDER_ID_EQ.$id_order.'&action=ver_ot"  data-confirm-message="" data-toggle="pstooltip" data-placement="top" data-original-title="Imprimir OT" class="btn tooltip-link js-link-row-action dropdown-item inline-dropdown-item"><i class="material-icons">print</i></a>';
        }

        return $actions;
    }



    public function getContent() // NOSONAR
    {
        $output = null;

        // < here we check if the form is submited for this module >
        if (Tools::isSubmit(CXP_SUBMIT.$this->name)) {
            $chilexpress_url = strval(Tools::getValue('chilexpress_oficial_url'));

            $api_key_georeferencia_value = strval(Tools::getValue(CXP_API_KEY_GEOREFERENCIA_VALUE));
            $api_key_generacion_ot_value = strval(Tools::getValue(CXP_API_KEY_GENERACION_OT_VALUE));
            $api_key_cotizador_value = strval(Tools::getValue(CXP_API_KEY_COTIZADOR_VALUE));

            $api_key_georeferencia_enabled = boolval(Tools::getValue(CXP_API_KEY_GEOREFERENCIA_ENABLED));
            $api_key_generacion_ot_enabled = boolval(Tools::getValue(CXP_API_KEY_GENERACION_OT_ENABLED));
            $api_key_cotizador_enabled = boolval(Tools::getValue(CXP_API_KEY_COTIZADOR_ENABLED));

            $ambiente = strval(Tools::getValue(CXP_AMBIENTE));

            $articulos_tienda = strval(Tools::getValue(CXP_ARTICULOS_TIENDA));

            $region_origen = strval(Tools::getValue(CXP_REGION_ORIGEN));
            $comuna_origen = strval(Tools::getValue(CXP_COMUNA_ORIGEN));
            $numero_tcc_origen = strval(Tools::getValue(CXP_NUMERO_TCC_ORIGEN));

            $nombre_remitente = strval(Tools::getValue(CXP_NOMBRE_REMITENTE));
            $telefono_remitente = strval(Tools::getValue(CXP_TELEFONO_REMITENTE));
            $email_remitente = strval(Tools::getValue(CXP_EMAIL_REMITENTE));
            $rut_seller_remitente = strval(Tools::getValue(CXP_RUT_SELLER_REMITENTE));
            $rut_marketplace_remitente = strval(Tools::getValue(CXP_RUT_MARKETPLACE_REMITENTE));

            $region_devolucion = strval(Tools::getValue(CXP_REGION_DEVOLUCION));
            $comuna_devolucion = strval(Tools::getValue(CXP_COMUNA_DEVOLUCION));
            $calle_devolucion = strval(Tools::getValue(CXP_CALLE_DEVOLUCION));
            $numero_calle_devolucion = strval(Tools::getValue(CXP_NUMERO_CALLE_DEVOLUCION));
            $complemento_devolucion = strval(Tools::getValue(CXP_COMPLEMENTO_DEVOLUCION));

            $dias_preparacion_pedidos = strval(Tools::getValue(CXP_DIAS_PREPARACION_PEDIDOS));

            $regiones_habilitadas = json_encode(Tools::getValue(CXP_REGIONES_HABILITADAS) );
            $comunas_habilitadas = json_encode(Tools::getValue(CXP_COMUNAS_HABILITADAS) );

            $prioridad_servicios = strval(Tools::getValue(CXP_PRIORIDAD_SERVICIOS));

            $ancho_defecto_producto = strval(Tools::getValue(CXP_PRODUCT_DEFAULT_WIDTH));
            $alto_defecto_producto = strval(Tools::getValue(CXP_PRODUCT_DEFAULT_HEIGHT));
            $largo_defecto_producto = strval(Tools::getValue(CXP_PRODUCT_DEFAULT_DEPTH));
            $peso_defecto_producto = strval(Tools::getValue(CXP_PRODUCT_DEFAULT_WEIGHT));

            $porcentaje_descuento = strval(Tools::getValue(CXP_PORCENTAJE_DESCUENTO));

            $corte_horario = strval(Tools::getValue(CXP_CORTE_HORARIO));
            $dias_semana_ampm = json_encode(Tools::getValue(CXP_DIAS_SEMANA_AMPM));

            if (isset($api_key_georeferencia_value)) {
                Configuration::updateValue(CXP_API_KEY_GEOREFERENCIA_VALUE, $api_key_georeferencia_value);
            }
            if (isset($api_key_generacion_ot_value)) {
                Configuration::updateValue(CXP_API_KEY_GENERACION_OT_VALUE, $api_key_generacion_ot_value);
            }
            if (isset($api_key_cotizador_value)) {
                Configuration::updateValue(CXP_API_KEY_COTIZADOR_VALUE, $api_key_cotizador_value);
            }

            if (isset($api_key_georeferencia_enabled)) {
                Configuration::updateValue(CXP_API_KEY_GEOREFERENCIA_ENABLED, $api_key_georeferencia_enabled);
            }
            if (isset($api_key_generacion_ot_enabled)) {
                Configuration::updateValue(CXP_API_KEY_GENERACION_OT_ENABLED, $api_key_generacion_ot_enabled);
            }
            if (isset($api_key_cotizador_enabled)) {
                Configuration::updateValue(CXP_API_KEY_COTIZADOR_ENABLED, $api_key_cotizador_enabled);
            }
            if (isset($ambiente)) {
                Configuration::updateValue(CXP_AMBIENTE, $ambiente);
            }

            if (isset($articulos_tienda)) {
                Configuration::updateValue(CXP_ARTICULOS_TIENDA, $articulos_tienda);
            }
            ///
            if (isset($region_origen)) {
                Configuration::updateValue(CXP_REGION_ORIGEN, $region_origen);
            }
            if (isset($comuna_origen)) {
                Configuration::updateValue(CXP_COMUNA_ORIGEN, $comuna_origen);
            }
            if (isset($numero_tcc_origen)) {
                Configuration::updateValue(CXP_NUMERO_TCC_ORIGEN, $numero_tcc_origen);
            }
            ///
            if (isset($nombre_remitente)) {
                Configuration::updateValue(CXP_NOMBRE_REMITENTE, $nombre_remitente);
            }
            if (isset($telefono_remitente)) {
                Configuration::updateValue(CXP_TELEFONO_REMITENTE, $telefono_remitente);
            }
            if (isset($email_remitente)) {
                Configuration::updateValue(CXP_EMAIL_REMITENTE, $email_remitente);
            }
            if (isset($rut_seller_remitente)) {
                Configuration::updateValue(CXP_RUT_SELLER_REMITENTE, $rut_seller_remitente);
            }
            if (isset($rut_marketplace_remitente)) {
                Configuration::updateValue(CXP_RUT_MARKETPLACE_REMITENTE, $rut_marketplace_remitente);
            }

            ///
            if (isset($nombre_remitente)) {
                Configuration::updateValue(CXP_REGION_DEVOLUCION, $region_devolucion);
            }
            if (isset($telefono_remitente)) {
                Configuration::updateValue(CXP_COMUNA_DEVOLUCION, $comuna_devolucion);
            }
            if (isset($calle_devolucion)) {
                Configuration::updateValue(CXP_CALLE_DEVOLUCION, $calle_devolucion);
            }
            if (isset($numero_calle_devolucion)) {
                Configuration::updateValue(CXP_NUMERO_CALLE_DEVOLUCION, $numero_calle_devolucion);
            }
            if (isset($complemento_devolucion)) {
                Configuration::updateValue(CXP_COMPLEMENTO_DEVOLUCION, $complemento_devolucion);
            }
            if (isset($dias_preparacion_pedidos)) {
                Configuration::updateValue(CXP_DIAS_PREPARACION_PEDIDOS, $dias_preparacion_pedidos);
            }
            if (isset($regiones_habilitadas)) {
                Configuration::updateValue(CXP_REGIONES_HABILITADAS, $regiones_habilitadas);
            }
            if (isset($comunas_habilitadas)) {
                Configuration::updateValue(CXP_COMUNAS_HABILITADAS, $comunas_habilitadas);
            }

            if (isset($prioridad_servicios)) {
                Configuration::updateValue(CXP_PRIORIDAD_SERVICIOS, $prioridad_servicios);
            }


            if (isset($ancho_defecto_producto)) {
                Configuration::updateValue(CXP_PRODUCT_DEFAULT_WIDTH, $ancho_defecto_producto);
            }

            if (isset($alto_defecto_producto)) {
                Configuration::updateValue(CXP_PRODUCT_DEFAULT_HEIGHT, $alto_defecto_producto);
            }

            if (isset($largo_defecto_producto)) {
                Configuration::updateValue(CXP_PRODUCT_DEFAULT_DEPTH, $largo_defecto_producto);
            }

            if (isset($peso_defecto_producto)) {
                Configuration::updateValue(CXP_PRODUCT_DEFAULT_WEIGHT, $peso_defecto_producto);
            }

            //

            if (isset($porcentaje_descuento)) {
                Configuration::updateValue(CXP_PORCENTAJE_DESCUENTO, $porcentaje_descuento);
            }

            //

            if (isset($corte_horario)) {
                Configuration::updateValue(CXP_CORTE_HORARIO, $corte_horario);
            }

            if (isset($dias_semana_ampm)) {
                Configuration::updateValue(CXP_DIAS_SEMANA_AMPM, $dias_semana_ampm);
            }

            $output .= $this->displayConfirmation($this->l('Datos Actualizados con éxito'));
        }
        return $output.$this->displayForm();
    }

    public function uninstallCarriers() // NOSONAR
    {
        $carrier_query = new DbQuery();
        $carrier_query->select(CXP_ID_CARRIER);
        $carrier_query->from(CXP_CARRIER);
        $carrier_query->where("name = 'Chilexpress'");
        
        $carriers_id_query = Db::getInstance()->executeS($carrier_query);
        $carriers_ids = [];

        foreach($carriers_id_query as $carrier_id)
        {
            $carriers_ids[] = $carrier_id[CXP_ID_CARRIER];
        }

        $carriers_ids = implode(",", $carriers_ids);

        Db::getInstance()->delete(CXP_CARRIER, 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete('carrier_group', 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete('carrier_lang', 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete('carrier_shop', 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete('carrier_tax_rules_group_shop', 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete('carrier_zone', 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete('cart', 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete('cart_rule_carrier', 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete(CXP_DELIVERY, 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete('range_price', 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete('range_weight', 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete('warehouse_carrier', 'id_carrier IN (' . $carriers_ids . ')'); // NOSONAR
        Db::getInstance()->delete('configuration', 'name LIKE "%CHILEXPRESS_OFCL%"'); // NOSONAR

        return true;
    }

    public function installCarriers() // NOSONAR
    {   
        foreach ($this->carriers_list as $carrier_key => $carrier_name)
        {
            if ( Configuration::hasKey($carrier_key) == false )
            {
                // Create new carrier
                $carrier = new Carrier();
                $carrier->name = $this->author;
                $carrier->id_tax_rules_group = 0;
                $carrier->active = 1;
                $carrier->deleted = 0;
                foreach (Language::getLanguages(true) as $language){
                    $carrier->delay[(int)$language['id_lang']] = $carrier_name;
                }
                $carrier->shipping_handling = false;
                $carrier->range_behavior = 0;
                $carrier->is_module = true;
                $carrier->shipping_external = true;
                $carrier->external_module_name = $this->name;
                $carrier->need_range = true;
                if (!$carrier->add()) {
                    return false;
                }

                // Associate carrier to all groups
                $groups = Group::getGroups(true);
                foreach ($groups as $group) {
                    Db::getInstance()->insert('carrier_group', array(CXP_ID_CARRIER => (int)$carrier->id, 'id_group' => (int)$group['id_group']));
                }

                // Create price range
                $rangePrice = new RangePrice();
                $rangePrice->id_carrier = $carrier->id;
                $rangePrice->delimiter1 = '0';
                $rangePrice->delimiter2 = '10000000';
                $rangePrice->add();

                // Create weight range
                $rangeWeight = new RangeWeight();
                $rangeWeight->id_carrier = $carrier->id;
                $rangeWeight->delimiter1 = '0';
                $rangeWeight->delimiter2 = '10000000';
                $rangeWeight->add();

                // Associate carrier to all zones
                $zones = Zone::getZones(true);
                foreach ($zones as $zone)
                {
                    Db::getInstance()->insert('carrier_zone', array(CXP_ID_CARRIER => (int)$carrier->id, CXP_ID_ZONE => (int)$zone[CXP_ID_ZONE]));
                    Db::getInstance()->insert(CXP_DELIVERY, array(CXP_ID_CARRIER => (int)$carrier->id, 'id_range_price' => (int)$rangePrice->id, 'id_range_weight' => NULL, CXP_ID_ZONE => (int)$zone[CXP_ID_ZONE], 'price' => '0'));
                    Db::getInstance()->insert(CXP_DELIVERY, array(CXP_ID_CARRIER => (int)$carrier->id, 'id_range_price' => NULL, 'id_range_weight' => (int)$rangeWeight->id, CXP_ID_ZONE => (int)$zone[CXP_ID_ZONE], 'price' => '0'));
                }

                // Copy the carrier logo
                copy(dirname(__FILE__).'/logo_medio_transporte.png', _PS_SHIP_IMG_DIR_.'/'.(int)$carrier->id.'.jpg');

                // Save the carrier ID in the Configuration table
                Configuration::updateValue($carrier_key, $carrier->id);
            }
            else
            {
                $carrier_query = new DbQuery();
                $carrier_query->from('carrier_lang');
                $carrier_query->where("delay = '". $carrier_name ."'");
                
                $carrier = Db::getInstance()->executeS($carrier_query);
                
                $update = Db::getInstance()->update(CXP_CARRIER, array('deleted' => 0), 'id_carrier = '. (int) $carrier[0][CXP_ID_CARRIER]);
                
                // Copy the carrier logo
                copy(dirname(__FILE__).'/logo_medio_transporte.png', _PS_SHIP_IMG_DIR_.'/'.(int) $carrier[0][CXP_ID_CARRIER].'.jpg');
            }
        }

        return true;
    }

    public function changeFormatAddress()
    {
        $format_address = 'firstname lastname
        address1
        other
        Country:name
        State:name
        city
        phone';

        $id_country = Country::getByIso('CL');

        Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'address_format` SET `format` = "'.$format_address.'" 
                                    WHERE id_country = '.$id_country);
        return true;
    }

    public function preloadRegionsCommunes()
    {
        $regiones = $this->api->obtener_regiones();
        $regiones_habilitadas = array();
        $comunas_habilitadas = array();

        if( is_array($regiones) && count($regiones) > 0 )
        {
            foreach ($regiones as $codigo_region => $nombre_region) 
            {
                array_push($regiones_habilitadas, $codigo_region);

                $_comunas = $this->api->obtener_comunas_desde_region($codigo_region);

                foreach ($_comunas as $codigo_comuna => $nombre_comuna) 
                {
                    array_push($comunas_habilitadas, $codigo_comuna);
                }    
            }
        }

        $coberturas = array(
            "regiones_habilitadas" => json_encode($regiones_habilitadas),
            "comunas_habilitadas" => json_encode($comunas_habilitadas)
        );

        return $coberturas;
    }

    public function hookDisplayBackOfficeHeader($params)
    {
        $this->context->controller->addJS($this->_path.'/views/js/jquery.dataTables.min.js'); //v1.11.4
        $this->context->controller->addCSS($this->_path.'/views/css/jquery.dataTables.min.css');
        $this->context->controller->addCSS($this->_path.'/views/css/chilexpress_oficial_admin.css');

        $this->context->smarty->assign(
            array(
                'chilexpress_oficial_ajax_url' => $this->context->link->getModuleLink( $this->name, 'ajax', array()),
            )
        );
        
        return $this->display(__FILE__, $this->name .'.tpl');
    }

    public function hookDisplayBackOfficeTop($params)
    {
        
        return $this->display(__FILE__, $this->name .'_footer'.'.tpl');
    }

    public function hookdisplayHeader($params)
    {
        // 
        $this->context->smarty->assign(
              array(
                  'chilexpress_oficial_ajax_url' => $this->context->link->getModuleLink( $this->name , 'ajax', array()),
              ));
        
        $this->context->controller->registerJavascript('chilexpress-official-front-script', 'modules/chilexpress_oficial/views/js/chilexpress_oficial_front.js', ['position' => 'bottom', 'priority' => 10]);
        return $this->display(__FILE__, $this->name .'_front.tpl');
    }

    public function hookUpdateCarrier($params)
    {
      $id_carrier_old = (int)($params[CXP_ID_CARRIER]);
      $id_carrier_new = (int)($params[CXP_CARRIER]->id);
     foreach ($this->carriers_list as $carrier_key => $carrier_name) {
        $carrier_id = Configuration::get($carrier_key);
        if ($id_carrier_old == $carrier_id) {
            Configuration::updateValue($carrier_key, $id_carrier_new);
        }
      }
    }

    public function hookDisplayCarrierExtraContent($params)
    {
        $carrier_param_key = '';
        $carrier_param_id = $params["carrier"]["delay"];
        foreach ($this->carriers_list as $carrier_key => $carrier_name) {
            $carrier_id = Configuration::get($carrier_key);
            if ($carrier_param_id == $carrier_name) {
                $carrier_param_key = $carrier_key;
            }
        }
        /*
            2)  PRIORITARIO: 1 dia (día sig habil hasta 11 am)
            3)  EXPRESS: 1 dia
            4)  EXTENDIDO: 1 - 2 dias
            5)  EXTREMOS: 2 - 3 dias
            8)  AM/PM: 0 dias  (mismo día hasta 20 hrs)
            41) ENC. GRANDES: 2 días hábiles, entre 11:00 y 19:00 hrs
            42) ENC. GRANDES EXTENDIDO: 6 días hábiles, entre 11:00 y 19:00 hrs
        */
        $dias_preparacion_tienda = intval( Configuration::get(CXP_DIAS_PREPARACION_PEDIDOS) );
        $delay = $params["carrier"]["delay"];
        $glosa_informativa = "<p style='text-align: center;'><small>La fecha de entrega de los servicios Chilexpress considera el tiempo de preparación del pedido, [".$dias_preparacion_tienda."] día(s), establecido por la tienda.</small></p>";
        if ($delay == 'PRIORITARIO' || $carrier_param_key == 'CHILEXPRESS_OFCL_DHSP') {
            $extra_content = "<p style='text-align: right;'><small>[ " . ($dias_preparacion_tienda + 1) . " días hábiles (hasta las 11 hrs) ] </small></p>";
            $extra_content = $extra_content . $glosa_informativa;
            $params["carrier"]["extraContent"] = $extra_content;
        } else if ($delay == 'EXPRESS' || $carrier_param_key == 'CHILEXPRESS_OFCL_DHS') {
            $extra_content = "<p style='text-align: right;'><small>[ " . ($dias_preparacion_tienda + 1) . " días hábiles (hasta las 19 hrs) ] </small></p>";
            $extra_content = $extra_content . $glosa_informativa;
            $params["carrier"]["extraContent"] = $extra_content;
        } elseif ($delay == 'EXTENDIDO' || $carrier_param_key == 'CHILEXPRESS_OFCL_DHSS') {
            $extra_content = "<p style='text-align: right;'><small>[ " . ($dias_preparacion_tienda + 1) . " a " . ($dias_preparacion_tienda + 2) . " días hábiles ] </small></p>";
            $extra_content = $extra_content . $glosa_informativa;
            $params["carrier"]["extraContent"] = $extra_content;
        } else if ($delay == 'EXTREMOS' || $carrier_param_key == 'CHILEXPRESS_OFCL_3DH') {
            $extra_content = "<p style='text-align: right;'><small>[ " . ($dias_preparacion_tienda + 2) . " a " . ($dias_preparacion_tienda + 3) . " días hábiles ] </small></p>";
            $extra_content = $extra_content . $glosa_informativa;
            $params["carrier"]["extraContent"] = $extra_content;
        } else if ($delay == 'AM/PM' || $carrier_param_key == 'CHILEXPRESS_OFCL_MDAP') {
            /*if($dias_preparacion_tienda > 0){
                $extra_content = "<p style='text-align: right;'><small>[ " . ($dias_preparacion_tienda + 0) . " días hábiles (hasta las 22 hrs) ] </small></p>";
                $extra_content = $extra_content . $glosa_informativa;
            }
            else{*/
                $extra_content = "<p style='text-align: right;'><small>[ mismo día hasta las 22 hrs ] </small></p>";
                //$extra_content = $extra_content . $glosa_informativa;
            //}
            $params["carrier"]["extraContent"] = $extra_content;
        } else if ($delay == 'ENC. GRANDES' || $carrier_param_key == 'CHILEXPRESS_OFCL_BIG1') {
            $extra_content = "<p style='text-align: right;'><small>[ " . ($dias_preparacion_tienda + 2) . " días hábiles (entre 11:00 y 19:00 hrs) ] </small></p>";
            $extra_content = $extra_content . $glosa_informativa;
            $params["carrier"]["extraContent"] = $extra_content;
        } else if ($delay == 'BASICO' && $carrier_param_key == 'CHILEXPRESS_OFCL_BSC3') {
            $extra_content = "<p style='text-align: right;'><small>[ " . ($dias_preparacion_tienda + 3) . " días hábiles (entre 11:00 y 19:00 hrs) ] </small></p>";
            $extra_content = $extra_content . $glosa_informativa;
            $params["carrier"]["extraContent"] = $extra_content;
        } else if ($delay == 'BASICO' && $carrier_param_key == 'CHILEXPRESS_OFCL_BSC4') {
            $extra_content = "<p style='text-align: right;'><small>[ " . ($dias_preparacion_tienda + 4) . " días hábiles (entre 11:00 y 19:00 hrs) ] </small></p>";
            $extra_content = $extra_content . $glosa_informativa;
            $params["carrier"]["extraContent"] = $extra_content;
        } else if ($delay == 'BASICO' && $carrier_param_key == 'CHILEXPRESS_OFCL_BSC5') {
            $extra_content = "<p style='text-align: right;'><small>[ " . ($dias_preparacion_tienda + 5) . " días hábiles (entre 11:00 y 19:00 hrs) ] </small></p>";
            $extra_content = $extra_content . $glosa_informativa;
            $params["carrier"]["extraContent"] = $extra_content;
        } else if ($carrier_param_key == 'CHILEXPRESS_OFCL_EX12') {
            $extra_content = "<p style='text-align: right;'><small>[ " . ($dias_preparacion_tienda + 12) . " días hábiles (entre 11:00 y 19:00 hrs) ] </small></p>";
            $extra_content = $extra_content . $glosa_informativa;
            $params["carrier"]["extraContent"] = $extra_content;
        } else if ($carrier_param_key == 'CHILEXPRESS_OFCL_EDS') {
            $extra_content = "<p style='text-align: right;'><small>[ " . ($dias_preparacion_tienda + 1) . " a " . ($dias_preparacion_tienda + 5) . " días hábiles] </small></p>";
            $extra_content = $extra_content . $glosa_informativa;
            $params["carrier"]["extraContent"] = $extra_content;
        } else {
            $params["carrier"]["extraContent"] = "";
        }
        return $params["carrier"]["extraContent"];
    }

    /** shipping related functions **/
    // This function is calles as many times as many carriers we'va got registered in the shop
    public function getOrderShippingCost($params, $shipping_fees) // NOSONAR
    {
        
        $currency = new Currency( $params->id_currency );
        
        if( $currency->iso_code !== 'CLP' )
          return false;
        
        $result = Db::getInstance()->delete('chilexpress_oficial_apicache', 'created < (NOW() - INTERVAL 1 HOUR)');
        $carrier = new Carrier($this->id_carrier);
        $current_carrier_key = false;
        $current_carrier_name = '';
        $current_carrier_id = 0;

        foreach ($this->carriers_list as $carrier_key => $carrier_name)
        {
            $carrier_id = Configuration::get($carrier_key);

            if ($carrier_id == $this->id_carrier)
            {
                $current_carrier_key = ($carrier_key);
                $current_carrier_name = ($carrier_name);
                $current_carrier_id = ($carrier_id);
                break;
            }
        }
        

        if (!$current_carrier_key) {
            return false;
        }

        $address = new Address($params->id_address_delivery);
        $pais = $address->country;

        if( $pais !== 'Chile' )
          return false;

        $comuna_code = $address->city; 
        $products = $params->getProducts(true);

        $products_required_fields = array();
        $total = 0;
        $total_weight = 0;

        $biggest_product = false;
        $biggest_size = 0;
        $product_quantity = array();

        $conf = array(
            CXP_COMUNA_ORIGEN => Configuration::get(CXP_COMUNA_ORIGEN),
            CXP_COMUNA_DESTINO => $comuna_code,
            CXP_TOTAL => $total,
            CXP_WIDTH => floatval( Configuration::get(CXP_PRODUCT_DEFAULT_WIDTH) ),
            CXP_HEIGHT => floatval( Configuration::get(CXP_PRODUCT_DEFAULT_HEIGHT) ),
            CXP_DEPTH => floatval( Configuration::get(CXP_PRODUCT_DEFAULT_DEPTH) ),
            CXP_PORCENTAJE_DESCUENTO => intval( Configuration::get(CXP_PORCENTAJE_DESCUENTO) )
        );

        foreach($products as $product) {

            $weight = ( floatval($product['weight']) ) ? floatval( $product['weight'] ) : floatval( Configuration::get(CXP_PRODUCT_DEFAULT_WEIGHT) );

            $product_quantity[] = $product[CXP_ID_PRODUCT] . ":" . $product[CXP_CART_QUANTITY];

            if ( floatval($product[CXP_WIDTH]) && floatval($product[CXP_HEIGHT]) && floatval($product[CXP_DEPTH]) ) 
            {
                if( floatval($product[CXP_WIDTH]) * floatval($product[CXP_HEIGHT]) * floatval($product[CXP_DEPTH]) > $biggest_size )
                { 
                    $biggest_size = $product[CXP_WIDTH] * $product[CXP_HEIGHT] * $product[CXP_DEPTH];
                    $conf[CXP_WIDTH] = floatval( $product[CXP_WIDTH] );
                    $conf[CXP_HEIGHT] = floatval( $product[CXP_HEIGHT] );
                    $conf[CXP_DEPTH] = floatval( $product[CXP_DEPTH] );
                }
                
            }

            $total_weight += $weight * $product[CXP_CART_QUANTITY];
            $conf[CXP_TOTAL] += $product[CXP_TOTAL];
        }


        $comunas_habilitadas = json_decode(Configuration::get(CXP_COMUNAS_HABILITADAS), true);

        if( !in_array( $conf[CXP_COMUNA_DESTINO], $comunas_habilitadas ) ){
            return false;
        }


        $sql = '
        SELECT * FROM 
            ' . _DB_PREFIX_ . 'chilexpress_oficial_apicache
        WHERE
            carrier_key = "'.$current_carrier_key.'" AND 
            comuna_origen = "'.$conf[CXP_COMUNA_ORIGEN].'" AND 
            comuna_destino = "'.$conf[CXP_COMUNA_DESTINO].'" AND 
            cart_id = "'.$params->id.'" AND 
            costo_total = "'.intval($conf[CXP_TOTAL]).'" AND 
            product_quantity = "'.implode(",",$product_quantity).'" 
        ORDER BY created DESC';
        $row = Db::getInstance()->getRow($sql);

        if ($row) {
            if (intval($row["service_value"]) == -1) {
                return false;
            }
            return  intval($row["service_value"]) + $shipping_fees;
        }

        $jresult = $this->api->obtener_cotizacion($conf[CXP_COMUNA_ORIGEN], $conf[CXP_COMUNA_DESTINO], $total_weight,  $conf[CXP_WIDTH],  $conf[CXP_HEIGHT],  $conf[CXP_DEPTH], $conf[CXP_TOTAL]);

        $api_cache = new ChilexpressOficialApiCache();
        $api_cache->carrier_key = $current_carrier_key;
        $api_cache->comuna_origen = $conf[CXP_COMUNA_ORIGEN];
        $api_cache->comuna_destino = $conf[CXP_COMUNA_DESTINO];
        $api_cache->cart_id = $params->id ;
        $api_cache->costo_total = intval($conf[CXP_TOTAL]);
        $api_cache->product_quantity = implode(",",$product_quantity);
        $api_cache->created = date('Y-m-d H:i:s');

        $service_value = -1;
        // busca el porcentaje de descuento en la configuracion
        $porcentaje_descuento = ( $conf[CXP_PORCENTAJE_DESCUENTO] ) ? intval( $conf[CXP_PORCENTAJE_DESCUENTO] ) : 0;


        if (!$jresult){
            $api_cache->service_value = $service_value;
            $api_cache->add();
            return false;
        } else {
            $servicios_excluidos = array(14,15,16,43,44,45,46,47,48);
			
            if( !in_array($this->carriers_serviceTypeCode[$current_carrier_key], $servicios_excluidos) ) {

                if($this->carriers_serviceTypeCode[$current_carrier_key] == 8){ //Si el servicio es AMPM
                    $service = $this->validate_ampm_service( $products );
                    if(!$service)
                        return false;
                }
            }
            else{
                return false;
            }
            $courier_service_options = [];
            foreach ($jresult["data"]["courierServiceOptions"] as $option) {

                if ($option[CXP_SERVICETYPECODE] == $this->carriers_serviceTypeCode[$current_carrier_key]) {
                    $serviceValueTemp = intval($option[CXP_SERVICEVALUE]);
                    $service_value = $this->discount_shipping( $serviceValueTemp, $porcentaje_descuento );
                }
                
            }
        }
        $api_cache->service_value = $service_value;
        $api_cache->add();
    //die();
        if ($service_value == -1) {
            return false;
        }

        return $service_value + $shipping_fees;
    }

    public function getOrderShippingCostExternal($params) // NOSONAR
    {
        $currency = new Currency( $params->id_currency );
        if( $currency->iso_code !== 'CLP' )
          return false;

          $carrier = new Carrier($this->id_carrier);
          $current_carrier_key = false;
          $current_carrier_name = '';
          $current_carrier_id = 0;

          foreach ($this->carriers_list as $carrier_key => $carrier_name) {
              $carrier_id = Configuration::get($carrier_key);
              if ($carrier_id == $this->id_carrier) {
                $current_carrier_key = ($carrier_key);
                $current_carrier_name = ($carrier_name);
                $current_carrier_id = ($carrier_id);
              }
          }

          if (!$current_carrier_key) {
            return false;
          }

          $address = new Address($params->id_address_delivery);
          $pais = $address->country;

          if( $pais !== 'Chile' )
            return false;

          $comuna_code = $address->city; 
          $products = $params->getProducts(true);

          //$products_required_fields = array();
          $total = 0;
          $total_weight = 0;
            
          //$biggest_product = false;
          $biggest_size = 0;

          $conf = array(
            CXP_COMUNA_ORIGEN => Configuration::get(CXP_COMUNA_ORIGEN),
            CXP_COMUNA_DESTINO => $comuna_code,
            CXP_TOTAL => $total,
            CXP_WIDTH => floatval( Configuration::get(CXP_PRODUCT_DEFAULT_WIDTH) ),
            CXP_HEIGHT => floatval( Configuration::get(CXP_PRODUCT_DEFAULT_HEIGHT) ),
            CXP_DEPTH => floatval( Configuration::get(CXP_PRODUCT_DEFAULT_DEPTH) ),
        );

        foreach($products as $product) {

            $weight = ( floatval($product['weight']) ) ? floatval( $product['weight'] ) : floatval( Configuration::get(CXP_PRODUCT_DEFAULT_WEIGHT) );

            $product_quantity[] = $product[CXP_ID_PRODUCT] . ":" . $product[CXP_CART_QUANTITY];

            if ( floatval($product[CXP_WIDTH]) && floatval($product[CXP_HEIGHT]) && floatval($product[CXP_DEPTH]) ) {
                
                if( floatval($product[CXP_WIDTH]) * floatval($product[CXP_HEIGHT]) * floatval($product[CXP_DEPTH]) > $biggest_size ) { 
                    $biggest_size = $product[CXP_WIDTH] * $product[CXP_HEIGHT] * $product[CXP_DEPTH];
                    $conf[CXP_WIDTH] = floatval( $product[CXP_WIDTH] );
                    $conf[CXP_HEIGHT] = floatval( $product[CXP_HEIGHT] );
                    $conf[CXP_DEPTH] = floatval( $product[CXP_DEPTH] );
                }
                
            }

            $total_weight += $weight * $product[CXP_CART_QUANTITY];
            $conf[CXP_TOTAL] += $product[CXP_TOTAL];
        }


        $comunas_habilitadas = json_decode(Configuration::get(CXP_COMUNAS_HABILITADAS), true);

        if( !in_array( $conf[CXP_COMUNA_DESTINO], $comunas_habilitadas ) ){
            return false;
        }


        $jresult = $this->api->obtener_cotizacion($conf[CXP_COMUNA_ORIGEN], $conf[CXP_COMUNA_DESTINO], $total_weight,  $conf[CXP_WIDTH],  $conf[CXP_HEIGHT],  $conf[CXP_DEPTH], $conf[CXP_TOTAL]);

        $serviceValue = false;
        if (!$jresult){
            return false;
        } 
        else {

            $lowestService = null;

            $servicios_excluidos = array(14,15,16,43,44,45,46,47,48);
			
            if( !in_array($this->carriers_serviceTypeCode[$current_carrier_key], $servicios_excluidos) ) {

                if($this->carriers_serviceTypeCode[$current_carrier_key] == 8){ //Si el servicio es AMPM
                    $service = $this->validate_ampm_service( $products );
                    if(!$service)
                        return false;
                }
            }
            else{
                return false;
            }

            $porcentaje_descuento = ( $conf[CXP_PORCENTAJE_DESCUENTO] ) ? intval( $conf[CXP_PORCENTAJE_DESCUENTO] ) : 0;
            
            foreach ($jresult["data"]["courierServiceOptions"] as $option)
            {
                if ($option[CXP_SERVICETYPECODE] == $this->carriers_serviceTypeCode[$current_carrier_key] && intval($option[CXP_SERVICETYPECODE]) >= 2)
                {
                    if($lowestService == NULL)
                    {
                        $lowestService = $option;
                        $serviceValueTemp = intval($option[CXP_SERVICEVALUE]);
                        $serviceValue = $this->discount_shipping( $serviceValueTemp, $porcentaje_descuento );
                    }
                    else
                    {
                        if($lowestService[CXP_SERVICETYPECODE] > $option[CXP_SERVICETYPECODE])
                        {
                            $lowestService = $option;
                            $serviceValueTemp = intval($option[CXP_SERVICEVALUE]);
                            $serviceValue = $this->discount_shipping( $serviceValueTemp, $porcentaje_descuento );
                        }
                    }
                }
            }
        }

        if(!serviceValue){
           return false;
        }

        return $serviceValue;
    }

    public function hookActionAdminCustomersListingFieldsModifier($params)
    {
        if (!isset($params[CXP_FIELDS]['customer_group'])) {
            $params[CXP_FIELDS]['customer_group'] = array(
                CXP_TITLE => 'Grupo',
                CXP_ALIGN => CXP_TEXT_CENTER,
                CXP_CLASS => CXP_FIXED_WIDTH_XS,
                CXP_FILTER_KEY => "cg!id_group"
            );
        }

        if (isset($params[CXP_SELECT])) {
            $params[CXP_SELECT] .= ", cg.id_group AS customer_group";
        }

        if (isset($params['join'])) {
            $params['join'] .= 'LEFT JOIN `' . _DB_PREFIX_ . 'customer_group` cg ON (a.`id_customer` = cg.`id_customer`)'; // NOSONAR
        }
    }

    /**
     * Hook allows to modify Order grid definition since 1.7.7.0
     *
     * @param array $params
     */
    public function hookActionOrderGridDefinitionModifier(array $params)
    {
        if (empty($params['definition'])) {
            return;
        }

        /** @var PrestaShop\PrestaShop\Core\Grid\Definition\GridDefinitionInterface $definition */
        $definition = $params['definition'];

        $column1 = new PrestaShop\PrestaShop\Core\Grid\Column\Type\DataColumn('carrier_reference');
        $column1->setName($this->l('Acciones Chilexpress'));
        $column1->setOptions([
            'field' => CXP_CARRIER_NAME,
            'clickable' => false,
        ]);

        $column2 = new PrestaShop\PrestaShop\Core\Grid\Column\Type\DataColumn(CXP_TRACKING_NUMBER);
        $column2->setName($this->l('Tracking Chilexpress'));
        $column2->setOptions([
            'field' => CXP_TRACKING_NUMBER,
            'clickable' => false,
        ]);

        $definition->getColumns()->remove('country_name');

        $definition
            ->getColumns()
            ->addBefore(
                'actions',
                $column1
            );

            $definition
            ->getColumns()
            ->addBefore(
                'actions',
                $column2
            );

        $definition->getBulkActions()->add(
                (new SubmitBulkAction('generar_multiples_ot'))
                    ->setName('Generar Multiples OT')
                    ->setOptions([
                        // in most cases submit action should be implemented by module
                        'submit_route' => 'cxpmodule_multiples_ot',
                    ]) 
            );
    }

    /**
     * Hook allows to modify Order grid data since 1.7.7.0
     *
     * @param array $params
     */
    public function hookActionOrderGridDataModifier(array $params) // NOSONAR
    {
        if (empty($params['data'])) {
            return;
        }
        

        /** @var PrestaShop\PrestaShop\Core\Grid\Data\GridData $gridData */
        
        $gridData = $params['data'];
        $modifiedRecords = $gridData->getRecords()->all();
        
        foreach ($modifiedRecords as $key => $data) {

            $order = new Order($data[CXP_ID_ORDER]);
            $res_carrier_name = '<div class="btn-group-action text-center"><div class="btn-group d-flex">';
            $res_tracking_number = "";
        
            if (Validate::isLoadedObject($order)) {
                $tracking_number = '';
                if($order->getWsShippingNumber()) {
                    $tracking_number = $order->getWsShippingNumber();
                }
                
                //$current_state = $order->current_state;
                $carrier_id = $order->id_carrier;
                foreach ($this->carriers_list as $carrier_key => $carrier_name) {
                    
                    $official_carrier_id = Configuration::get($carrier_key);
                    
                    //if( $carrier_id == $official_carrier_id && array_search( $current_state , array(100,5,4,8,2,11,12,9,3,7)) ) { // when state was the first then returned 0 that is false
                    if( $carrier_id == $official_carrier_id ) {
                        if($tracking_number) {
                            $numbers = explode(",", $tracking_number);
                            $out = array();
                            foreach ($numbers as $number)
                            {
                                $out[] = '<a href="javascript:;" data-tracking-code="'.$number.'" data-orderid="'.$data[CXP_ID_ORDER].'">'.$number.'</a>';
                            }
                            $res_carrier_name .= CXP_A_HREF.$this->context->link->getAdminLink(CXP_CHILEXPRESS_ORDER).CXP_ORDER_ID_EQ.$data[CXP_ID_ORDER].'&action=ver_ot"  data-confirm-message="" data-toggle="pstooltip" data-placement="top" data-original-title="Imprimir OT" class="btn tooltip-link js-link-row-action dropdown-item inline-dropdown-item"><i class="material-icons">print</i></a>';
                            $res_tracking_number = implode('<br />', $out);
                        } else { 
                            $res_carrier_name .= CXP_A_HREF.$this->context->link->getAdminLink(CXP_CHILEXPRESS_ORDER).CXP_ORDER_ID_EQ.$data[CXP_ID_ORDER].'&action=generar_ot" data-confirm-message="" data-toggle="pstooltip" data-placement="top" data-original-title="Generar OT" class="btn tooltip-link js-link-row-action dropdown-item inline-dropdown-item"><i class="material-icons">settings</i></a>';
                        }
                    }
                }
            }
            $res_carrier_name .= '</div></div>';

            if (empty($data[CXP_CARRIER_NAME])) {
                $modifiedRecords[$key][CXP_CARRIER_NAME] = $res_carrier_name;
            }
            
            if (empty($data[CXP_TRACKING_NUMBER])) {
                $modifiedRecords[$key][CXP_TRACKING_NUMBER] = $res_tracking_number;
            }
        }

        $params['data'] = new PrestaShop\PrestaShop\Core\Grid\Data\GridData(
            new PrestaShop\PrestaShop\Core\Grid\Record\RecordCollection($modifiedRecords),
            $gridData->getRecordsTotal(),
            $gridData->getQuery()
        );
        
    }

    /**
     * Hook allows to modify Order query builder and add custom sql statements since 1.7.7.0
     *
     * @param array $params
     */
    public function hookActionOrderGridQueryBuilderModifier(array $params)
    {
        
        if (isset($params[CXP_SELECT])) {
            $params[CXP_SELECT] .= ", oca.tracking_number AS tracking_number";
            $params[CXP_SELECT] .= ", ca.name AS carrier_name";
        }

        if (isset($params['join'])) {
            $params['join'] .= 'LEFT JOIN `' . _DB_PREFIX_ . 'order_carrier` oca ON (a.`id_order` = oca.`id_order`)'; // NOSONAR
            $params['join'] .= 'LEFT JOIN `' . _DB_PREFIX_ . 'carrier` ca ON (ca.`id_carrier` = oca.`id_carrier`)'; // NOSONAR
        }
    }

    /**
     * Hook allows to modify Order grid data before 1.7.7.0
     *
     * @param array $params
     */
    public function hookActionAdminOrdersListingFieldsModifier($params)
    {
        if (!isset($params[CXP_FIELDS][CXP_CARRIER_NAME])) {
            $params[CXP_FIELDS][CXP_CARRIER_NAME] = array(
                CXP_TITLE => 'Acciones',
                CXP_ALIGN => CXP_TEXT_CENTER,
                CXP_CLASS => CXP_FIXED_WIDTH_XS,
                CXP_FILTER_KEY => "ca!name",
                'callback' => 'callbackMethod2',
                'orderby' => false,
                'search' => false,
                'callback_object' => Module::getInstanceByName($this->name)
            );
        } 

        if (!isset($params[CXP_FIELDS][CXP_TRACKING_NUMBER])) {

            $params[CXP_FIELDS][CXP_TRACKING_NUMBER] = array(
                CXP_TITLE => 'Tracking',
                CXP_ALIGN => CXP_TEXT_CENTER,
                CXP_CLASS => CXP_FIXED_WIDTH_XS,
                CXP_FILTER_KEY => "oca!tracking_number",
                'callback' => 'callbackMethod',
                'orderby' => false,
                'search' => false,
                'callback_object' => Module::getInstanceByName($this->name)
            );
        }
        
        if (isset($params[CXP_SELECT])) {
            $params[CXP_SELECT] .= ", oca.tracking_number AS tracking_number";
            $params[CXP_SELECT] .= ", ca.name AS carrier_name";
        }

        if (isset($params['join'])) {
            $params['join'] .= 'LEFT JOIN `' . _DB_PREFIX_ . 'order_carrier` oca ON (a.`id_order` = oca.`id_order`)'; // NOSONAR
            $params['join'] .= 'LEFT JOIN `' . _DB_PREFIX_ . 'carrier` ca ON (ca.`id_carrier` = oca.`id_carrier`)'; // NOSONAR
        }

    }

    public function callbackMethod($value, $tr)
    {
        $order = new Order($tr[CXP_ID_ORDER]);
        if (!Validate::isLoadedObject($order)) {
            return '';
        }
        $tracking_number = $order->getWsShippingNumber();
        $current_state = $order->current_state;
        $carrier_id = $order->id_carrier;

        foreach ($this->carriers_list as $carrier_key => $carrier_name) {
            $official_carrier_id = Configuration::get($carrier_key);
            if( $carrier_id == $official_carrier_id && array_search( $current_state , array(100,5,4,8,2,11,12,9,3,7)) && $tracking_number) {
                $numbers = explode(",", $tracking_number);
                $out = array();
                foreach ($numbers as $number)
                {
                    $out[] = '<a href="javascript:;" data-tracking-code="'.$number.'" data-orderid="'.$tr[CXP_ID_ORDER].'">'.$number.'</a>';
                }
                return implode('<br />', $out);
            }
        }

        return '-';
    }

    public function callbackMethod2($value, $tr) // NOSONAR
    {
        $order = new Order($tr[CXP_ID_ORDER]);
        if (!Validate::isLoadedObject($order)) {
            return '';
        }
        $tracking_number = $order->getWsShippingNumber();
        $current_state = $order->current_state;
        $carrier_id = $order->id_carrier;

        foreach ($this->carriers_list as $carrier_key => $carrier_name) {
            $official_carrier_id = Configuration::get($carrier_key);
            if( $carrier_id == $official_carrier_id && array_search( $current_state , array(100,5,4,8,2,11,12,9,3,7)) )
            {
                if(!$tracking_number) {
                    return CXP_A_HREF.$this->context->link->getAdminLink(CXP_CHILEXPRESS_ORDER).CXP_ORDER_ID_EQ.$tr[CXP_ID_ORDER].'&action=generar_ot" title="Generar OT" class="btn btn-default with-tooltip"><i class="icon-cog" data-toggle="tooltip" data-placement="top" title="Generar OT"></i></a>';
                } else {
                    return CXP_A_HREF.$this->context->link->getAdminLink(CXP_CHILEXPRESS_ORDER).CXP_ORDER_ID_EQ.$tr[CXP_ID_ORDER].'&action=ver_ot" title="Imprimir OT" class="btn btn-default with-tooltip"><i class="icon-print" data-toggle="tooltip" data-placement="top" title="Imprimir OT"></i></a>';
                }
            }
        }

        return '';
    }

    /**
     * Add buttons to main buttons bar
     */
    public function hookActionGetAdminOrderButtons(array $params)
    {
        $order = new Order($params[CXP_ID_ORDER]);

        /** @var \Symfony\Bundle\FrameworkBundle\Routing\Router $router */
        $router = $this->get('router');

        /** @var \PrestaShopBundle\Controller\Admin\Sell\Order\ActionsBarButtonsCollection $bar */
        $bar = $params['actions_bar_buttons_collection'];

        $viewCustomerUrl = $router->generate('admin_customers_view', ['customerId'=> (int)$order->id_customer]);
        $bar->add(
            new \PrestaShopBundle\Controller\Admin\Sell\Order\ActionsBarButton(
                'btn-secondary', ['href' => $viewCustomerUrl], 'View customer'
            )
        );
        $bar->add(
            new \PrestaShopBundle\Controller\Admin\Sell\Order\ActionsBarButton(
                'btn-info', ['href' => 'https://www.prestashop.com/'], 'Go to prestashop'
            )
        );
        $bar->add(
            new \PrestaShopBundle\Controller\Admin\Sell\Order\ActionsBarButton(
                'btn-dark', ['href' => 'https://github.com/PrestaShop/example-modules/tree/master/demovieworderhooks'], 'Go to GitHub'
            )
        );
        $createAnOrderUrl = $router->generate('admin_orders_create');
        $bar->add(
            new \PrestaShopBundle\Controller\Admin\Sell\Order\ActionsBarButton(
                'btn-link', ['href' => $createAnOrderUrl], 'Create an order'
            )
        );
    }

    public function loadSQLFile($sql_file)
    {
      // Get install SQL file content
      $sql_content = file_get_contents($sql_file);

      // Replace prefix and store SQL command in array
      $sql_content = str_replace('PREFIX_', _DB_PREFIX_, $sql_content);
      $sql_requests = preg_split("/;\s*[\r\n]+/", $sql_content); // NOSONAR

      // Execute each SQL statement
      $result = true;
      foreach($sql_requests as $request){
        if (!empty($request)) {
            $result &= Db::getInstance()->execute(trim($request));
        }
      }

      // Return result
      return $result;
    }

    function hookDisplayAdminOrderContentShip($param)
    {   
        if ( $param[CXP_ORDER]->shipping_number!= '' )
        {
            $order_id = $param[CXP_ORDER]->id;
            $carrier_id = $param[CXP_ORDER]->id_carrier;


            foreach ($this->carriers_list as $carrier_key => $carrier_name) {
                $official_carrier_id = Configuration::get($carrier_key);
                if ( $carrier_id == $official_carrier_id){
                    $query = new DbQuery();
                    $query->from('chilexpress_oficial_ordermeta', 'com');
                    $query->where('com.id_order = "'.$order_id.'"');
                    $metasArray = Db::getInstance()->executeS($query);
                    $out = '<div class="well"><div class="row"><div class="col-md-12"><h3>Etiquetas de Chilexpress</h3></div>';
                    foreach ($metasArray as $meta) {
                        $src = 'data:image/jpg;base64,'.$meta['labelData'];
                        $out.= '<img src="'.$src.'" style="display:block; margin:0 auto;"/> <br />';

                    }
                    $out.= CXP_A_HREF.$this->context->link->getAdminLink(CXP_CHILEXPRESS_ORDER).CXP_ORDER_ID_EQ.$order_id.'&action=print_ot'.'" class="btn btn-primary btn-block"><i class="icon-print"></i> Imprimir Etiquetas</a>';

                    $out .= "</div></div>";
                    return $out;
                }
            }
        }
        
        return '';
        
    }

    private function checkAndAddChileanStatesOnInstall() // NOSONAR
    {
        // // // // // // // //
        $id_country = (int) Country::getByIso(strval('CL'));
        $regiones = $this->api->obtener_regiones();
        foreach ($regiones as $iso => $name) {
            
            $id_state = State::getIdByIso($iso, $id_country);
            if (!$id_state) {
                $state = new State();
                $state->name = substr ($name , 0 , 32) ;
                $state->iso_code = strval($iso);
                $state->id_country = $id_country;

                $id_zone = (int) Zone::getIdByName(strval('South America'));

                if (!$id_zone) {
                    $zone = new Zone();
                    $zone->name = 'South America';
                    $zone->active = true;
                    
                    if (!$zone->add()) {
                        $this->_errors[] = Context::getContext()->getTranslator()->trans('Invalid Zone name.', array(), CXP_ADMIN_INTERNATIONAL_NOTIFICATION);

                        return false;
                    }

                    $id_zone = $zone->id;
                }
                $state->id_zone = $id_zone;

                $country = new Country($state->id_country);
                if (!$country->contains_states) {
                    $country->contains_states = 1;
                    if (!$country->update()) {
                        $this->_errors[] = Context::getContext()->getTranslator()->trans('Cannot update the associated country: %s', array($country->name), CXP_ADMIN_INTERNATIONAL_NOTIFICATION);
                    }
                }

                if (!$state->add()) {
                    $this->_errors[] = Context::getContext()->getTranslator()->trans('An error occurred while adding the state.', array(), CXP_ADMIN_INTERNATIONAL_NOTIFICATION);

                    return false;
                }

            }
        }
        return true;
        // // // // // // // //
    }

    public function getErrors()
    {
        return $this->_errors;
    }

    function discount_shipping( $price, $porcent ) {

        $discount_price = $price;

        if( $porcent > 0){

            $discount = ($price * $porcent) / 100;
            $discount_price = $price - $discount;

        }
        
        return $discount_price;
    }

    function validate_ampm_service( $products ) {

        date_default_timezone_set("America/Santiago");
        $date = new DateTime();
            
        $hora = true;
        $dia = true;
        $diaH = true;
        $productos = true;
        $service = true;
            
        /*Inicio validar corte horario*/
        $corte_horario = Configuration::get(CXP_CORTE_HORARIO).":00";
        $hora_actual = $date->format('H:i');

        if( strtotime( $hora_actual ) > strtotime( $corte_horario ) )
            $hora = false;
        /*Final validar corte horario*/

        /*Inicio validar dia*/
        $dias_semana = json_decode(Configuration::get(CXP_DIAS_SEMANA_AMPM), true);
        $dia_actual = $date->format('w');

        if( !in_array($dia_actual, $dias_semana) )
            $dia = false;
        /*Final validar dia*/

        /*Inicio validar dia habil*/
        $dia_habil = $this->api->validar_dia_habil();
        if( $dia_habil["IndHabil"] > 0 )
            $diaH = false;
        /*Final validar dia habil*/

        /*Inicio validar productos*/
        foreach ( $products as $key => $product ) {
            
            $_service_ampm = $this->getChilexpressProductmeta($product['id_product'], '_service_ampm');

            if($_service_ampm == '' || !$_service_ampm)
                $productos = false;
        }
        /*Final validar productos*/

        if(!$hora || !$dia || !$diaH || !$productos)
            $service = false;

        return $service;
    }

}
