HEX
Server: Apache
System: Linux srv13.cpanelhost.cl 3.10.0-962.3.2.lve1.5.38.el7.x86_64 #1 SMP Thu Jun 18 05:28:41 EDT 2020 x86_64
User: cca63905 (4205)
PHP: 7.3.20
Disabled: NONE
Upload Files
File: /home4/cca63905/www/nueva/modules/roja45quotationsprofree/roja45quotationsprofree.php
<?php
/**
 * Roja45QuotationsProFree.
 *
 * @author    Roja45
 * @copyright 2016 Roja45
 * @license   license.txt
 * @category  Roja45QuotationsProFree
 *
 * 2016 ROJA45 - All rights reserved.
 *
 * DISCLAIMER
 * Changing this file will render any support provided by us null and void.
 */

/**
 * Roja45QuotationsProFree.
 *
 * @author    Roja45
 * @copyright 2016 Roja45
 * @license   license.txt
 * @category  Class
 *
 * 2016 ROJA45 - All rights reserved.
 *
 * DISCLAIMER
 * Changing this file will render any support provided by us null and void.
 */

spl_autoload_register(function ($class_name) {
    if (file_exists(_PS_MODULE_DIR_ . 'roja45quotationsprofree/classes/' . $class_name . '.php')) {
        require_once _PS_MODULE_DIR_ . 'roja45quotationsprofree/classes/' . $class_name . '.php';
    } elseif (0 === strpos($class_name, 'Html2Text')) {
        if (file_exists(_PS_MODULE_DIR_ . 'roja45quotationsprofree/vendor/Html2Text/' . $class_name . '.php')) {
            require_once _PS_MODULE_DIR_ . 'roja45quotationsprofree/vendor/Html2Text/' . $class_name . '.php';
        }
    } elseif (Tools::substr($class_name, 0, 10) == 'ReCaptcha\\') {
        $class = str_replace('\\', '/', $class_name);
        $path = dirname(_PS_MODULE_DIR_ . 'roja45quotationsprofree/vendor/ReCaptcha').'/'.$class.'.php';
        if (is_readable($path)) {
            require_once $path;
        }
    } else {
        return;
    }
});

class Roja45QuotationsProFree extends Module
{
    const TOPIC = 'UNSET';
    const DEFAULT_PRECISION = 6;
    public $html;
    protected static $cache_enabled;

    public function __construct()
    {
        $this->name = 'roja45quotationsprofree';
        $this->tab = 'specialized_platforms';
        $this->version = '1.2.12';
        $this->author = 'Roja45';
        $this->source = 'Roja45';
        $this->is_eu_compatible = 1;
        $this->need_instance = 1;
        $this->bootstrap = true;
        $this->tabClassName = 'AdminQuotationsPro';

        parent::__construct();

        $this->displayName = $this->l('Roja45: Quotations Pro [FREE]');
        $this->description = $this->l('Enable product quotations for customers with custom forms and quotation response system. [FREE VERSION]');
        $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
        $this->confirmUninstall = $this->l('Are you sure you want to delete all saved details?');
        $this->secure_key = Tools::encrypt($this->name);
        $this->module_key = 'd88ff1bf238941b1c79d71246d5264b6';
        $this->author_address = '0xF3D82474F7BE4238658Bac2a21e8aD338B86447f';
        RojaFortyFiveQuotationsProCore::validateUpdate(
            $this->name,
            $this->version,
            $this->source,
            Configuration::get('ROJA45_ORDERREF')
        );
    }

    public function install()
    {
        if (!parent::install()
            || !$this->registerHooks()
            || !$this->installDb()
            || !$this->installTabs()
            || !$this->setGlobalVars()
            || !$this->populateDefaultData()
        ) {
            $this->uninstallDb();
            parent::uninstall();
            return false;
        }

        return true;
    }

    public function uninstall()
    {
        if (!$this->uninstallDb()
            || !$this->uninstallTabs()
            || !$this->removeGlobalVars()
            || !parent::uninstall()
        ) {
            return false;
        }

        return true;
    }

    public function getContent()
    {
        $this->html = RojaFortyFiveQuotationsProCore::renderHeader($this);
        $this->processSubmit();
        $this->html .= $this->renderModuleForm();
        $this->html .= RojaFortyFiveQuotationsProCore::renderFooter($this);
        return $this->html;
    }

    public function renderWidget($hookName = null, array $configuration = [])
    {
        if ($hookName == null && isset($configuration['hook'])) {
            $hookName = $configuration['hook'];
        }

        $this->getWidgetVariables($hookName, $configuration);
        return $this->fetch('module:'.$this->name.'/views/templates/hook/PS17_'.$hookName.'.tpl');
    }

    public function getWidgetVariables($hookName = null, array $configuration = [])
    {
        if (preg_match('/^displayProductButtons\d*$/', $hookName)) {
            if (!is_array($configuration['product'])) {
                $id_product = $configuration['product']->id;
                $id_product_attribute = 0;
                $minimal_quantity = $configuration['product']->minimal_quantity;
                $product = new Product($id_product);
                $attributes_groups = $product->getAttributesGroups($this->context->language->id);
                if (is_array($attributes_groups) && $attributes_groups) {
                    foreach ($attributes_groups as $row) {
                        if ($row['default_on']) {
                            $id_product_attribute = (int)$row['id_product_attribute'];
                            $minimal_quantity = (int)$row['minimal_quantity'];
                        }
                    }
                }
            } else {
                $id_product = $configuration['product']['id_product'];
                $id_product_attribute = $configuration['product']['id_product_attribute'];
                $product = new Product($id_product);
                $minimal_quantity =  $configuration['product']['minimal_quantity'];
            }
            if (in_array($id_product, Roja45QuotationsProFree::cacheEnabled())) {
                $this->smarty->assign(array(
                    'roja45_quotation_useajax' => Configuration::get('ROJA45_QUOTATIONSPRO_USEAJAX'),
                    'roja45_quotation_enablequotecart' => Configuration::get('ROJA45_QUOTATIONSPRO_ENABLEQUOTECART'),
                    'product' => $product,
                    'id_product_attribute' => $id_product_attribute,
                    'minimal_quantity' => $minimal_quantity,
                ));
            }
        } elseif (preg_match('/^displayNav\d*$/', $hookName)) {
            $request = QuotationRequest::getInstance();
            $products = $request->getProducts();
            $request_link = $this->context->link->getModuleLink(
                'roja45quotationsprofree',
                'QuotationsProFront',
                array(
                    'action' => 'quoteSummary'
                )
            );
            $this->smarty->assign(
                array(
                    'roja45quotationspro_enable_inquotenotify' => 1,
                    'roja45_quotation_enablequotecart' => Configuration::get('ROJA45_QUOTATIONSPRO_ENABLEQUOTECART'),
                    'request_link' => $request_link,
                    'nbr_products' => count($products),
                    'products' => $products,
                    'request_qty' => QuotationRequest::getNumberOfProducts($request->id)
                )
            );
            Media::addJsDef(array(
                'generated_date' => time(),
            ));

            Media::addJsDefL('customizationIdMessage', $this->l('Customization #'));
            Media::addJsDefL('removingLinkText', $this->l('remove this product from my cart\''));
            Media::addJsDefL('freeShippingTranslation', $this->l('Free shipping!'));
            Media::addJsDefL('freeProductTranslation', $this->l('Free!'));
            Media::addJsDefL('delete_txt', $this->l('Delete'));
            Media::addJsDefL('toBeDetermined', $this->l('To be determined'));
        } elseif (preg_match('/^displayProductListAddToQuoteButton\d*$/', $hookName)) {
            $min_quantity = 1;
            if (
                isset($configuration['product']->product_attribute_minimal_quantity) &&
                $configuration['product']->product_attribute_minimal_quantity >= 1
            ) {
                $min_quantity = $configuration['product']->product_attribute_minimal_quantity;
            }

            $this->smarty->assign(
                array(
                    'min_quantity' => $min_quantity,
                    'product' => $configuration['product']
                )
            );
        } elseif (preg_match('/^displayEnabledIndicator\d*$/', $hookName)) {
            $this->smarty->assign(array(
                'product' => $configuration['product'],
            ));
        } elseif (preg_match('/^displayRoja45ProductList\d*$/', $hookName)) {
            $minimum_quantity = 1;
            if (
                isset($configuration['product']['product_attribute_minimal_quantity']) &&
                $configuration['product']['product_attribute_minimal_quantity'] >= 1
            ) {
                $minimum_quantity = (int)  $configuration['product']['product_attribute_minimal_quantity'];
            }

            $this->smarty->assign(
                array(
                    'id_language' => $this->context->language->id,
                    'product' => $configuration['product'],
                    'roja45_quotation_enablequotecart' => Configuration::get('ROJA45_QUOTATIONSPRO_ENABLEQUOTECART'),
                    'id_product' => $configuration['product']['id_product'],
                    'id_product_attribute' => $configuration['product']['id_product_attribute'],
                    'minimum_quantity' => $minimum_quantity,
                )
            );
        } elseif (preg_match('/^displayCustomerAccount\d*$/', $hookName)) {
            $this->smarty->assign(
                array(
                    'id_language' => $this->context->language->id,
                    'account_link' => $this->context->link->getModuleLink(
                        'roja45quotationsprofree',
                        'QuotationsProFront',
                        array(
                            'action' => 'getCustomerQuotes'
                        )
                    )
                )
            );
        } else {
        }
    }

    public function clearCache()
    {
        $this->_clearCache('displayFooter.tpl');
        $this->_clearCache('displayRoja45QuotationDialog.tpl');
        $this->_clearCache('displayShoppingCartFooter.tpl');
        $this->_clearCache('displayProductButtons.tpl');
        $this->_clearCache('displayBackOfficeTop.tpl');
        $this->_clearCache('displayEnabledIndicator.tpl');
        $this->_clearCache('my-account.tpl');
    }

    public static function cacheEnabled()
    {
        if (!isset(Roja45QuotationsProFree::$cache_enabled)) {
            $product_ids = array();
            $sql = 'SELECT id_product FROM `' . _DB_PREFIX_ . 'product_quotationspro` WHERE enabled = 1';

            if ($results = Db::getInstance()->executeS($sql)) {
                foreach ($results as $row) {
                    $product_ids[$row['id_product']] = $row['id_product'];
                }
                Roja45QuotationsProFree::$cache_enabled = $product_ids;
                return  Roja45QuotationsProFree::$cache_enabled;
            } else {
                return array();
            }
        }

        if (Roja45QuotationsProFree::$cache_enabled=== false || empty(Roja45QuotationsProFree::$cache_enabled)) {
            return array();
        } else {
            return Roja45QuotationsProFree::$cache_enabled;
        }
    }

    public function hookDisplayHeader($params)
    {
        $page = $this->context->controller->php_self;
        if (!$page) {
            $page = $this->context->controller->page_name;
        }
        if (!$page) {
            return;
        } elseif ($page == 'pagenotfound') {
            return;
        }

        if (version_compare(_PS_VERSION_, '1.7', '>=') == true) {
            $this->context->controller->addJqueryPlugin('growl');
            $this->context->controller->addJqueryUI('ui.effect');
            $this->context->controller->addJS($this->_path . 'views/js/roja45quotationspro17.js');
            $this->context->controller->addJS($this->_path . 'views/js/roja45quotationspro_cart17.js');
            $this->context->controller->addCSS($this->_path . 'views/css/roja45quotationspro17.css', 'all');
            $this->context->controller->addJS($this->_path . 'views/js/validate.js');
            if ((int)Configuration::get('ROJA45_QUOTATIONSPRO_ENABLEQUOTECART')) {
                // $this->context->controller->addJS($this->_path . 'views/js/roja45quotationspro_cart17.js');
            }
        } else {
            $this->context->controller->addCSS($this->_path . 'views/css/roja45quotationsprofree.css', 'all');
            $this->context->controller->addJS($this->_path . 'views/js/roja45quotationsprofree.js');
            $this->context->controller->addJqueryPlugin('growl');
            $this->context->controller->addJqueryUI('ui.effect');
            $this->context->controller->addJqueryUI('ui.datepicker');
            $this->context->controller->addJS($this->_path . 'views/js/validate.js');
            if ((int)Configuration::get('ROJA45_QUOTATIONSPRO_ENABLEQUOTECART')) {
                $this->context->controller->addJS($this->_path . 'views/js/roja45quotationspro_cart.js');
            }
        }
        $this->smarty->assign(
            array(
                'roja45_use_quote_cart' => (int)Configuration::get('ROJA45_QUOTATIONSPRO_ENABLEQUOTECART'),
            )
        );

        if ($page == 'order' || $page == 'order-opc') {
            $roja45_in_cart = (int) RojaFortyFiveQuotationsProCore::getCustomerRequirement('ROJA45QUOTATIONSPRO_QUOTEINCART');
            $roja45_quote_modified = (int) RojaFortyFiveQuotationsProCore::getCustomerRequirement('ROJA45QUOTATIONSPRO_QUOTEMODIFIED');

            if ($roja45_quote_modified && !(int)Configuration::get('ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION')) {
                $id_roja45_quotation = RojaFortyFiveQuotationsProCore::getCustomerRequirement('ROJA45QUOTATIONSPRO_ID_QUOTATION');
                $quotation = new RojaQuotation($id_roja45_quotation);
                $products = $quotation->getQuotationProductList();
                foreach ($products as $product) {
                    $this->context->cart->deleteProduct($product['id_product'], $product['id_product_attribute']);
                    $quotationProduct = new QuotationProduct($product['id_roja45_quotation_product']);
                    if ($quotationProduct->id_specific_price) {
                        $specific_price = new SpecificPrice($quotationProduct->id_specific_price);
                        $specific_price->delete();
                    }
                }
            }
            $this->context->controller->addJS($this->_path . 'views/js/roja45quotationspro_order.js');
            Media::addJsDef(array(
                'roja45quotationspro_allow_modifications' => (int) Configuration::get(
                    'ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION'
                ),
                'roja45quotationspro_cart_modified' => $roja45_quote_modified,
                'roja45quotationspro_in_cart' => $roja45_in_cart,
            ));
        } else {
            if (in_array($this->context->controller->php_self, array('index', 'category'))) {
                $cart = $this->context->cart;
                $id = RojaQuotation::getQuotationsForCart($cart->id);
                if (count($id)) {
                    $quotation = new RojaQuotation($id[0]['id_roja45_quotation']);
                    if (Validate::isLoadedObject($quotation)) {
                        if ($quotation->modified) {
                            $products = $quotation->getQuotationProductList();
                            foreach ($products as $product) {
                                if ($product['id_specific_price']) {
                                    $specific_price = new SpecificPrice($product['id_specific_price']);
                                    $specific_price->delete();
                                    $quotation_product = new QuotationProduct($product['id_roja45_quotation_product']);
                                    $quotation_product->id_specific_price = 0;
                                    $quotation_product->save();
                                }
                            }
                            $discounts = $quotation->getQuotationChargeList(QuotationCharge::$DISCOUNT);
                            foreach ($discounts as $discount) {
                                if ($discount['id_cart_rule']) {
                                    $cart_rule = new CartRule($discount['id_cart_rule']);
                                    $cart_rule->delete();
                                    $quotation_discount = new QuotationCharge($discount['id_roja45_quotation_charge']);
                                    $quotation_discount->id_cart_rule = 0;
                                    $quotation_discount->save();
                                }
                            }
                        }
                    }
                }
            } else {
                if (in_array($this->context->controller->php_self, array('product'))) {
                    // $id_product = Tools::getValue('id_product');
                }
            }
        }

        $controller_url = $this->context->link->getModuleLink(
            'roja45quotationsprofree',
            'QuotationsProFront',
            array(
                'token' => Tools::getToken(false)
            )
        );

        Media::addJsDef(array(
        'roja45quotationspro_controller' => $controller_url,
        'roja45quotationspro_enabled' => Tools::jsonEncode(Roja45QuotationsProFree::cacheEnabled()),
        'roja45quotationspro_change_qty' => (int)Configuration::get('ROJA45_QUOTATIONSPRO_QTY_CART_PRODUCTS'),
        'roja45quotationspro_delete_products' => (int)Configuration::get('ROJA45_QUOTATIONSPRO_DELETE_CART_PRODUCTS'),
        'roja45quotationspro_enable_captcha' => (int)Configuration::get('ROJA45_QUOTATIONSPRO_ENABLE_CAPTCHA'),
        'roja45quotationspro_enable_invisiblecaptcha' => (int)Configuration::get('ROJA45_QUOTATIONSPRO_ENABLE_INVISIBLECAPTCHA'),
        'roja45quotationspro_recaptcha_site_key' => (int)Configuration::get('ROJA45_QUOTATIONSPRO_RECAPTCHA_SITE'),
        'roja45quotationspro_enable_js' => (int)Configuration::get('ROJA45_QUOTATIONSPRO_USEJS'),
        'roja45quotationspro_enable_ajax' => (int)Configuration::get('ROJA45_QUOTATIONSPRO_USEAJAX'),
        'roja45quotationspro_enable_inquotenotify' => 1,
        'roja45quotationspro_enablequotecart' => (int)Configuration::get('ROJA45_QUOTATIONSPRO_ENABLEQUOTECART'),
        'roja45quotationspro_show_label' => (int)Configuration::get('ROJA45_QUOTATIONSPRO_DISPLAY_LABEL'),
        'roja45quotationspro_catalog_mode' => (int)Configuration::get('PS_CATALOG_MODE'),
        'roja45quotationspro_request_buttons' => Configuration::get('ROJA45_QUOTATIONSPRO_REQUEST_BUTTONS'),
        'roja45quotationspro_label_position' => Configuration::get('ROJA45_QUOTATIONSPRO_DISPLAY_LABEL_POSITION'),
    ));

        Media::addJsDefL('roja45quotationspro_quote_link_text', $this->l('Get A Quote'));
        Media::addJsDefL('roja45quotationspro_button_addquote', $this->l('Get A Quote'));
        Media::addJsDefL('roja45quotationspro_button_text', $this->l('Request Quote'));
        Media::addJsDefL('roja45quotationspro_cartbutton_text', $this->l('Add To Quote'));
        Media::addJsDefL('roja45quotationspro_success_title', $this->l('Success'));
        Media::addJsDefL('roja45quotationspro_warning_title', $this->l('Warning'));
        Media::addJsDefL('roja45quotationspro_error_title', $this->l('Error'));
        Media::addJsDefL('roja45quotationspro_notice_title', $this->l('NEW QUOTE AVAILABLE'));
        Media::addJsDefL('roja45quotationspro_notice_link_text', $this->l('CLICK HERE TO VIEW'));
        Media::addJsDefL('roja45quotationspro_quote_modified', $this->l(
            'Your cart has changed, you can request a new quote or reload an existing quote by clicking the link below.'
        ));
        Media::addJsDefL('roja45quotationspro_new_quote_available', $this->l('A new quotation is available in your account.'));
        Media::addJsDefL('roja45quotationspro_button_text_2', $this->l('Request New Quote'));
        Media::addJsDefL('roja45quotationspro_sent_success', $this->l('Request received, we will be in touch shortly. Thank You.'));
        Media::addJsDefL('roja45quotationspro_added_success', $this->l('Product added to your request successfully.'));
        Media::addJsDefL('roja45quotationspro_added_failed', $this->l('Unable to add product to your request.'));
        Media::addJsDefL('roja45quotationspro_deleted_success', $this->l('Product removed from your request successfully.'));
        Media::addJsDefL('roja45quotationspro_deleted_failed', $this->l('Unable to remove product from your request.'));
        Media::addJsDefL('roja45quotationspro_sent_failed', $this->l(
            'Unable to send request. Please try again later.'
        ));
        Media::addJsDefL('roja45quotationspro_unknown_error', $this->l(
            'An unexpected error has occurred, please raise this with your support provider.'
        ));

        //return $this->displayTemplate('displayHeader.tpl');
    }

    public function hookDisplayNav($params)
    {
        return '';
    }

    public function hookDisplayNav2($params)
    {
        return $this->hookDisplayNav($params);
    }

    public function hookDisplayProductAdditionalInfo($params)
    {
        return $this->hookDisplayProductButtons($params);
    }

    public function hookDisplayProductButtons($params)
    {
        if (!isset($this->context->controller->php_self)) {
            return;
        }

        if (is_array($params['product'])) {
            $id_product = $params['product']['id_product'];
        } else {
            $id_product = $params['product']->id;
        }

        if (in_array($id_product, Roja45QuotationsProFree::cacheEnabled())) {
            if (version_compare(_PS_VERSION_, '1.7', '<') == true) {
                $this->getWidgetVariables('displayProductButtons', $params);
                return $this->display(__FILE__, 'displayProductButtons.tpl', $this->getCacheId());
            } else {
                return $this->renderWidget('displayProductButtons', $params);
            }
        }
    }

    public function hookDisplayRoja45AddToQuoteButton($params)
    {
        return $this->hookDisplayProductButtons($params);
    }

    public function hookDisplayLeftColumnProduct($params)
    {
        return $this->hookDisplayProductButtons($params);
    }

    public function hookDisplayRightColumnProduct($params)
    {
        return $this->hookDisplayProductButtons($params);
    }

    public function hookDisplayShoppingCartFooter($params)
    {
        if ((int)RojaFortyFiveQuotationsProCore::getCustomerRequirement('ROJA45QUOTATIONSPRO_QUOTEMODIFIED') &&
            !(int)Configuration::get('ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION')) {
            RojaFortyFiveQuotationsProCore::saveCustomerRequirement('ROJA45QUOTATIONSPRO_QUOTEMODIFIED', 0);
            $this->smarty->assign(
                array(
                    'roja45_cartmodified' => 1,
                )
            );
            return $this->display(__FILE__, 'displayShoppingCartFooter.tpl', $this->getCacheId());
        }
    }

    public function hookActionAdminControllerSetMedia($params)
    {
        if (
            $this->context->controller->controller_name == 'AdminModules' &&
            Tools::getValue('configure') == $this->name
        ) {
            if (
                $this->context->controller->controller_name == 'AdminModules' &&
                Tools::getValue('configure') == $this->name
            ) {
                $this->context->controller->addJS($this->_path . 'views/js/roja45moduleadmin.js');
                $this->context->controller->addCSS($this->_path . 'views/css/roja45moduleadmin.css');
            }
            $this->context->controller->addJS(_PS_MODULE_DIR_ . $this->name . '/vendor/riotjs/riot+compiler.min.js');
            $this->context->controller->addJqueryPlugin('growl');
            $this->context->controller->addJS($this->_path . 'views/js/validate.js');
            $this->context->controller->addJqueryUi('ui.dialog');
            if (version_compare(_PS_VERSION_, '1.6.0.3', '>=') === true) {
                $this->context->controller->addjqueryPlugin('sortable');
            } elseif (version_compare(_PS_VERSION_, '1.6.0', '>=') === true) {
                $this->context->controller->addJS(_PS_JS_DIR_ . 'jquery/plugins/jquery.sortable.js');
            }
        }
    }

    public function hookDisplayBackOfficeHeader($params)
    {
        if (version_compare(_PS_VERSION_, '1.7', '<') == true) {
            return $this->display(__FILE__, 'displayBackOfficeHeader.tpl');
        }
    }

    public function hookDisplayBackOfficeFooter($params)
    {
        if (!Configuration::get('ROJA45_MODULEMANAGER_INSTALLED')) {
            if (version_compare(_PS_VERSION_, '1.6.0.9', '<=') === true) {
                $this->smarty->assign(
                    array(
                        'requires_multiselect' => 1,
                    )
                );
            }
            return $this->display(__FILE__, 'hookRoja45ModalDialogs.tpl');
        }
    }

    public function hookDisplayProductListReviews($params)
    {
        if (!isset($this->context->controller->php_self)) {
            return;
        }

        $id_product = $params['product']['id_product'];
        if (in_array($id_product, Roja45QuotationsProFree::cacheEnabled())) {
            if (version_compare(_PS_VERSION_, '1.7', '<') == true) {
                $this->getWidgetVariables('displayEnabledIndicator', $params);
                return $this->display(__FILE__, 'displayEnabledIndicator.tpl', $this->getCacheId());
            } else {
                return $this->renderWidget('displayEnabledIndicator', $params);
            }
        }
    }

    public function hookDisplayRoja45ModuleManager($params)
    {
        $return = $this->name;
        return $return;
    }

    public function hookDisplayRoja45QuotationDialog($params)
    {
        return $this->hookDisplayFooter($params);
    }

    public function hookDisplayRoja45ProductList($params)
    {
        if (in_array($params['product']['id_product'], Roja45QuotationsProFree::cacheEnabled())) {
            if (version_compare(_PS_VERSION_, '1.7', '<') == true) {
                $this->getWidgetVariables('displayRoja45ProductList', $params);
                return $this->display(__FILE__, 'displayRoja45ProductList.tpl', $this->getCacheId());
            } else {
                return $this->renderWidget('displayRoja45ProductList', $params);
            }
        }
    }

    public function hookDisplayCustomerAccount($params)
    {
        if (version_compare(_PS_VERSION_, '1.7', '>=') == true) {
            return $this->display(__FILE__, 'PS17_displayCustomerAccount.tpl');
        } else {
            $this->getWidgetVariables('displayCustomerAccount', $params);
            return $this->display(__FILE__, 'displayCustomerAccount.tpl');
        }
    }

    public function hookActionCarrierProcess($params)
    {
        if ($params['cart'] !=null) {
            $id = RojaQuotation::getQuotationsForCart($params['cart']->id);
            if (count($id)) {
                $quotation = new RojaQuotation($id[0]['id_roja45_quotation']);
                if (Validate::isLoadedObject($quotation) && $params['cookie']->isLogged()) {
                    // TODO - Comparison between cart and quote (method on quotation object)
                }
            }
        }
    }

    public function hookActionValidateOrder($params)
    {
        $id = RojaQuotation::getQuotationsForCart($params['order']->id_cart);
        if (count($id)) {
            $quotation = new RojaQuotation($id[0]['id_roja45_quotation']);
            $quotation->id_order = $params['order']->id;
            $quotation->setStatus(QuotationStatus::$ORDR);
            $mysql_date_now = date('Y-m-d H:i:s');
            $quotation->purchase_date = $mysql_date_now;
            $quotation->resetCartPrices();
            $quotation->save();
        }
    }

    public function hookActionBeforeCartUpdateQty($params)
    {
        $id_roja45_quotation = RojaFortyFiveQuotationsProCore::getCustomerRequirement('ROJA45QUOTATIONSPRO_ID_QUOTATION');
        if ($id_roja45_quotation && (int) RojaFortyFiveQuotationsProCore::getCustomerRequirement('ROJA45QUOTATIONSPRO_QUOTEINCART')) {
            $quotation = new RojaQuotation($id_roja45_quotation);
            if (Validate::isLoadedObject($quotation) &&
                $params['cookie']->isLogged() &&
                !(int)Configuration::get('ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION')) {
                $quotation->resetCartPrices();
                $quotation->modified = 1;
                $quotation->save();
                RojaFortyFiveQuotationsProCore::saveCustomerRequirement('ROJA45QUOTATIONSPRO_QUOTEMODIFIED', 1);
                RojaFortyFiveQuotationsProCore::clearCustomerRequirement('ROJA45QUOTATIONSPRO_ID_QUOTATION');
                RojaFortyFiveQuotationsProCore::clearCustomerRequirement('ROJA45QUOTATIONSPRO_QUOTEINCART', 0);
            }
        }
    }

    public function hookActionObjectCustomerMessageAddAfter($params)
    {
        $id = QuotationMessage::getQuotationForThread($params['object']->id_customer_thread);
        if (count($id)) {
            $quotation = new RojaQuotation($id[0]['id_roja45_quotation']);
            if (Validate::isLoadedObject($quotation)) {
                // TODO - delete discounts and specific prices here??
                $quotation->setStatus(QuotationStatus::$CUSR);
                $quotation->save();
            }
        }
    }

    public function getForm()
    {
        $form = array();
        $sql = '
            SELECT * 
            FROM `' . _DB_PREFIX_ . 'roja45_quotationspro_form` 
            WHERE id_shop =' . (int) $this->context->shop->id;

        if ($row = Db::getInstance()->getRow($sql)) {
            $form['id'] = $row['id_quotation_form'];
            $form['cols'] = $row['form_columns'];
            // explode titles.
            $titles = array();
            parse_str($row['form_column_titles'], $titles);

            $form['titles'] = $titles;
            $sql = '
            	SELECT 
            	    form_element_id as id, 
            	    form_element_name as name, 
            	    form_element_type as type, 
            	    form_element_column as col, 
            	    form_element_deletable as deletable, 
            	    form_element_config as configuration
                FROM `' . _DB_PREFIX_ . 'roja45_quotationspro_form_element` 
                WHERE id_quotation_form = ' . (int) $form['id'];
            if ($results = Db::getInstance()->executeS($sql)) {
                foreach ($results as $row) {
                    $form['fields'][$row['col']][] = $row;
                }
            }
        } else {
            $form['cols'] = 2;
            $form['id'] = '';
        }

        return $form;
    }

    protected function processSubmit()
    {
        if (Tools::isSubmit('sent_register')) {
            if (Tools::getIsset('email') && Tools::getIsset('number_order')) {
                $params = array();
                $params['email'] = Tools::getValue('email');
                $params['number_order'] = Tools::getValue('number_order');
                $params['is_domain_test'] = (
                (Tools::getIsset('is_domain_test') && Tools::getValue('is_domain_test', 'off') == 'on') ? 1 : 0
                );

                if (!empty($params['email']) && !empty($params['number_order'])) {
                    $response = $this->jsonDecode($this->sendRequest($params));

                    if (is_object($response)) {
                        if ($response->code == self::CODE_ERROR) {
                            $this->errors[] = $response->message;
                        } elseif ($response->code == self::CODE_SUCCESS) {
                            $this->html .= $this->displayConfirmation($response->message);
                        }
                    }
                } else {
                    $this->errors[] = 'Please enter the information marked as mandatory for registration module.';
                }
            }
        } else {
            if (Tools::isSubmit('submitConfiguration')) {
                $returned = $this->processSubmitConfiguration();
                if (is_array($returned)) {
                    if (count($returned) > 0) {
                        foreach ($returned as $err) {
                            $this->html .= $this->displayError($err);
                        }
                    } else {
                        $this->html .= $this->displayError($this->l('Unable to save configuration.'));
                    }
                } elseif ($returned == true) {
                    $this->html .= $this->displayConfirmation($this->l('Settings updated'));
                } else {
                    $this->html .= $this->displayError($this->l('Unable to save configuration.'));
                }
            }
        }

        if (Tools::isSubmit('submitFormDesign')) {
            $this->processSubmitFormDesign();
        }
    }

    private function registerHooks()
    {
        if (!$this->registerHook('actionAdminControllerSetMedia')
            || !$this->registerHook('actionCarrierProcess')
            || !$this->registerHook('displayHeader')
            || !$this->registerHook('displayRoja45ModuleManager')
            || !$this->registerHook('displayProductListReviews')
            || !$this->registerHook('displayCustomerAccount')
            || !$this->registerHook('actionBeforeCartUpdateQty')
            || !$this->registerHook('actionValidateOrder')
            || !$this->registerHook('displayRoja45QuotationDialog')
            || !$this->registerHook('displayShoppingCartFooter')
            || !$this->registerHook('displayRoja45ProductList')
            || !$this->registerHook('displayRoja45AddToQuoteButton')
            || !$this->registerHook('displayBackOfficeFooter')
            || !$this->registerHook('actionObjectCustomerMessageAddAfter')) {
            return false;
        }

        if (version_compare(_PS_VERSION_, '1.7', '<') == true) {
            if (!$this->registerHook('displayNav')
                || !$this->registerHook('displayBackOfficeHeader')
                || !$this->registerHook('displayProductButtons')
                || !$this->registerHook('displayBackOfficeTop')) {
                return false;
            }
        }

        if (version_compare(_PS_VERSION_, '1.7', '>=') == true) {
            if (!$this->registerHook('displayNav2')
                || !$this->registerHook('displayProductAdditionalInfo')) {
                return false;
            }
        }

        return true;
    }

    private function installDb()
    {
        $return = true;
        try {
            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'product_quotationspro` (
                `id_roja45_product_quotation` int(10) unsigned NOT NULL auto_increment,
                `id_product` int(10) NOT NULL,
                `enabled` tinyint(1) NOT NULL DEFAULT \'0\',
                PRIMARY KEY (`id_roja45_product_quotation`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro_form` (
                `id_quotation_form` int(10) unsigned NOT NULL auto_increment,
                `id_shop` int(10) unsigned NOT NULL,
                `form_columns` int(10) NOT NULL,
                `form_column_titles` varchar(255) NOT NULL,
                PRIMARY KEY (`id_quotation_form`, `id_shop`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro_form_element` (
                `id_quotation_form_element` int(10) unsigned NOT NULL auto_increment,
                `id_quotation_form` int(10) unsigned NOT NULL,
                `form_element_id` varchar(255) NOT NULL,
                `form_element_name` varchar(255) NOT NULL,
                `form_element_type` varchar(255),
                `form_element_column` int(1) NOT NULL,
                `form_element_position` int(10) NOT NULL,
                `form_element_deletable` tinyint(1) NOT NULL,
                `form_element_config` text NOT NULL,
                PRIMARY KEY (`id_quotation_form_element`, `id_quotation_form`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro_status` (
                `id_roja45_quotation_status` int(10) unsigned NOT NULL auto_increment,
                `color`       varchar(255) NOT NULL,
                `code`        varchar(255) NOT NULL,
                `send_email`  tinyint(1) NOT NULL DEFAULT \'0\',
                `notify_admin`  tinyint(1) NOT NULL DEFAULT \'0\',
                `unremovable`     tinyint(1) NOT NULL DEFAULT \'0\',
                `answer_template`   varchar(255) NOT NULL,
                PRIMARY KEY (`id_roja45_quotation_status`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro_status_lang` (
                `id_roja45_quotation_status` int(10) unsigned NOT NULL auto_increment,
                `id_lang` varchar(255) NOT NULL,
                `status` varchar(255) NOT NULL,
                PRIMARY KEY (`id_roja45_quotation_status`,`id_lang`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro_answer` (
                `id_roja45_quotation_answer` int(10) unsigned NOT NULL auto_increment,
                `name` varchar(255) NOT NULL,
                `enabled` tinyint(1) NOT NULL DEFAULT \'1\',
                PRIMARY KEY (`id_roja45_quotation_answer`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);
            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro` (
                `id_roja45_quotation` int(10) unsigned NOT NULL auto_increment,
                `id_roja45_quotation_status` int(10),
                `id_lang` int(10),
                `id_shop` int(10),
                `id_currency` int(10),
                `id_country` int(10),
                `id_state` int(10),
                `id_address` int(10),
                `id_carrier` int(10),
                `id_request` int(10),
                `expiry_date` DATETIME NOT NULL,
                `valid_days` int(10),
                `email` varchar(255) NOT NULL,
                `firstname` varchar(255) NOT NULL,
                `lastname` varchar(255) NOT NULL,
                `form_data` text,
                `reference` varchar(255) NOT NULL,
                `filename` varchar(255) NOT NULL,
                `calculate_taxes` tinyint(1) NOT NULL DEFAULT \'0\',
                `modified` tinyint(1) NOT NULL DEFAULT \'0\',
                `quote_sent` tinyint(1) NOT NULL DEFAULT \'0\',
                `id_customer` int(10),
                `tmp_password` varchar(255) NOT NULL,
                `id_cart` int(10),
                `id_order` int(10),
                `purchase_date` DATETIME NOT NULL,
                `id_employee` varchar(255),
                `total_to_pay` decimal(20,6),
                `total_to_pay_wt` decimal(20,6),
                `total_products` decimal(20,6),
                `total_products_wt` decimal(20,6),
                `total_discount` decimal(20,6),
                `total_discount_wt` decimal(20,6),
                `total_shipping` decimal(20,6),
                `total_shipping_wt` decimal(20,6),
                `total_handling` decimal(20,6),
                `total_handling_wt` decimal(20,6),
                `total_wrapping` decimal(20,6),
                `total_charges` decimal(20,6),
                `total_charges_wt` decimal(20,6),
                `is_template` tinyint(1),
                `quote_name` varchar(255) NOT NULL,
                `template_name` varchar(255) NOT NULL,
                `date_add` DATETIME NOT NULL,
                `date_upd` DATETIME NOT NULL,
                PRIMARY KEY (`id_roja45_quotation`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            $sql = '
              CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro_product` (
              `id_roja45_quotation_product` int(10) unsigned NOT NULL auto_increment,
              `id_roja45_quotation` int(10) unsigned NOT NULL,
              `id_product` int(10),
              `id_product_attribute` int(10),
              `id_shop` int(10),
              `product_title` varchar(255),
              `comment` varchar(1000),
              `qty` int(10),
              `unit_price_tax_excl` decimal(20,6),
              `unit_price_tax_incl` decimal(20,6),
              `custom_price` tinyint(1) NOT NULL DEFAULT \'0\',
              `id_specific_price` int(10),
              `date_add` DATETIME NOT NULL,
                `date_upd` DATETIME NOT NULL,
              PRIMARY KEY (`id_roja45_quotation_product`)
            ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro_charge` (
                `id_roja45_quotation_charge` int(10) unsigned NOT NULL auto_increment,
                `id_roja45_quotation` int(10),
                `charge_name` varchar(255),
                `charge_type` varchar(255),
                `charge_method` varchar(255),
                `charge_value` decimal(20,6),
                `charge_amount` decimal(20,6),
                `charge_amount_wt` decimal(20,6),
                `specific_product` tinyint(1) NOT NULL DEFAULT \'0\',
                `id_roja45_quotation_product` int(10),
                `id_cart_rule` int(10),
                PRIMARY KEY (`id_roja45_quotation_charge`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro_message` (
                `id_roja45_quotation_message` int(10) unsigned NOT NULL auto_increment,
                `id_roja45_quotation` int(10),
                `id_customer_thread` int(10),
                PRIMARY KEY (`id_roja45_quotation_message`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro_note` (
                `id_roja45_quotation_note` int(10) unsigned NOT NULL auto_increment,
                `id_roja45_quotation` int(10),
                `note` text,
                `added` DATETIME NOT NULL,
                PRIMARY KEY (`id_roja45_quotation_note`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro_request` (
                `id_roja45_quotation_request` int(10) unsigned NOT NULL auto_increment,
                `id_shop` int(10),
                `id_currency` int(10),
                `id_customer` int(10),
                `id_guest` int(10),
                `id_lang` int(10),
                `secure_key` varchar(32),
                `form_data` text,
                `date_add` datetime,
                `date_upd` datetime,
                PRIMARY KEY (`id_roja45_quotation_request`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            $sql = '
                CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'roja45_quotationspro_requestproduct` (
                `id_roja45_quotation_requestproduct` int(10) unsigned NOT NULL auto_increment,
                `id_roja45_quotation_request` int(10),
                `id_shop` int(10),
                `id_product` int(10),
                `id_product_attribute` int(10),
                `qty` int(10),
                `date_add` datetime,
                PRIMARY KEY (`id_roja45_quotation_requestproduct`)
                ) ENGINE=`' . _MYSQL_ENGINE_ . '` DEFAULT CHARSET=UTF8;';
            $return &= (bool)Db::getInstance()->execute($sql);

            return $return;
        } catch (Exception $e) {
            return false;
        }
    }

    private function setGlobalVars()
    {
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_ENABLED', '0');
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_EMAIL', '');
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_ENABLE_CAPTCHA', 0);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_COLUMNS', 2);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_CALCULATION_ORDER', 1);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_REPLACE_CART', 1);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_USE_CS', 0);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_REQUEST_TYPE', 1);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_REQUEST_BUTTONS', 1);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_DISPLAY_LABEL', 1);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_DELETE_CART_PRODUCTS', 0);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_QTY_CART_PRODUCTS', 0);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_QUOTE_REDIRECT_CUSTOMER', 1);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_QUOTE_VALID_DAYS', 30);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_DISPLAY_LABEL_POSITION', 'quote-box-bottom-left');
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_USEAJAX', 1);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_USEJS', 1);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_ENABLEQUOTECART', 1);
        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION', 0);
        return true;
    }

    private function installTabs()
    {
        $return = true;
        $id_tab = Tab::getIdFromClassName('AdminParentAdminQuotationsPro');
        if (!$id_tab) {
            $tab = new Tab();
            $tab->active = 1;
            $tab->class_name = 'AdminParentAdminQuotationsPro';
            $tab->id_parent = 0;
            $tab->module = $this->name;
            $tab->icon = 'list';
            $tab->name = array();
            foreach (Language::getLanguages(true) as $lang) {
                $tab->name[$lang['id_lang']] = RojaFortyFiveQuotationsProCore::getLocalTranslation($this, $tab->class_name, $lang);
            }
            $return &= $tab->add();

            $tab->updatePosition(0, 3);

            $tab = new Tab();
            $tab->active = 1;
            $tab->class_name = 'AdminQuotationsPro';
            $tab->id_parent = Tab::getIdFromClassName('AdminParentAdminQuotationsPro');
            $tab->module = $this->name;
            $tab->icon = 'list';
            $tab->name = array();
            foreach (Language::getLanguages(true) as $lang) {
                $tab->name[$lang['id_lang']] = RojaFortyFiveQuotationsProCore::getLocalTranslation($this, $tab->class_name, $lang);
            }
            $return &= $tab->add();
        }

        return $return;
    }

    private function populateDefaultData()
    {
        $return = true;
        $return &= Db::getInstance()->insert(
            'roja45_quotationspro_form',
            array(
                'id_shop' => (int)$this->context->shop->id,
                'form_columns' => 1,
            )
        );

        $id_form = Db::getInstance()->Insert_ID();
        $languages = Language::getLanguages(true);
        $contact_firstname_config = 'form_element_name=ROJA45QUOTATIONSPRO_FIRSTNAME&form_element_size=&form_element_required=1&form_element_validation=isName&form_element_validation_custom=&';
        $contact_lastname_config = 'form_element_name=ROJA45QUOTATIONSPRO_LASTNAME&form_element_size=&form_element_required=1&form_element_validation=isName&form_element_validation_custom=&';
        $contact_email_config = 'form_element_name=ROJA45QUOTATIONSPRO_EMAIL&form_element_size=&form_element_required=1&form_element_validation=isEmail&form_element_validation_custom=&';
        foreach ($languages as $language) {
            $contact_firstname_config .= 'form_element_label_'.$language['id_lang'].'='.RojaFortyFiveQuotationsProCore::getLocalTranslation($this, 'FormFieldFirstName', $language).'&form_element_description_'.$language['id_lang'].'='.RojaFortyFiveQuotationsProCore::getLocalTranslation($this, 'FormFieldFirstNameDesc', $language).'&';
            $contact_lastname_config .= 'form_element_label_'.$language['id_lang'].'='.RojaFortyFiveQuotationsProCore::getLocalTranslation($this, 'FormFieldLastName', $language).'&form_element_description_'.$language['id_lang'].'='.RojaFortyFiveQuotationsProCore::getLocalTranslation($this, 'FormFieldLastNameDesc', $language).'&';
            $contact_email_config .= 'form_element_label_'.$language['id_lang'].'='.RojaFortyFiveQuotationsProCore::getLocalTranslation($this, 'FormFieldEmail', $language).'&form_element_description_'.$language['id_lang'].'='.RojaFortyFiveQuotationsProCore::getLocalTranslation($this, 'FormFieldEmailDesc', $language).'&';
        }
        $contact_firstname_config = Tools::substr($contact_firstname_config, 0, Tools::strlen($contact_firstname_config)-1);
        $contact_lastname_config = Tools::substr($contact_lastname_config, 0, Tools::strlen($contact_lastname_config)-1);
        $contact_email_config = Tools::substr($contact_email_config, 0, Tools::strlen($contact_email_config)-1);

        $return &= Db::getInstance()->insert(
            'roja45_quotationspro_form_element',
            array(
                'id_quotation_form' => (int)$id_form,
                'form_element_id' => 'ROJA45QUOTATIONSPRO_FIRSTNAME',
                'form_element_name' => 'ROJA45QUOTATIONSPRO_FIRSTNAME',
                'form_element_type' => 'TEXT',
                'form_element_column' => 1,
                'form_element_position' => 0,
                'form_element_deletable' => 0,
                'form_element_config' => pSQL($contact_firstname_config),
            )
        );

        $return &= Db::getInstance()->insert(
            'roja45_quotationspro_form_element',
            array(
                'id_quotation_form' => (int)$id_form,
                'form_element_id' => 'ROJA45QUOTATIONSPRO_LASTNAME',
                'form_element_name' => 'ROJA45QUOTATIONSPRO_LASTNAME',
                'form_element_type' => 'TEXT',
                'form_element_column' => 1,
                'form_element_position' => 0,
                'form_element_deletable' => 0,
                'form_element_config' => pSQL($contact_lastname_config),
            )
        );

        $return &= Db::getInstance()->insert(
            'roja45_quotationspro_form_element',
            array(
                'id_quotation_form' => (int)$id_form,
                'form_element_id' => 'ROJA45QUOTATIONSPRO_EMAIL',
                'form_element_name' => 'ROJA45QUOTATIONSPRO_EMAIL',
                'form_element_type' => 'TEXT',
                'form_element_column' => 1,
                'form_element_position' => 1,
                'form_element_deletable' => 0,
                'form_element_config' => pSQL($contact_email_config),
            )
        );

        $def_states = array(
            array(
                'code' => QuotationStatus::$RCVD,
                'color' => '#FF8C00',
                'unremovable' => 1,
                'send_email' => 0,
                'notify_admin' => 1,
                'name' => 'Quotation Request Received',
                'answer_template' => 'quotation_request_received'
            ),
            array(
                'code' => QuotationStatus::$SENT,
                'color' => '#32CD32',
                'unremovable' => 1,
                'send_email' => 0,
                'notify_admin' => 0,
                'name' => 'Customer Quotation Sent',
                'answer_template' => 'customer_quotation_sent'
            ),
            array(
                'code' => QuotationStatus::$CART,
                'color' => '#4169E1',
                'unremovable' => 1,
                'send_email' => 0,
                'notify_admin' => 0,
                'name' => 'In Customer Cart',
                'answer_template' => null
            ),
            array(
                'code' => QuotationStatus::$MESG,
                'color' => '#FF8C00',
                'unremovable' => 1,
                'send_email' => 1,
                'notify_admin' => 1,
                'name' => 'Customer Message Received',
                'answer_template' => 'customer_message_received'
            ),
            array(
                'code' => QuotationStatus::$CUSR,
                'color' => '#4169E1',
                'unremovable' => 1,
                'send_email' => 0,
                'notify_admin' => 0,
                'name' => 'Customer Response Sent',
                'answer_template' => null
            ),
            array(
                'code' => QuotationStatus::$ORDR,
                'color' => '#4169E1',
                'unremovable' => 1,
                'send_email' => 0,
                'notify_admin' => 1,
                'name' => 'Customer Order Raised',
                'answer_template' => null
            ),
            array(
                'code' => QuotationStatus::$CLSD,
                'color' => '#108510',
                'unremovable' => 1,
                'send_email' => 0,
                'notify_admin' => 0,
                'name' => 'Closed - Completed',
                'answer_template' => null
            ),
            array(
                'code' => QuotationStatus::$INCP,
                'color' => '#DC143C',
                'unremovable' => 1,
                'send_email' => 0,
                'notify_admin' => 0,
                'name' => 'Closed - Incomplete',
                'answer_template' => null
            ),
            array(
                'code' => QuotationStatus::$DLTD,
                'color' => '#FF0000',
                'unremovable' => 1,
                'send_email' => 0,
                'notify_admin' => 0,
                'name' => 'Quotation Deleted',
                'answer_template' => null
            ),
            array(
                'code' => QuotationStatus::$CCLD,
                'color' => '#FF0000',
                'unremovable' => 1,
                'send_email' => 1,
                'notify_admin' => 0,
                'name' => 'Quotation Request Cancelled',
                'answer_template' => 'quotation_request_cancelled'
            ),
            array(
                'code' => QuotationStatus::$CORD,
                'color' => '#FF0000',
                'unremovable' => 1,
                'send_email' => 1,
                'notify_admin' => 1,
                'name' => 'Customer Order Request',
                'answer_template' => 'customer_order_request'
            ),
            array(
                'code' => QuotationStatus::$NWQT,
                'color' => '#FF0000',
                'unremovable' => 1,
                'send_email' => 0,
                'notify_admin' => 0,
                'name' => 'New Quotation',
                'answer_template' => 'customer_order_request'
            ),
        );

        foreach ($def_states as $state) {
            $return &= Db::getInstance()->insert(
                'roja45_quotationspro_status',
                array(
                    'color' => pSQL($state['color']),
                    'code' => pSQL($state['code']),
                    'unremovable' => (int)$state['unremovable'],
                    'send_email' => (int)$state['send_email'],
                    'notify_admin' => (int)$state['notify_admin'],
                    'answer_template' => pSQL($state['answer_template']),
                )
            );
            $id_status = Db::getInstance()->Insert_ID();
            foreach (Language::getLanguages(true) as $language) {
                $return &= Db::getInstance()->insert(
                    'roja45_quotationspro_status_lang',
                    array(
                        'id_roja45_quotation_status' => (int)$id_status,
                        'id_lang' => (int)$language['id_lang'],
                        'status' => pSQL(RojaFortyFiveQuotationsProCore::getLocalTranslation($this, $state['code'], $language)),
                    )
                );
            }
        }

        $def_answers = array(
            array(
                'name' => 'test_response',
            ),
        );
        foreach ($def_answers as $answer) {
            $return &= Db::getInstance()->insert(
                'roja45_quotationspro_answer',
                array(
                    'id_roja45_quotation_answer' => 1,
                    'name' => pSQL($answer['name']),
                    'enabled' => 1,
                )
            );
        }

        return $return;
    }

    private function uninstallDb()
    {
        try {
            return Db::getInstance()->execute('DROP TABLE IF EXISTS
            `' . _DB_PREFIX_ . 'product_quotationspro`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro_form`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro_form_element`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro_status`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro_status_lang`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro_answer`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro_product`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro_charge`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro_message`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro_request`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro_requestproduct`,
            `' . _DB_PREFIX_ . 'roja45_quotationspro_note`');
        } catch (Exception $e) {
            return false;
        }
    }

    private function uninstallTabs()
    {
        $id_tab = Tab::getIdFromClassName($this->tabClassName);
        if ($id_tab) {
            $tab = new Tab($id_tab);
            $tab->delete();
        }
        $id_tab = Tab::getIdFromClassName('AdminParent' . $this->tabClassName);
        if ($id_tab) {
            $tab = new Tab($id_tab);
            $tab->delete();
        }

        return true;
    }

    private function removeGlobalVars()
    {
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_ENABLED');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_EMAIL');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_COLUMNS');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_EMAIL_TEMPLATES');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_ENABLE_CAPTCHA');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_CALCULATION_ORDER');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_REPLACE_CART');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_REQUEST_TYPE');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_REQUEST_BUTTONS');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_DISPLAY_LABEL');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_DELETE_CART_PRODUCTS');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_QTY_CART_PRODUCTS');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_QUOTE_REDIRECT_CUSTOMER');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_RECAPTCHA_SECRET');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_USE_CS');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_RECAPTCHA_SITE');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_DISPLAY_LABEL_POSITION');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_QUOTE_VALID_DAYS');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_ENABLEQUOTECART');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_USEAJAX');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_USEJS');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_CONTACT_NAME');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_CS_ACCOUNT');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_ADD_CART_PRODUCTS');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_ENABLEPRODUCTCART');
        Configuration::deleteByName('ROJA45_QUOTATIONSPRO_ENABLE_INVISIBLECAPTCHA');

        return true;
    }

    protected function renderModuleForm()
    {
        $sql = '
            SELECT pl.`id_product`, pl.`name`
            FROM `'._DB_PREFIX_.'product_lang` pl
            WHERE pl.id_lang='.$this->context->language->id;
        $options = Db::getInstance()->executeS($sql);

        $form = $this->getForm();
        $tpl = $this->context->smarty->createTemplate($this->getTemplatePath('configuration.tpl'));
        $tpl->assign(
            array(
                'url' => $this->context->link->getAdminLink(
                    'AdminModules',
                    true
                ).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name,
                'languages' => $this->context->controller->getLanguages(),
                'is_17' => (version_compare(_PS_VERSION_, '1.7', '>=') == true) ? true : false,
                'contacts' => Contact::getContacts($this->context->language->id),
                'form' => $form,
                'columns' => $form['cols'],
                'col_width' => 12,
                'defaultFormLanguage' => (int)Configuration::get('PS_LANG_DEFAULT'),
                'products' => array(
                    'label' => $this->l('Enabled Product List'),
                    'hint' => $this->l('Select the products for which you would like enable quotations.'),
                    'name' => 'ROJA45_QUOTATIONSPRO_ENABLED_PRODUCTS',
                    'required' => true,
                    'size' => '20',
                    'options' => array(
                        'query' => $options,
                        'id' => 'id_product',
                        'name' => 'name',
                    ),
                ),
                'text_input' => array(
                    'name' => 'TEXT_FIELD_LABEL',
                    'id' => 'TEST_ID',
                    'type' => 'text',
                    //'maxchar' => '10',
                    'size' => '20',
                    'maxlength' => '10',
                    'readonly' => '0',
                    // 'prefix' => 'TE',
                    //'suffix' => 'ST',
                    'class' => 'test-class',
                    // 'string_format' => 'test-format',
                    // 'disabled' => '0',
                    // 'autocomplete' => '0',
                    'required' => '1',
                    // 'placeholder' => '',
                ),
                'fields_value' => $this->getModuleConfigFieldsValues(),
            )
        );
        $this->html .= $tpl->fetch();
        $tpl = $this->context->smarty->createTemplate(_PS_MODULE_DIR_.$this->name.'/views/templates/admin/prestui/ps-tags.tpl');
        $this->html .= $tpl->fetch();
    }

    private function postValidation()
    {
        if (Tools::isSubmit('submitConfiguration')) {
            if (!Tools::getValue('ROJA45_QUOTATION_ENABLED')) {
                $this->postErrors[] = $this->l('Account Name is required.');
            }
        }
    }

    private function getModuleConfigFieldsValues()
    {
        return array(
            'ROJA45_QUOTATIONSPRO_USE_CS' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_USE_CS',
                Configuration::get('ROJA45_QUOTATIONSPRO_USE_CS')
            ),
            'ROJA45_QUOTATIONSPRO_CS_ACCOUNT' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_CS_ACCOUNT',
                Configuration::get('ROJA45_QUOTATIONSPRO_CS_ACCOUNT')
            ),
            'ROJA45_QUOTATIONSPRO_EMAIL' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_EMAIL',
                Configuration::get('ROJA45_QUOTATIONSPRO_EMAIL')
            ),
            'ROJA45_QUOTATIONSPRO_CONTACT_NAME' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_CONTACT_NAME',
                Configuration::get('ROJA45_QUOTATIONSPRO_CONTACT_NAME')
            ),
            'ROJA45_QUOTATIONSPRO_CONTACT_BCC' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_CONTACT_BCC',
                Configuration::get('ROJA45_QUOTATIONSPRO_CONTACT_BCC')
            ),
            'ROJA45_QUOTATIONSPRO_EMAIL_TEMPLATES' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_EMAIL_TEMPLATES',
                Configuration::get('ROJA45_QUOTATIONSPRO_EMAIL_TEMPLATES')
            ),
            'ROJA45_QUOTATIONSPRO_ENABLE_CAPTCHA' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_ENABLE_CAPTCHA',
                Configuration::get('ROJA45_QUOTATIONSPRO_ENABLE_CAPTCHA')
            ),
            'ROJA45_QUOTATIONSPRO_ENABLE_INVISIBLECAPTCHA' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_ENABLE_INVISIBLECAPTCHA',
                Configuration::get('ROJA45_QUOTATIONSPRO_ENABLE_INVISIBLECAPTCHA')
            ),
            'ROJA45_QUOTATIONSPRO_CALCULATION_ORDER' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_CALCULATION_ORDER',
                Configuration::get('ROJA45_QUOTATIONSPRO_CALCULATION_ORDER')
            ),
            'ROJA45_QUOTATIONSPRO_REPLACE_CART' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_REPLACE_CART',
                Configuration::get('ROJA45_QUOTATIONSPRO_REPLACE_CART')
            ),
            'ROJA45_QUOTATIONSPRO_DELETE_CART_PRODUCTS' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_DELETE_CART_PRODUCTS',
                Configuration::get('ROJA45_QUOTATIONSPRO_DELETE_CART_PRODUCTS')
            ),
            'ROJA45_QUOTATIONSPRO_QTY_CART_PRODUCTS' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_QTY_CART_PRODUCTS',
                Configuration::get('ROJA45_QUOTATIONSPRO_QTY_CART_PRODUCTS')
            ),
            'ROJA45_QUOTATIONSPRO_QUOTE_REDIRECT_CUSTOMER' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_QUOTE_REDIRECT_CUSTOMER',
                Configuration::get('ROJA45_QUOTATIONSPRO_QUOTE_REDIRECT_CUSTOMER')
            ),
            'ROJA45_QUOTATIONSPRO_RECAPTCHA_SECRET' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_RECAPTCHA_SECRET',
                Configuration::get('ROJA45_QUOTATIONSPRO_RECAPTCHA_SECRET')
            ),
            'ROJA45_QUOTATIONSPRO_RECAPTCHA_SITE' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_RECAPTCHA_SITE',
                Configuration::get('ROJA45_QUOTATIONSPRO_RECAPTCHA_SITE')
            ),
            'ROJA45_QUOTATIONSPRO_REQUEST_BUTTONS' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_REQUEST_BUTTONS',
                Configuration::get('ROJA45_QUOTATIONSPRO_REQUEST_BUTTONS')
            ),
            'ROJA45_QUOTATIONSPRO_DISPLAY_LABEL' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_DISPLAY_LABEL',
                Configuration::get('ROJA45_QUOTATIONSPRO_DISPLAY_LABEL')
            ),
            'ROJA45_QUOTATIONSPRO_DISPLAY_LABEL_POSITION' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_DISPLAY_LABEL_POSITION',
                Configuration::get('ROJA45_QUOTATIONSPRO_DISPLAY_LABEL_POSITION')
            ),
            'ROJA45_QUOTATIONSPRO_QUOTE_VALID_DAYS' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_QUOTE_VALID_DAYS',
                Configuration::get('ROJA45_QUOTATIONSPRO_QUOTE_VALID_DAYS')
            ),
            'ROJA45_QUOTATIONSPRO_USEJS' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_USEJS',
                Configuration::get('ROJA45_QUOTATIONSPRO_USEJS')
            ),
            'ROJA45_QUOTATIONSPRO_USEAJAX' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_USEAJAX',
                Configuration::get('ROJA45_QUOTATIONSPRO_USEAJAX')
            ),
            'ROJA45_QUOTATIONSPRO_ENABLEQUOTECART' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_ENABLEQUOTECART',
                Configuration::get('ROJA45_QUOTATIONSPRO_ENABLEQUOTECART')
            ),
            'ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION' => Tools::getValue(
                'ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION',
                Configuration::get('ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION')
            ),
            'ROJA45_QUOTATIONSPRO_ENABLED_PRODUCTS' => Roja45QuotationsProFree::cacheEnabled(),
        );
    }

    public function buildFormComponents($form_config)
    {
        $id_language = $this->context->language->id;

        $form = array();
        // for columns
        foreach ($form_config['fields'] as $col => $column) {
            $form[$col] = array();
            $form[$col]['settings'] = array();
            $form[$col]['fields'] = array();

            if (isset($form_config['titles']['form_element_column_title_' . $col])) {
                $form[$col]['settings']['column_heading'] = $form_config['titles']['form_element_column_title_' . $col];
            }

            foreach ($column as $pos => $field) {
                $form_field = array();
                $form_field['id'] = $field['id'];
                $form_field['name'] = $field['name'];
                $form_field['type'] = $field['type'];
                if (isset($field['pos'])) {
                    $form_field['position'] = $field['pos'];
                }

                $config = array();
                parse_str($field['configuration'], $config);
                $form_field['required'] = $config['form_element_required'];

                if (isset($config['form_element_validation'])) {
                    $form_field['validation'] = $config['form_element_validation'];

                    // TODO - need to convert back to string here?
                    if ($form_field['validation'] == 'custom') {
                        $form_field['custom_regex'] = $config['form_element_validation_custom'];
                    } else {
                        $form_field['custom_regex'] = '';
                    }
                }

                if ($form_field['type'] == 'SELECT') {
                    if ($config['form_element_contents'] == 1) {
                        $exploded = explode("\n", urldecode($config['form_element_select_options_' . $id_language]));
                        $options = array();
                        foreach ($exploded as $key => $option) {
                            $options[$key]['id'] = Tools::strtoupper(trim($option));
                            $options[$key]['name'] = $option;
                        }
                        $form_field['options'] = $options;
                        $form_field['key_options'] = 'id';
                        $form_field['value_options'] = 'name';
                    } elseif ($config['form_element_contents'] == 2) {
                        if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES')) {
                            $countries = Carrier::getDeliveredCountries($this->context->language->id, true, true);
                        } else {
                            $countries = Country::getCountries($this->context->language->id, true);
                        }
                        $form_field['options'] = $countries;
                        $form_field['key_options'] = 'id_country';
                        $form_field['value_options'] = 'name';
                    }
                }
                if ($form_field['type'] == 'TEXTAREA') {
                    $form_field['rows'] = $config['form_element_rows_' . $id_language];
                }
                if ($form_field['type'] == 'DATE') {
                    $form_field['format'] = $config['form_element_date_format'];
                }
                $form_field['label'] = $config['form_element_label_' . $id_language];
                $form_field['description'] = $config['form_element_description_' . $id_language];

                if (isset($config['form_element_size'])) {
                    $form_field['size'] = $config['form_element_size'];
                } else {
                    $form_field['size'] = '';
                }

                if (isset($config['form_element_class'])) {
                    $form_field['class'] = $config['form_element_class'];
                } else {
                    $form_field['class'] = '';
                }
                if (isset($config['form_element_length'])) {
                    $form_field['maxlength'] = $config['form_element_length'];
                } else {
                    $form_field['maxlength'] = 255;
                }
                if (isset($config['form_element_prefix_' . $id_language]) && Tools::strlen($config['form_element_prefix_' . $id_language]) > 0) {
                    $form_field['prefix'] = $config['form_element_prefix_' . $id_language];
                } else {
                    $form_field['prefix'] = null;
                }
                if (isset($config['form_element_suffix_' . $id_language]) && Tools::strlen($config['form_element_suffix_' . $id_language]) > 0) {
                    $form_field['suffix'] = $config['form_element_suffix_' . $id_language];
                } else {
                    $form_field['suffix'] = null;
                }
                $form[$col]['fields'][$pos] = $form_field;
            }
        }
        return $form;
    }

    private static function getCountry($address = null)
    {
        if ($id_country = Tools::getValue('id_country')) {
            return (int)$id_country;
        } elseif (isset($address) && isset($address->id_country) && $address->id_country) {
            $id_country = $address->id_country;
        } elseif (Configuration::get('PS_DETECT_COUNTRY') && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            preg_match('#(?<=-)\w\w|\w\w(?!-)#', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $array);
            if (is_array($array) && isset($array[0]) && Validate::isLanguageIsoCode($array[0])) {
                $id_country = (int)Country::getByIso($array[0], true);
            }
        }
        if (!isset($id_country) || !$id_country) {
            $id_country = Configuration::get('PS_COUNTRY_DEFAULT');
        }
        return (int)$id_country;
    }

    public function processSubmitConfiguration()
    {
        $validationErrors = array();
        $html = '';
        try {
            // FORM VALIDATION
            Configuration::updateGlobalValue(
                'ROJA45_QUOTATIONSPRO_USE_CS',
                Tools::getValue('ROJA45_QUOTATIONSPRO_USE_CS')
            );

            if (Tools::getValue('ROJA45_QUOTATIONSPRO_USE_CS') == 1) {
                if (!Tools::strlen(trim(Tools::getValue('ROJA45_QUOTATIONSPRO_EMAIL'))) > 0) {
                    $validationErrors[] = $this->l('Email Address Required');
                }
                if (!Tools::strlen(trim(Tools::getValue('ROJA45_QUOTATIONSPRO_CONTACT_NAME'))) > 0) {
                    $validationErrors[] = $this->l('Contact Name Required');
                }
            } else {
                if (!Tools::strlen(trim(Tools::getValue('ROJA45_QUOTATIONSPRO_CS_ACCOUNT'))) > 0) {
                    $validationErrors[] = $this->l('Customer Service Account Required');
                }
            }

            if (!count($validationErrors)) {
                if (Tools::getValue('ROJA45_QUOTATIONSPRO_USE_CS') == 0) {
                    $id_account = Tools::getValue('ROJA45_QUOTATIONSPRO_CS_ACCOUNT');
                    $sql = 'SELECT c.id_contact, c.email, cl.name
                    FROM `' . _DB_PREFIX_ . 'contact` c
                    LEFT JOIN `' . _DB_PREFIX_ . 'contact_lang` cl on (c.id_contact = cl.id_contact)
                    WHERE c.id_contact = ' . (int) $id_account . '
                    AND cl.id_lang = ' . (int) $this->context->language->id;

                    if ($row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql)) {
                        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_EMAIL', $row['email']);
                        Configuration::updateGlobalValue('ROJA45_QUOTATIONSPRO_CONTACT_NAME', $row['name']);
                    }
                    Configuration::updateGlobalValue(
                        'ROJA45_QUOTATIONSPRO_CS_ACCOUNT',
                        Tools::getValue('ROJA45_QUOTATIONSPRO_CS_ACCOUNT')
                    );
                } else {
                    Configuration::updateGlobalValue(
                        'ROJA45_QUOTATIONSPRO_EMAIL',
                        Tools::getValue('ROJA45_QUOTATIONSPRO_EMAIL')
                    );
                    Configuration::updateGlobalValue(
                        'ROJA45_QUOTATIONSPRO_CONTACT_NAME',
                        Tools::getValue('ROJA45_QUOTATIONSPRO_CONTACT_NAME')
                    );
                    Configuration::updateGlobalValue(
                        'ROJA45_QUOTATIONSPRO_CONTACT_BCC',
                        Tools::getValue('ROJA45_QUOTATIONSPRO_CONTACT_BCC')
                    );
                }

                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_EMAIL_TEMPLATES',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_EMAIL_TEMPLATES')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_ENABLE_CAPTCHA',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_ENABLE_CAPTCHA')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_ENABLE_INVISIBLECAPTCHA',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_ENABLE_INVISIBLECAPTCHA')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_RECAPTCHA_SITE',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_RECAPTCHA_SITE')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_RECAPTCHA_SECRET',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_RECAPTCHA_SECRET')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_CALCULATION_ORDER',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_CALCULATION_ORDER')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_REPLACE_CART',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_REPLACE_CART')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_REQUEST_TYPE',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_REQUEST_TYPE')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_DELETE_CART_PRODUCTS',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_DELETE_CART_PRODUCTS')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_QTY_CART_PRODUCTS',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_QTY_CART_PRODUCTS')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_QUOTE_REDIRECT_CUSTOMER',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_QUOTE_REDIRECT_CUSTOMER')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_REQUEST_BUTTONS',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_REQUEST_BUTTONS')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_DISPLAY_LABEL',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_DISPLAY_LABEL')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_DISPLAY_LABEL_POSITION',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_DISPLAY_LABEL_POSITION')
                );
                if (!is_int((int) Tools::getValue('ROJA45_QUOTATIONSPRO_QUOTE_VALID_DAYS'))) {
                    throw new Exception($this->module->l('your valid days value should be an number.'));
                }
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_QUOTE_VALID_DAYS',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_QUOTE_VALID_DAYS')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_USEJS',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_USEJS')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_USEAJAX',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_USEAJAX')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_ENABLEQUOTECART',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_ENABLEQUOTECART')
                );
                Configuration::updateGlobalValue(
                    'ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION',
                    Tools::getValue('ROJA45_QUOTATIONSPRO_ALLOW_CART_MODIFICATION')
                );

                $enabled_products = array();
                $selected_products = Tools::getValue('ROJA45_QUOTATIONSPRO_ENABLED_PRODUCTS_selected');
                $sql = '
                    SELECT id_product 
                    FROM `' . _DB_PREFIX_ . 'product_quotationspro`
                    WHERE enabled=1';
                $results = Db::getInstance()->executeS($sql);
                foreach ($results as $row) {
                    $enabled_products[$row['id_product']] = $row['id_product'];
                }

                if ($selected_products) {
                    foreach ($selected_products as $id_product) {
                        if (($key = array_search($id_product, $enabled_products)) !== false) {
                            unset($enabled_products[$key]);
                        } else {
                            $insert = array(
                                'id_product' => (int)$id_product,
                                'enabled' => (int) 1
                            );
                            Db::getInstance()->insert('product_quotationspro', $insert);
                        }
                    }
                }

                foreach ($enabled_products as $id_product) {
                    if ($selected_products && !in_array($id_product, $selected_products)) {
                        $sql = '
                            DELETE FROM `' . _DB_PREFIX_ . 'product_quotationspro`
                            WHERE id_product='.(int) $id_product;
                        Db::getInstance()->execute($sql);
                    }
                }
                $this->clearCache();
            }

            if (count($validationErrors)) {
                foreach ($validationErrors as $validationError) {
                    $html .= $this->displayError($validationError);
                }
            } else {
                $this->clearCache();
                $html .= $this->displayConfirmation($this->l('Configuration Updated'));
            }

            return $html;
        } catch (Exception $e) {
            $validationErrors = array();
            $validationErrors[] = $e->getMessage();
            foreach ($validationErrors as $validationError) {
                $html .= $this->displayError($validationError);
            }
            return $html;
        }
    }

    protected function processSubmitFormDesign()
    {
        $validationErrors = array();
        $html = '';
        try {
            $config = Tools::jsonDecode(Tools::getValue('ROJA45_QUOTATIONSPRO_FORM'));
            $sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'roja45_quotationspro_form` WHERE id_quotation_form="' . (int) $config->form_id . '"';
            if (!Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql)) {
                Db::getInstance()->insert(
                    'roja45_quotationspro_form',
                    array(
                        'id_shop' => (int)$this->context->shop->id,
                        'form_columns' => (int) $config->num_columns,
                        'form_column_titles' => pSQL($config->titles),
                    )
                );
                $form_id = Db::getInstance()->Insert_ID();
                $config->form_id = $form_id;
            } else {
                // Update it
                Db::getInstance()->update(
                    'roja45_quotationspro_form',
                    array(
                        'form_columns' => (int) $config->num_columns,
                        'form_column_titles' => pSQL($config->titles),
                    ),
                    'id_quotation_form="' . (int) $config->form_id . '" AND id_shop=' . (int) $this->context->shop->id . ''
                );
            }

            // delete everything and re-insert?
            $sql = 'DELETE FROM `' . _DB_PREFIX_ . 'roja45_quotationspro_form_element` WHERE id_quotation_form ="' . (int) $config->form_id . '"';
            if (Db::getInstance()->execute($sql)) {
                foreach ($config->columns as $col => $column) {
                    if ($column) {
                        foreach ($column->fields as &$field) {
                            $configuration = $field->configuration;
                            $id = $field->id;
                            $name = $field->name;
                            $pos = $field->pos;
                            $type = $field->type;

                            if (($id == 'ROJA45QUOTATIONSPRO_FIRSTNAME') || ($id == 'ROJA45QUOTATIONSPRO_LASTNAME') || ($id == 'ROJA45QUOTATIONSPRO_EMAIL')) {
                                $deletable = 0;
                            } else {
                                $deletable = 1;
                            }

                            Db::getInstance()->insert(
                                'roja45_quotationspro_form_element',
                                array(
                                    'id_quotation_form' => (int) $config->form_id,
                                    'form_element_id' => pSQL($id),
                                    'form_element_name' => pSQL($name),
                                    'form_element_type' => pSQL($type),
                                    'form_element_column' => (int) $col,
                                    'form_element_position' => (int) $pos,
                                    'form_element_deletable' => (int) $deletable,
                                    'form_element_config' => pSQL($configuration),
                                )
                            );
                            //$item_id = Db::getInstance()->Insert_ID();
                        }
                    }
                }
            }
            if (count($validationErrors)) {
                foreach ($validationErrors as $validationError) {
                    $html .= $this->displayError($validationError);
                }
            } else {
                $this->clearCache();
                $html .= $this->displayConfirmation($this->l('Configuration Updated'));
            }

            return $html;
        } catch (Exception $e) {
            $validationErrors = array();
            $validationErrors[] = $e->getMessage();
            foreach ($validationErrors as $validationError) {
                $html .= $this->displayError($validationError);
            }
            return $html;
        }
    }
}