<?php
/**
* NOTICE OF LICENSE
*
* This source file is subject to a commercial license from SARL Ether Création
* Use, copy, modification or distribution of this source file without written
* license agreement from the SARL Ether Création is strictly forbidden.
* In order to obtain a license, please contact us: contact@ethercreation.com
* ...........................................................................
* INFORMATION SUR LA LICENCE D'UTILISATION
*
* L'utilisation de ce fichier source est soumise a une licence commerciale
* concedee par la societe Ether Création
* Toute utilisation, reproduction, modification ou distribution du present
* fichier source sans contrat de licence ecrit de la part de la SARL Ether Création est
* expressement interdite.
* Pour obtenir une licence, veuillez contacter la SARL Ether Création a l'adresse: contact@ethercreation.com
* ...........................................................................
*
*  @package eclaposte
*  @author Arthur R.
*  @copyright Copyright (c) 2010-2016 S.A.R.L Ether Création (http://www.ethercreation.com)
*  @license Commercial license
*/

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

class Eclaposte extends Module
{
    public function __construct()
    {
        $this->name = 'eclaposte';
        $this->tab = 'shipping_logistics';
        $this->version = '1.2.4';
        $this->bootstrap = true;
        $this->module_key = 'af05c5d583d62c83186c6161c54e874c';
        $this->author = 'Ether Création';
        $this->displayName = $this->l('EC Settings shipping');
        $this->description = $this->l('Settings shipping : la poste');
        $this->repertoire_sav = _PS_MODULE_DIR_.'eclaposte/backup';
        parent::__construct();
    }

    public function install()
    {
        if (!parent::install()) {
            return false;
        }
        Configuration::updateValue('EC_LAPOSTE_TRANS_colissimo', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_colissimoR1', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_colissimoR2', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_colissimoR3', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_colissimoR4', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_colissimoR5', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_colissimoA', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_colissimoB', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_colissimoC', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_OM1', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_OM1eco', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_OM2', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_OM2eco', 0);
        Configuration::updateValue('EC_LAPOSTE_TRANS_posteLS', 0);
        return true;
    }

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

    
    public function majTransp($trans)
    {
        switch ($trans)
        {
            case 'colissimo':
                $type = 'colissimo';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.25', 'price' => '4.90'),
                    array( 'min' => '0.25', 'max' => '0.5', 'price' => '6.10'),
                    array( 'min' => '0.5', 'max' => '0.75', 'price' => '6.90'),
                    array( 'min' => '0.75', 'max' => '1', 'price' => '7.50'),
                    array( 'min' => '1', 'max' => '2', 'price' => '8.50'),
                    array( 'min' => '2', 'max' => '5', 'price' => '12.50'),
                    array( 'min' => '5', 'max' => '10', 'price' => '18.50'),
                    array( 'min' => '10', 'max' => '30', 'price' => '26.50'),
                );
                $id_country = 'IN (8,40,148)';
                $zone_name = $this->l('France métropolitaine');
                $carrier_name = $this->l('Colissimo France');
                $img_name = $this->l('colissimo');
                $delay = $this->l('Délais indicatifs de livraison sous 48 heures ouvrables en boîte à lettres.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'colissimoR1':
                $type = 'colissimoR1';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.25', 'price' => '7.40'),
                    array( 'min' => '0.25', 'max' => '0.5', 'price' => '8.60'),
                    array( 'min' => '0.5', 'max' => '0.75', 'price' => '9.40'),
                    array( 'min' => '0.75', 'max' => '1', 'price' => '10.00'),
                    array( 'min' => '1', 'max' => '2', 'price' => '11.00'),
                    array( 'min' => '2', 'max' => '5', 'price' => '15.00'),
                    array( 'min' => '5', 'max' => '10', 'price' => '21.00'),
                    array( 'min' => '10', 'max' => '30', 'price' => '29.00'),
                );
                $id_country = 'IN (8,40,148)';
                $zone_name = $this->l('France métropolitaine');
                $carrier_name = $this->l('Colissimo France Recommandation 1');
                $img_name = $this->l('colissimo');
                $delay = $this->l('Délais indicatifs de livraison sous 48 heures ouvrables contre signature avec indemnisation 50€.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'colissimoR2':
                $type = 'colissimoR2';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.25', 'price' => '8.90'),
                    array( 'min' => '0.25', 'max' => '0.5', 'price' => '10.10'),
                    array( 'min' => '0.5', 'max' => '0.75', 'price' => '10.90'),
                    array( 'min' => '0.75', 'max' => '1', 'price' => '11.50'),
                    array( 'min' => '1', 'max' => '2', 'price' => '12.50'),
                    array( 'min' => '2', 'max' => '5', 'price' => '14.50'),
                    array( 'min' => '5', 'max' => '10', 'price' => '22.50'),
                    array( 'min' => '10', 'max' => '30', 'price' => '30.50'),
                );
                $id_country = 'IN (8,40,148)';
                $zone_name = $this->l('France métropolitaine');
                $carrier_name = $this->l('Colissimo France Recommandation 2');
                $img_name = $this->l('colissimo');
                $delay = $this->l('Délais indicatifs de livraison sous 48 heures ouvrables contre signature avec indemnisation 200€.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'colissimoR3':
                $type = 'colissimoR3';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.25', 'price' => '9.50'),
                    array( 'min' => '0.25', 'max' => '0.5', 'price' => '10.70'),
                    array( 'min' => '0.5', 'max' => '0.75', 'price' => '11.50'),
                    array( 'min' => '0.75', 'max' => '1', 'price' => '12.10'),
                    array( 'min' => '1', 'max' => '2', 'price' => '13.10'),
                    array( 'min' => '2', 'max' => '5', 'price' => '17.10'),
                    array( 'min' => '5', 'max' => '10', 'price' => '23.10'),
                    array( 'min' => '10', 'max' => '30', 'price' => '31.10'),
                );
                $id_country = 'IN (8,40,148)';
                $zone_name = $this->l('France métropolitaine');
                $carrier_name = $this->l('Colissimo France Recommandation 3');
                $img_name = $this->l('colissimo');
                $delay = $this->l('Délais indicatifs de livraison sous 48 heures ouvrables contre signature avec indemnisation 400€.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'colissimoR4':
                $type = 'colissimoR4';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.25', 'price' => '10.70'),
                    array( 'min' => '0.25', 'max' => '0.5', 'price' => '11.90'),
                    array( 'min' => '0.5', 'max' => '0.75', 'price' => '12.70'),
                    array( 'min' => '0.75', 'max' => '1', 'price' => '13.30'),
                    array( 'min' => '1', 'max' => '2', 'price' => '14.30'),
                    array( 'min' => '2', 'max' => '5', 'price' => '18.30'),
                    array( 'min' => '5', 'max' => '10', 'price' => '24.30'),
                    array( 'min' => '10', 'max' => '30', 'price' => '32.30'),
                );
                $id_country = 'IN (8,40,148)';
                $zone_name = $this->l('France métropolitaine');
                $carrier_name = $this->l('Colissimo France Recommandation 4');
                $img_name = $this->l('colissimo');
                $delay = $this->l('Délais indicatifs de livraison sous 48 heures ouvrables contre signature avec indemnisation 600€.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'colissimoR5':
                $type = 'colissimoR5';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.25', 'price' => '11.90'),
                    array( 'min' => '0.25', 'max' => '0.5', 'price' => '13.10'),
                    array( 'min' => '0.5', 'max' => '0.75', 'price' => '13.90'),
                    array( 'min' => '0.75', 'max' => '1', 'price' => '14.50'),
                    array( 'min' => '1', 'max' => '2', 'price' => '15.50'),
                    array( 'min' => '2', 'max' => '5', 'price' => '19.50'),
                    array( 'min' => '5', 'max' => '10', 'price' => '25.50'),
                    array( 'min' => '10', 'max' => '30', 'price' => '33.50'),
                );
                $id_country = 'IN (8,40,148)';
                $zone_name = $this->l('France métropolitaine');
                $carrier_name = $this->l('Colissimo France Recommandation 5');
                $img_name = $this->l('colissimo');
                $delay = $this->l('Délais indicatifs de livraison sous 48 heures ouvrables contre signature avec indemnisation 800€.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'colissimoA':
                $type = 'colissimoA';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.5', 'price' => '12.15'),
                    array( 'min' => '0.5', 'max' => '1', 'price' => '14.85'),
                    array( 'min' => '1', 'max' => '2', 'price' => '16.50'),
                    array( 'min' => '2', 'max' => '5', 'price' => '21.20'),
                    array( 'min' => '5', 'max' => '10', 'price' => '35.00'),
                    array( 'min' => '10', 'max' => '30', 'price' => '58.00'),
                );
                $id_country = 'IN (1,2,3,6,7,9,10,12,13,14,15,16,17,18,19,20,26,36,37,74,76,86,125,131,139,143,193,236)';
                $zone_name = $this->l('International zone A');
                $carrier_name = $this->l('Colissimo International zone A');
                $img_name = $this->l('inter');
                $delay = $this->l('Délais indicatifs de livraison de 3 à 8 jours ouvrés en boîte à lettres.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'colissimoB':
                $type = 'colissimoB';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.5', 'price' => '16.20'),
                    array( 'min' => '0.5', 'max' => '1', 'price' => '19.35'),
                    array( 'min' => '1', 'max' => '2', 'price' => '21.05'),
                    array( 'min' => '2', 'max' => '5', 'price' => '27.00'),
                    array( 'min' => '5', 'max' => '10', 'price' => '45.00'),
                    array( 'min' => '10', 'max' => '20', 'price' => '70.00'),
                );
                $id_country = 'IN (23,38,45,47,52,89,93,97,101,107,109,114,116,130,133,147,152,150,177,186,190,210,211,216,230,233,244)';
                $zone_name = $this->l('International zone B');
                $carrier_name = $this->l('Colissimo International zone B');
                $img_name = $this->l('inter');
                $delay = $this->l('Délais indicatifs de livraison de 3 à 8 jours ouvrés en boîte à lettres.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'colissimoC':
                $type = 'colissimoC';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.5', 'price' => '23.70'),
                    array( 'min' => '0.5', 'max' => '1', 'price' => '26.30'),
                    array( 'min' => '1', 'max' => '2', 'price' => '36.10'),
                    array( 'min' => '2', 'max' => '5', 'price' => '53.00'),
                    array( 'min' => '5', 'max' => '10', 'price' => '100.00'),
                    array( 'min' => '10', 'max' => '20', 'price' => '160.00'),
                );
                $id_country = 'NOT IN (98,141,144,176,179,182,183,241,158,225,232,242,243,23,38,45,47,52,89,93,97,101,107,109,114,116,130,133,147,152,150,177,186,190,210,211,216,230,233,244,1,2,3,6,7,9,10,12,13,14,15,16,17,18,19,20,26,36,37,74,76,86,125,131,139,143,193,236,8,40,148)';
                $zone_name = $this->l('International zone C');
                $carrier_name = $this->l('Colissimo International zone C');
                $img_name = $this->l('inter');
                $delay = $this->l('Délais indicatifs de livraison de 3 à 8 jours ouvrés en boîte à lettres.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'OM1':
                $type = 'OM1';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.5', 'price' => '9.15'),
                    array( 'min' => '0.5', 'max' => '1', 'price' => '13.85'),
                    array( 'min' => '1', 'max' => '2', 'price' => '18.90'),
                    array( 'min' => '2', 'max' => '5', 'price' => '28.00'),
                    array( 'min' => '5', 'max' => '10', 'price' => '45.00'),
                    array( 'min' => '10', 'max' => '30', 'price' => '101.00'),
                );
                $id_country = 'IN (98,141,144,176,179,182,183,241)';
                $zone_name = $this->l('Outre Mer 1');
                $carrier_name = $this->l('Colissimo Outre Mer 1');
                $img_name = $this->l('outre');
                $delay = $this->l('Délais indicatifs de livraison sous 20 à 30 jours ouvrés en boîte à lettres.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'OM1eco':
                $type = 'OM1eco';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.5', 'price' => '8.50'),
                    array( 'min' => '0.5', 'max' => '1', 'price' => '11.00'),
                    array( 'min' => '1', 'max' => '2', 'price' => '13.50'),
                    array( 'min' => '2', 'max' => '5', 'price' => '20.90'),
                    array( 'min' => '5', 'max' => '10', 'price' => '30.80'),
                    array( 'min' => '10', 'max' => '30', 'price' => '68.90'),
                );
                $id_country = 'IN (98,141,144,176,179,182,183,241)';
                $zone_name = $this->l('Outre Mer 1');
                $carrier_name = $this->l('Colissimo Outre Mer 1 Economique');
                $img_name = $this->l('outre');
                $delay = $this->l('Délais indicatifs de livraison sous 5 à 7 jours ouvrés en boîte à lettres.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'OM2':
                $type = 'OM2';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.5', 'price' => '10.95'),
                    array( 'min' => '0.5', 'max' => '1', 'price' => '16.55'),
                    array( 'min' => '1', 'max' => '2', 'price' => '29.20'),
                    array( 'min' => '2', 'max' => '5', 'price' => '48.50'),
                    array( 'min' => '5', 'max' => '10', 'price' => '95.00'),
                    array( 'min' => '10', 'max' => '30', 'price' => '250.00'),
                );
                $id_country = 'IN (158,225,232,242,243)';
                $zone_name = $this->l('Outre Mer 2');
                $carrier_name = $this->l('Colissimo Outre Mer 2');
                $img_name = $this->l('outre');
                $delay = $this->l('Délais indicatifs de livraison sous 20 à 30 jours ouvrés en boîte à lettres.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'OM2eco':
                $type = 'OM2eco';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.5', 'price' => '10.80'),
                    array( 'min' => '0.5', 'max' => '1', 'price' => '16.30'),
                    array( 'min' => '1', 'max' => '2', 'price' => '29.00'),
                    array( 'min' => '2', 'max' => '5', 'price' => '48.00'),
                    array( 'min' => '5', 'max' => '10', 'price' => '94.50'),
                    array( 'min' => '10', 'max' => '30', 'price' => '248.00'),
                );
                $id_country = 'IN (158,225,232,242,243)';
                $zone_name = $this->l('Outre Mer 2');
                $carrier_name = $this->l('Colissimo Outre Mer 2 Economique');
                $img_name = $this->l('outre');
                $delay = $this->l('Délais indicatifs de livraison sous 5 à 7 jours ouvrés en boîte à lettres.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            case 'posteLS':
                $type = 'posteLS';
                $price_tab = array(
                    array( 'min' => '0', 'max' => '0.02', 'price' => '1.10'),
                    array( 'min' => '0.02', 'max' => '0.1', 'price' => '1.80'),
                    array( 'min' => '0.1', 'max' => '0.25', 'price' => '3.20'),
                    array( 'min' => '0.25', 'max' => '0.5', 'price' => '4.60'),
                    array( 'min' => '0.5', 'max' => '3.0', 'price' => '6.00'),
                );
                $id_country = 'IN (8,40,148)';
                $zone_name = $this->l('France métropolitaine');
                $carrier_name = $this->l('Lettre suivie La Poste France');
                $img_name = $this->l('poste');
                $delay = $this->l('Délais indicatifs de livraison sous 48 heures ouvrables en boîte à lettres.');
                $this->createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay);
                return 1;
            default:
                return 0;
        }
    }
    
    public function createCarrier($type, $price_tab, $id_country, $zone_name, $carrier_name, $img_name, $delay)
    {
        //Creation Zone si non existant
        if (Db::getInstance()->getValue('SELECT COUNT(name) FROM `'._DB_PREFIX_.'zone` WHERE name = "'.pSQL($zone_name).'"') == 0) {
            Db::getInstance()->Execute(
                'INSERT INTO `'._DB_PREFIX_.'zone` (`id_zone`, `name`, `active`) 
                VALUES ("", "'.pSQL($zone_name).'", 1)'
            );
            $newZone = Db::getInstance()->Insert_ID();
            foreach (Shop::getShops() as $shop) {
                Db::getInstance()->Execute(
                    'INSERT INTO `'._DB_PREFIX_.'zone_shop` (`id_zone`, `id_shop`) 
                    VALUES ('.(int)$newZone.', '.(int)$shop['id_shop'].')'
                );
            }
            //Affectation zone -> Pays
            Db::getInstance()->execute(
                'UPDATE `'._DB_PREFIX_.'country` 
                SET id_zone='.(int)$newZone.' 
                WHERE id_country '.pSQL($id_country)
            );
            //Affectation zone -> etat
            Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'state` SET id_zone='.(int)$newZone.' WHERE id_country '.pSQL($id_country));
        } else {
            $newZone = Db::getInstance()->getValue('SELECT id_zone FROM `'._DB_PREFIX_.'zone` WHERE name = "'.pSQL($zone_name).'"');
        }
        
        
        //Creation Transporteur si non existant
        if (Db::getInstance()->getValue('SELECT COUNT(name) FROM `'._DB_PREFIX_.'carrier` WHERE name = "'.pSQL($carrier_name).'" AND deleted = 0 ') == 0) {
            Db::getInstance()->Execute(
                'INSERT INTO `'._DB_PREFIX_.'carrier` 
                (`id_carrier`, `id_tax_rules_group`, `name`, `url`, `active`, `deleted`, `shipping_handling`, `range_behavior`, `is_module`, `is_free`, `shipping_external`, `need_range`, `external_module_name`, `shipping_method`) 
                VALUES ("", 0, "'.pSQL($carrier_name).'", "http://www.coliposte.net/particulier/suivi_particulier.jsp?colispart=@", 1, 0, 1, 1, 0, 0, 0, 0, NULL, 0)'
            );
            $newTransp = Db::getInstance()->Insert_ID();
            Db::getInstance()->Execute(
                'UPDATE `'._DB_PREFIX_.'carrier` 
                SET id_reference = '.(int)$newTransp.' 
                WHERE id_carrier = '.(int)$newTransp
            );
            foreach (Shop::getShops() as $shop) {
                DB::getInstance()->Execute(
                    'INSERT INTO `'._DB_PREFIX_.'carrier_shop` (`id_carrier`, `id_shop`) 
                    VALUES('.(int)$newTransp.', '.(int)$shop['id_shop'].')'
                );
            }
            Configuration::updateGlobalvalue('EC_LAPOSTE_TRANS_'.$type, (int)$newTransp);
        
            @copy('../modules/eclaposte/views/img/'.$img_name.'.jpg', '../img/s/'.$newTransp.'.jpg');
            
            $lstGroup = Db::getInstance()->ExecuteS('SELECT id_group FROM `'._DB_PREFIX_.'group`');
            foreach ($lstGroup as $grp) {
                Db::getInstance()->Execute(
                    'INSERT INTO `'._DB_PREFIX_.'carrier_group` (`id_carrier`, `id_group`) 
                    VALUES('.(int)$newTransp.', '.(int)$grp['id_group'].')'
                );
            }
            $lstLng = Db::getInstance()->ExecuteS('SELECT id_lang FROM `'._DB_PREFIX_.'lang`');
            foreach ($lstLng as $lng) {
                foreach (Shop::getShops() as $shop) {
                    Db::getInstance()->Execute(
                        'INSERT INTO `'._DB_PREFIX_.'carrier_lang` (`id_carrier`,`id_shop`, `id_lang`, `delay`) 
                        VALUES('.(int)$newTransp.','.(int)$shop['id_shop'].', '.(int)$lng['id_lang'].', "'.pSQL($delay).'")'
                    );
                }
            }
            Db::getInstance()->Execute(
                'INSERT INTO `'._DB_PREFIX_.'carrier_zone` (`id_carrier`, `id_zone`) 
                VALUES('.(int)$newTransp.', '.(int)$newZone.')'
            );
            
            //Creation des tranches de poids et prix
            foreach ($price_tab as $row) {
                Db::getInstance()->execute(
                    'INSERT INTO `'._DB_PREFIX_.'range_weight` (`id_range_weight`, `id_carrier`, `delimiter1`, `delimiter2`) 
                    VALUES("", '.(int)$newTransp.', '.(float)$row['min'].', '.(float)$row['max'].')'
                );
                $newRange = Db::getInstance()->Insert_ID();
                Db::getInstance()->execute(
                    'INSERT INTO `'._DB_PREFIX_.'delivery` (`id_delivery`, `id_carrier`, `id_range_price`, `id_range_weight`, `id_zone`, `price`) 
                    VALUES("", '.(int)$newTransp.', 0, '.(int)$newRange.', '.(int)$newZone.', '.(float)$row['price'].')'
                );
            }
        }
    }
    
    public function executeSQLFile($file)
    {
        $path = $this->repertoire_sav;
        if (!file_exists($path.'/'.$file)) {
            return (false);
        } else if (!$sql = Tools::file_get_contents($path.'/'.$file)) {
            return (false);
        }
        $sql = preg_split("/;\s*[\r\n]+/", str_replace('PREFIX_', _DB_PREFIX_, $sql));
        $db = Db::getInstance();
        foreach ($sql as $query) {
            $query = trim($query);
            if ($query) {
                if (!$db->Execute($query)) {
                    $this->_postErrors[] = $db->getMsgError().' '.$query;
                    return false;
                }
            }
        }
        return true;
    }
      
    
    public function getContent()
    {
        $html = '';
        
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            if (isset($this->context)) {
                $this->context->controller->addJS(($this->_path).'views/js/bootstrap.min.js');
                $this->context->controller->addJS(($this->_path).'views/js/jquery-1.11.1.min.js');
                
                $this->context->controller->addCSS(($this->_path).'views/css/bootstrap.min.css', 'all');
                $this->context->controller->addCSS(($this->_path).'views/css/bootstrap-theme.css', 'all');
                $this->context->controller->addCSS(($this->_path).'views/css/font-awesome.min.css', 'all');
                $this->context->controller->addCSS(($this->_path).'views/css/admin-theme.css', 'all');
                $this->context->controller->addCSS(($this->_path).'views/css/admin-15-14.css', 'all');
            } else {
                Tools::addJS(($this->_path).'views/js/boostrap.min.js');
                Tools::addJS(($this->_path).'views/js/jquery-1.11.1.min.js');
                
                Tools::addCSS(($this->_path).'views/css/bootstrap.min.css', 'all');
                Tools::addCSS(($this->_path).'views/css/bootstrap-theme.css', 'all');
                Tools::addCSS(($this->_path).'views/css/font-awesome.min.css', 'all');
                Tools::addCSS(($this->_path).'views/css/admin-theme.css', 'all');
                Tools::addCSS(($this->_path).'views/css/admin-15-14.css', 'all');
            }
        }
        
        $html .= '<div class="bootstrap" id="ec_content">';
        if (isset($this->context)) {
            $this->context->controller->addJS($this->_path.'views/js/function.js');
        } else {
            Tools::addJS($this->_path.'views/js/function.js');
        }
        
        if (Tools::getValue('valider')) {
            while (list($key, $val) = each($_POST)) {
                Configuration::updateGlobalValue('EC_LAPOSTE_'.$key, $val);
                if ($val == 1) {
                    if (Configuration::get('EC_LAPOSTE_TRANS_'.$key) == 0) {
                        $this->majTransp($key);
                    } else {
                        Db::getInstance()->execute(
                            'UPDATE `'._DB_PREFIX_.'carrier` 
                            SET active=1 WHERE id_carrier="'.(int)Configuration::get('EC_LAPOSTE_TRANS_'.$key).'"'
                        );
                    }
                } else {
                    Db::getInstance()->execute(
                        'UPDATE `'._DB_PREFIX_.'carrier` 
                        SET active=0 WHERE id_carrier="'.(int)Configuration::get('EC_LAPOSTE_TRANS_'.$key).'"'
                    );
                }
            }
            $html .= $this->displayConfirmation($this->l('Carrier update'));
        }
        if (Tools::getValue('backupSpe')) {
            $this->backUp();
            $html .= $this->displayConfirmation($this->l('Backup OK'));
        }
        if (Tools::getValue('delB')) {
            unlink($this->repertoire_sav.'/'.Tools::getValue('delB'));
            $html .= $this->displayConfirmation($this->l('Backup delete'));
        }
        if (Tools::getValue('resB')) {
            $this->executeSQLFile(Tools::getValue('resB'));
            $html .= $this->displayConfirmation($this->l('Backup restore'));
        }
        $html .= $this->displayUpdate();
        $html .= $this->displaySave();
        $html .= $this->displaySaveTab();
        return $html;
    }
    
    public function displayUpdate()
    {
        $tab_content = array(
            array('name'=>$this->l('Colissimo France'),'id'=>'colissimo'),
            array('name'=>$this->l('Colissimo France Recommandation 1'),'id'=>'colissimoR1'),
            array('name'=>$this->l('Colissimo France Recommandation 2'),'id'=>'colissimoR2'),
            array('name'=>$this->l('Colissimo France Recommandation 3'),'id'=>'colissimoR3'),
            array('name'=>$this->l('Colissimo France Recommandation 4'),'id'=>'colissimoR4'),
            array('name'=>$this->l('Colissimo France Recommandation 5'),'id'=>'colissimoR5'),
            array('name'=>$this->l('Colissimo International zone A'),'id'=>'colissimoA'),
            array('name'=>$this->l('Colissimo International zone B'),'id'=>'colissimoB'),
            array('name'=>$this->l('Colissimo International zone C'),'id'=>'colissimoC'),
            array('name'=>$this->l('Colissimo Outre Mer 1'),'id'=>'OM1'),
            array('name'=>$this->l('Colissimo Outre Mer 1 Economique'),'id'=>'OM1eco'),
            array('name'=>$this->l('Colissimo Outre Mer 2'),'id'=>'OM2'),
            array('name'=>$this->l('Colissimo Outre Mer 2 Economique'),'id'=>'OM2eco'),
            array('name'=>$this->l('Lettre suivie La Poste France'),'id'=>'posteLS'),
        );
        $tab_switch = array();
        foreach ($tab_content as $content) {
            $tab_switch[] = array(
                'type' => (version_compare(_PS_VERSION_, '1.6', '>=')?'switch':'radio'),
                'label' => $content['name'],
                'name' => $content['id'],
                'is_bool' => true,
                'class' => 't',
                'values' => array(
                    array(
                        'id' => 'active_on',
                        'value' => 1,
                        'label' => $this->l('Enabled'),
                    ),
                    array(
                        'id' => 'active_off',
                        'value' => 0,
                        'label' => $this->l('Disabled'),
                    )
                ),
            );
        }
        $fields_form = array();
        $fields_form[0]['form'] = array(
            'legend' => array(
                'title' => $this->displayName,
                'icon' => 'icon-cogs',
            ),
            'input' => $tab_switch,
            'submit' => array(
                'title' => $this->l('Update'),
                'class' => 'btn btn-default pull-right',
                'icon' => 'process-icon-refresh'
            )
        );
        $helper = new HelperForm();
        $helper->module = $this;
        $helper->name_controller = $this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
        $helper->title = 'configuration';
        $helper->show_toolbar = true;
        $helper->toolbar_scroll = true;
        $helper->submit_action = 'valider';
        $helper->toolbar_btn = array(
            'save' => array(
                'desc' => $this->l('Save'),
                'href' => AdminController::$currentIndex.'&configure='.$this->name.'&valider&token='.Tools::getAdminTokenLite('AdminModules'),
            ),
        );
        $helper->tpl_vars = array('base_url' => $this->context->shop->getBaseURL());
        foreach ($tab_content as $content) {
            $helper->fields_value[$content['id']] = Configuration::get('EC_LAPOSTE_'.$content['id']);
        }
        return $helper->generateForm($fields_form);
    }
    
    public function displaySave()
    {
        $fields_form = array();
        $fields_form[0]['form'] = array(
            'legend' => array(
                'title' => $this->l('Before doing any change, save your current carrier settings'),
                'icon' => 'icon-cogs',
            ),
            'submit' => array(
                'title' => $this->l('Save'),
                'class' => 'btn btn-default pull-right',
                'icon' => 'process-icon-save'
            )
        );
        $helper = new HelperForm();
        $helper->module = $this;
        $helper->name_controller = $this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
        $helper->title = 'configuration';
        $helper->show_toolbar = true;
        $helper->toolbar_scroll = true;
        $helper->submit_action = 'backupSpe';
        $helper->toolbar_btn = array(
            'save' => array(
                'desc' => $this->l('Save'),
                'href' => AdminController::$currentIndex.'&configure='.$this->name.'&backupSpe&token='.Tools::getAdminTokenLite('AdminModules'),
            ),
        );
        $helper->tpl_vars = array('base_url' => $this->context->shop->getBaseURL());
        return $helper->generateForm($fields_form);
    }
    
    public function displaySaveTab()
    {
        try {
            $dir = opendir($this->repertoire_sav);
            $listfiles = array();
            while ($file = readdir($dir)) {
                if ($file != '.' && $file != '..' && !is_dir($this->repertoire_sav.$file)) {
                    $linkres = AdminController::$currentIndex.'&configure='.$this->name.'&resB='.$file.'&token='.Tools::getAdminTokenLite('AdminModules');
                    $linkdel =AdminController::$currentIndex.'&configure='.$this->name.'&delB='.$file.'&token='.Tools::getAdminTokenLite('AdminModules');
                    $listfiles[]=array($file,$linkres,$linkdel);
                }
            }
            closedir($dir);
        } catch (MyException $e) {
            $e->getMessage();
        }
     
        $this->smarty->assign(array(
              'listfiles' => $listfiles,
              ));
        return $this->display(__FILE__, '/views/templates/admin/savetab.tpl');
    }
    
    private function backUp()
    {
        $repertoire_sav = $this->repertoire_sav;
        @ob_start();
        $table = "";
        $tb = "";
        $nom_bd = _DB_NAME_;
        $date_sauvegarde = date('Y-m-d H:i:s');
        $nom_save = "bd_".time()."_";
        $nom_save .= date('Y-m-d');
        $nom_save .= ".sql";
        $crlf = "\n";
        $strTableStructure        = "Table structure for table";
        $strDumpingData         = "Dumping data for table";
        $sauvegarde = "# ---- BD: $nom_bd    ------------------------------$crlf";
        $sauvegarde .= "# ---- Date de la sauvegarde : $date_sauvegarde    ----------------$crlf";
        $tables = array(
            0 => _DB_PREFIX_.'carrier_lang',
            1 => _DB_PREFIX_.'zone',
            2 => _DB_PREFIX_.'country',
            3 => _DB_PREFIX_.'carrier',
            4 => _DB_PREFIX_.'carrier_group',
            5 => _DB_PREFIX_.'carrier_zone',
            6 => _DB_PREFIX_.'range_weight',
            7 => _DB_PREFIX_.'delivery',
            8 => _DB_PREFIX_.'carrier_shop',
            9 => _DB_PREFIX_.'zone_shop',
            10 => _DB_PREFIX_.'state'
        );
        foreach ($tables as $table) {
            if ($tb) {
                if ($table == $tb) {
                    $sauvegarde .=    $crlf;
                    $sauvegarde .=    "# --------------------------------------------------------$crlf";
                    $sauvegarde .=    "#$crlf";
                    $sauvegarde .=    "# $strTableStructure '$table'$crlf";
                    $sauvegarde .=    "#$crlf";
                    $sauvegarde .=    $crlf;
                    $sauvegarde .=    $this->getTableDef($table, $crlf).";$crlf$crlf";
                    $sauvegarde .=    "#$crlf";
                    $sauvegarde .=    "# $strDumpingData '$table'$crlf";
                    $sauvegarde .=    "#$crlf";
                    $sauvegarde .=    $crlf;
                    $this->getTableContent($table, "myHandler");
                    exit ;
                }
            } else {
                $sauvegarde .= $crlf;
                $sauvegarde .= "# --------------------------------------------------------$crlf";
                $sauvegarde .= "#$crlf";
                $sauvegarde .= "# $strTableStructure '$table'$crlf";
                $sauvegarde .= "#$crlf";
                $sauvegarde .= $crlf;
            
                $sauvegarde .= $this->getTableDef($table, $crlf).";$crlf$crlf";
            
                $sauvegarde .= "#$crlf";
                $sauvegarde .= "# $strDumpingData '$table'$crlf";
                $sauvegarde .= "#$crlf";
                $sauvegarde .= $crlf;
            
                $this->getTableContent($table, "myHandler");
            }
        }
            
        // enregistrer le save
        $sauvegarde .= @ob_get_clean();
        
        // patch bug CURENT_TIMESTAMP
        $sauvegarde .= str_replace("DEFAULT 'CURRENT_TIMESTAMP'", "DEFAULT CURRENT_TIMESTAMP", $sauvegarde);
        
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_colissimo').' WHERE name="EC_LAPOSTE_TRANS_colissimo";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_colissimoR1').' WHERE name="EC_LAPOSTE_TRANS_colissimoR1";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_colissimoR2').' WHERE name="EC_LAPOSTE_TRANS_colissimoR2";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_colissimoR3').' WHERE name="EC_LAPOSTE_TRANS_colissimoR3";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_colissimoR4').' WHERE name="EC_LAPOSTE_TRANS_colissimoR4";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_colissimoR5').' WHERE name="EC_LAPOSTE_TRANS_colissimoR5";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_colissimoA').' WHERE name="EC_LAPOSTE_TRANS_colissimoA";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_colissimoB').' WHERE name="EC_LAPOSTE_TRANS_colissimoB";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_colissimoC').' WHERE name="EC_LAPOSTE_TRANS_colissimoC";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_OM1').' WHERE name="EC_LAPOSTE_TRANS_OM1";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_OM1eco').' WHERE name="EC_LAPOSTE_TRANS_OM1eco";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_OM2').' WHERE name="EC_LAPOSTE_TRANS_OM2";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_OM2eco').' WHERE name="EC_LAPOSTE_TRANS_OM2eco";';
        $sauvegarde .= ";$crlf$crlf";
        $sauvegarde .= 'UPDATE `'._DB_PREFIX_.'configuration` SET value='.Configuration::get('EC_LAPOSTE_TRANS_posteLS').' WHERE name="EC_LAPOSTE_TRANS_posteLS";';

        $nom_fichier = "$repertoire_sav/$nom_save";
        $fd = fopen($nom_fichier, "w+");
        fwrite($fd, $sauvegarde);
        fclose($fd);
    }
      
    private function getTableDef($table, $crlf)
    {
        $index = array();
        $schema_create = "";
        $schema_create .= "DROP TABLE IF EXISTS $table;$crlf";
        $schema_create .= "CREATE TABLE IF NOT EXISTS $table ($crlf";
        $result = Db::getInstance()->ExecuteS("SHOW FIELDS FROM $table");
        foreach ($result as $row) {
            $schema_create .= "    $row[Field] $row[Type]";
            if (isset($row["Default"]) && (!empty($row["Default"]) || $row["Default"] == "0")) {
                $schema_create .= " DEFAULT '$row[Default]'";
            }
            if ($row["Null"] != "YES") {
                $schema_create .= " NOT NULL";
            }
            if ($row["Extra"] != "") {
                $schema_create .= " $row[Extra]";
            }
            $schema_create .= ",$crlf";
        }
        $schema_create = preg_replace("/,".$crlf."$/", "", $schema_create);
        $result = Db::getInstance()->ExecuteS("SHOW KEYS FROM $table");
        foreach ($result as $row) {
            $kname = $row['Key_name'];
            if (($kname != "PRIMARY") && ($row['Non_unique'] == 0)) {
                $kname = "UNIQUE|$kname";
            }
            if (!isset($index[$kname])) {
                $index[$kname] = array();
            }
            $index[$kname][] = $row['Column_name'];
        }
        while (list($x, $columns) = @each($index)) {
            $schema_create .= ",$crlf";
            if ($x == "PRIMARY") {
                $schema_create .= " PRIMARY KEY (".implode($columns, ", ").")";
            } elseif (Tools::substr($x, 0, 6) == "UNIQUE") {
                $schema_create .= " UNIQUE ".Tools::substr($x, 7)." (".implode($columns, ", ").")";
            } else {
                $schema_create .= " KEY $x (".implode($columns, ", ").")";
            }
        }
        $schema_create .= "$crlf)";
        return (Tools::stripslashes($schema_create));
    }
      
    private function getTableContent($table, $handler)
    {
        $dns = 'mysql:host='._DB_SERVER_.';dbname='._DB_NAME_;
        $connection = new PDO($dns, _DB_USER_, _DB_PASSWD_);
        $result = $connection->query("SELECT * FROM ".$table);
        $i = 0;
        $result->setFetchMode(PDO::FETCH_NUM);
        while ($row = $result->fetch()) {
            $table_list = "(";
            for ($j = 0; $j < $result->ColumnCount(); $j++) {
                $tab = $result->getColumnMeta($j);
                $table_list .= $tab['name'].", ";
            }
            $table_list = Tools::substr($table_list, 0, -2);
            $table_list .= ")";
        
            if (isset($GLOBALS["showcolumns"])) {
                $schema_insert = "INSERT INTO ".$table." ".$table_list." VALUES (";
            } else {
                $schema_insert = "INSERT INTO ".$table." VALUES (";
            }
            for ($j = 0; $j < $result->ColumnCount(); $j++) {
                if (!isset($row[$j])) {
                    $schema_insert .= " NULL,";
                } elseif ($row[$j] != "") {
                    $schema_insert .= " '".addslashes($row[$j])."',";
                } else {
                    $schema_insert .= " '',";
                }
            }
            $schema_insert = preg_replace("/,$/", "", $schema_insert);
            $schema_insert .= ");";
            $this->$handler(trim($schema_insert));
            $i++;
        }
        return (true);
    }
      
    private function myHandler($sql_insert)
    {
        $crlf = "\n";
        echo $sql_insert.$crlf;
    }
}
