<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    LD
*  @copyright 2018 LD
*  @version   1.0.1
*  @link      http://www.ld.com.br/
*  @license
*  
*  Based on the following version
* 
*  @author    DJTAL
*  @copyright 2017 DJTAL
*  @version   1.0.0
*  @link      http://www.djtal.com.br/
*/

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

include_once dirname(__FILE__).'/models/BrazilianRegister.class.php';
class LDbrazilianregister extends Module
{
    protected $config_form = false;

    public function __construct()
    {
        $this->name = 'ldbrazilianregister';
        $this->tab = 'administration';
        $this->version = '1.0.1';
        $this->ps_versions_compliancy = array('min' => '1.7.0.0', 'max' => _PS_VERSION_);
        $this->author = 'LD';
        $this->key = 0;
        $this->need_instance = 0;
        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->l('Registering rules for Brazil');
        $this->description = $this->l('This modules adds the expected informations for the client registering process in Brazil: CPF / CNPJ / CEP');

        $this->confirmUninstall = $this->l('Are you sure you want to make this big mistake ?');
        $this->active = BrazilianRegister::VerificarVersaoPHP(Configuration::get('LDBR_VERSAOPHP'));
    }
    
    public function install()
    {
        if (
            !parent::install()
            || !Configuration::updateValue('PS_TAX', false) //Global PS
            || !Configuration::updateValue('PS_TAX_DISPLAY', false) //Global PS
            || !Configuration::updateValue('LDBR_VERSAOPHP', '')
            || !Configuration::updateValue('LDBR_CPF_CNPJ_ACTIVE', true)
            || !Configuration::updateValue('LDBR_CPF_CNPJ_MODE', 'cpf-or-cnpj')
            || !Configuration::updateValue('LDBR_CPF_CNPJ_MANDATORY', 'yes')
            || !Configuration::updateValue('LDBR_CEP_MODE', 'manual')
            || !Configuration::updateValue('LDBR_CUTOMER_PERMISSIONS', 'none')
            || !Configuration::updateValue('LDBR_CEP_DK', true)
            || !Configuration::updateValue('LDBR_STREET_NUM', 'yes_mand')
            || !Configuration::updateValue('LDBR_STREET_COMPL', 'yes')
            || !$this->registerHook(
                array(
                    'header',
                    'backOfficeHeader',
					'displayCustomerAccount',
                    'additionalCustomerFormFields',
                    'validateCustomerFormFields',
                    'displayCustomerIdentityForm',
                    'actionCustomerAccountAdd',
                    'createAccount',
                    'actionBeforeSubmitAccount',
                    'displayPDFInvoice',
                    'displayAdminCustomers',
                    'displayAdminOrderContentOrder',
                    'displayAdminOrderTabOrder',
                    'displayHeader',
                )
            )
        ) {
            return false;
        }
        
        include(dirname(__FILE__).'/sql/install.php');
        
        //TAB
        $this->installTab('AdminLDBrazilianRegister', $this->l('Edit CPF / CNPJ'), 'AdminParentCustomer');
        
		$this->sendUsageStats();
		
        $brazil_id = Country::getByIso('BR');
        $tmp_addr_format = new AddressFormat($brazil_id);
        $tmp_addr_format->format =
'firstname
lastname
Country:name
postcode
address1
address2
city
State:name
phone
phone_mobile';
        $tmp_addr_format->id_country = $brazil_id;
        return $tmp_addr_format->save();
    }
    
    public function installTab($class_name,$tab_name,$tab_parent_name=false) 
    {
        $tab = new Tab();
        $tab->active = 1;
        $tab->class_name = $class_name;
        $tab->name = array();
        foreach (Language::getLanguages(true) as $lang)
            $tab->name[$lang['id_lang']] = $tab_name;

        if($tab_parent_name)
            $tab->id_parent = (int)Tab::getIdFromClassName($tab_parent_name);
        else
            $tab->id_parent = 0;
        
        $tab->module = $this->name;
        return $tab->add();
    }
    
    public function uninstall()
    {
        //include(dirname(__FILE__).'/sql/uninstall.php');

        //TAB
        if ($id_tab = Tab::getIdFromClassName('AdminLDBrazilianRegister')) {
            $tab = new Tab($id_tab);
            if(!$tab->delete()) {
                $this->_errors[] = 'Tab deletion';
                return false;
            }
        }
        
        return parent::uninstall();
    }

    /**
     * Load the configuration form
     */
    public function getContent()
    {
        $output = '';
        /**
         * If values have been submitted in the form, process.
         */
        if (((bool)Tools::isSubmit('submitLDBrazilianRegisterModule')) == true) {
            $output .= $this->postProcess();
        }
        
        $this->context->smarty->assign('module_dir', $this->_path);

        $output .= $this->context->smarty->fetch($this->local_path.'views/templates/admin/configure.tpl');

        return $output.$this->renderForm();
    }
	
	public function sendUsageStats()
    {
        $postdata = http_build_query(array(
            'domain' => _PS_BASE_URL_ . __PS_BASE_URI__,
            'module' => $this->name,
            'version' => $this->version,
            //'key' => $this->ld_key,
            'stats' => ''
        ));
        $opts     = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);
        //file_get_contents('http://ld.com.br/getModStats.php', false, $context);
    }

    /**
     * Create the form that will be displayed in the configuration of your module.
     */
    protected function renderForm()
    {
        $helper = new HelperForm();

        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $helper->module = $this;
        $helper->default_form_language = $this->context->language->id;
        $allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
        if(empty($allow_employee_form_lang)) {
            $allow_employee_form_lang = true;
        }
        $helper->allow_employee_form_lang = $allow_employee_form_lang;

        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitLDBrazilianRegisterModule';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
            .'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');

        $helper->tpl_vars = array(
            'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id,
        );

        return $helper->generateForm(array($this->getConfigForm(), $this->getConfigFormCEP(), $this->getOthersConfig(), $this->getCEPtest(), $this->getDataImport()));
    }

    /**
     * Create the structure of your form.
     */
    protected function getConfigForm()
    {
        return array(
            'form' => array(
                'legend' => array(
                'title' => $this->l('CPF and CNPJ Settings'),
                'icon' => 'icon-cogs',
                ),
                'input' => array(
                    array(
                        'type' => 'text',
                        'label' => $this->l('Serial'),
                        'name' => 'LDBR_VERSAOPHP',
                        'desc' => $this->l('Informe o serial para ativar o módulo em sua loja: ').trim(str_replace(array('www.', 'http://', 'https://'), '', _PS_BASE_URL_)),
                    ),
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Live mode'),
                        'name' => 'LDBR_CPF_CNPJ_ACTIVE',
                        'is_bool' => true,
                        'desc' => $this->l('Active the CPF | CNPJ option on your store'),
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'lang' => false,
                        'label' => $this->l('Mode'),
                        'required' => false,
                        'desc' => $this->l('Choose the information you need from your clients'),
                        'options' => array(
                            'id' => 'id_mode',
                            'name' => 'name', 
                            'query' => array(
                                          array(
                                            'id_mode' => 'cpf-or-cnpj',
                                            'name' => $this->l('CPF or CNPJ'),
                                          ),
                                          array(
                                            'id_mode' => 'cpf-or-cnpj-or-passport', 
                                            'name' => $this->l('CPF or CNPJ, or Passport'),
                                          ),
                                          
                                          array(
                                            'id_mode' => 'cpf-and-cnpj', 
                                            'name' => $this->l('CPF and CNPJ'),
                                          ),
                                          array(
                                            'id_mode' => 'cpf-only',
                                            'name' => $this->l('CPF Only'),
                                          ),
                                          array(
                                            'id_mode' => 'cnpj-only',
                                            'name' => $this->l('CNPJ Only'),
                                          ),
                                        ),                                          
                          ),
                        'name' => 'LDBR_CPF_CNPJ_MODE',
                    ),
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Ask for RG with CPF'),
                        'name' => 'LDBR_CPF_CNPJ_RG',
                        'is_bool' => true,
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Ask for IE (Inscrição Estadual) with CNPJ'),
                        'name' => 'LDBR_CPF_CNPJ_IE',
                        'is_bool' => true,
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Accept duplicate values'),
                        'name' => 'LDBR_ACCEPT_DUPLICATE_VALUES',
                        'is_bool' => true,
                        'desc' => $this->l('Accept duplicate values in CPF | CNPJ'),
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Ask for a Complementary Question'),
                        'desc' => $this->l('In order to customise the question, The text should be translated in the Prestashop translation interface'),
                        'name' => 'LDBR_ASK_COMP',
                        'is_bool' => true,
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
					array(
                        'type' => 'select',
                        'lang' => false,
                        'label' => $this->l('Mandatory'),
                        'required' => false,
                        'desc' => $this->l('Your clients will have to fill this information or not'),
                        'options' => array(
                            'id' => 'id_mandatory',
                            'name' => 'name', 
                            'query' => array(
                                          array(
                                            'id_mandatory' => 'yes',
                                            'name' => $this->l('Yes'),
                                          ),
                                          array(
                                            'id_mandatory' => 'yes-and-popup', 
                                            'name' => $this->l('Yes and show a popup on checkout (for users registred by Social login)'),
                                          ),
                                          
                                          array(
                                            'id_mandatory' => 'no', 
                                            'name' => $this->l('No'),
                                          ),
                                        ),                                          
                          ),
                        'name' => 'LDBR_CPF_CNPJ_MANDATORY',
                    ),
					array(
                        'type' => 'select',
                        'lang' => false,
                        'label' => $this->l('The customer permission'),
                        'required' => false,
                        'desc' => $this->l('After the custumer registration, define if they can change or not the data of their fiscal information'),
                        'options' => array(
                            'id' => 'id_perm',
                            'name' => 'name', 
                            'query' => array(
                                          array(
                                            'id_perm' => 'none', 
                                            'name' => $this->l('None: Only the administrator can change or add fiscal information'),
                                          ),
                                          array(
                                            'id_perm' => 'add',
                                            'name' => $this->l('Add: The customer can add missing information'),
                                          ),
										  array(
                                            'id_perm' => 'edit',
                                            'name' => $this->l('Edit: The customer can change the registred information'),
                                          ),
                                        ),
                          ),
                        'name' => 'LDBR_CUTOMER_PERMISSIONS',
                    ),
                ),
                'submit' => array(
                    'title' => $this->l('Save All'),
                    'name' => 'submitLDBrazilianRegisterModule-save',
                ),
            ),
        );
    }
    
    /**
     * Create the structure of your form.
     */
    protected function getConfigFormCEP()
    {
        return array(
            'form' => array(
                'legend' => array(
                'title' => $this->l('CEP Settings'),
                'icon' => 'icon-cogs',
                ),
                'input' => array(
                    array(
                        'type' => 'select',
                        'label' => $this->l('CEP Search mode'),
                        'name' => 'LDBR_CEP_MODE',
                        'is_bool' => true,
                        'desc' => $this->l('Choose the CEP search mode: It can  be manual, then the user have the option to click a button to initiate the search, or the search can start automatically when the CEP is digited. The automatic search can also prevent the user to change the adress information'),
                        'options' => array(
                            'id' => 'id_mode',
                            'name' => 'name', 
                            'query' => array(
                                array(
                                    'id_mode' => 'none', 
                                    'name' => $this->l('None'),
                                    ),
                                array(
                                    'id_mode' => 'manual', 
                                    'name' => $this->l('Manually'),
                                    ),
                                array(
                                    'id_mode' => 'auto',
                                    'name' => $this->l('Automatic'),
                                    ),
                                array(
                                    'id_mode' => 'auto_prevent',
                                    'name' => $this->l('Automatic and prevent'),
                                    ),
                            ),                                          
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'lang' => false,
                        'label' => $this->l('Choose a web service'),
                        'required' => false,
                        'hint' => $this->l('Select one of the Provider'),
                        'desc' => $this->l('More information:').
                            '<a target="blank" href="http://www.republicavirtual.com.br/" >www.republicavirtual.com.br</a> - 
                            <a target="blank" href="http://avisobrasil.com.br/" >www.avisobrasil.com.br</a> - 
                            <a target="blank" href="http://postmon.com.br/" >www.postmon.com.br</a> - 
                            <a target="blank" href="http://viacep.com.br/" >www.viacep.com.br</a><br />'.
                            $this->l('If you need to use another provider, feel free to ask us: ').'<a target="blank" href="http://ld.com.br/contato/" >'.$this->l('Contact').'</a>',
                        'options' => array(
                            'id' => 'id_mode',
                            'name' => 'name', 
                            'query' => array(
                                array(
                                    'id_mode' => 'republicavirtual', 
                                    'name' => $this->l('Republica Virtual'),
                                    ),
                                array(
                                    'id_mode' => 'avisobrasil',
                                    'name' => $this->l('Aviso Brasil'),
                                    ),
                                array(
                                    'id_mode' => 'postmon',
                                    'name' => $this->l('Postmon'),
                                    ),
                                array(
                                    'id_mode' => 'viacep',
                                    'name' => $this->l('Viacep'),
                                    ),
                            ),                                          
                        ),
                        'name' => 'LDBR_CEP_WEBSERVICE',
                    ),
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Don\'t know my CEP'),
                        'name' => 'LDBR_CEP_DK',
                        'is_bool' => true,
                        'desc' => $this->l('Show a "I Don\'t know my CEP" button. This button redirect\'s the user the correios page'),
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                ),
                'submit' => array(
                    'title' => $this->l('Save All'),
                    'name' => 'submitLDBrazilianRegisterModule-save',
                ),
            ),
        );
    }
    
    
    protected function getOthersConfig()
    {
        return array(
            'form' => array(
                'legend' => array(
                'title' => $this->l('Others options'),
                'icon' => 'icon-cogs',
                ),
                'input' => array(
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Show customer informations on the invoice'),
                        'name' => 'LDBR_CPF_CNPJ_PDF_INVOICE',
                        'is_bool' => true,
                        'desc' => $this->l('Show the CPF / CNPJ / RG / IE on the PDF invoice'),
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Add mascara on the phone number'),
                        'name' => 'LDBR_CEP_PHONES',
                        'is_bool' => true,
                        'desc' => $this->l('Format the phones numbers: (xx) xxxx-xxxx e (xx) 9xxxx-xxxx for mobile'),
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Show a specific field for the street number'),
                        'name' => 'LDBR_STREET_NUM',
                        'options' => array(
                                'id' => 'id_mode',
                                'name' => 'name', 
                                'query' => array(
                                              array(
                                                'id_mode' => 'no', 
                                                'name' => $this->l('No'),
                                              ),
                                              array(
                                                'id_mode' => 'yes',
                                                'name' => $this->l('Yes but not mandatory'),
                                              ),
                                              array(
                                                'id_mode' => 'yes_mand',
                                                'name' => $this->l('Yes, mandatory'),
                                              ),
                                            ),                                          
                              ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Show a specific field for the address complement'),
                        'name' => 'LDBR_STREET_COMPL',
                        'options' => array(
                                'id' => 'id_mode',
                                'name' => 'name', 
                                'query' => array(
                                              array(
                                                'id_mode' => 'no', 
                                                'name' => $this->l('No'),
                                              ),
                                              array(
                                                'id_mode' => 'yes',
                                                'name' => $this->l('Yes but not mandatory'),
                                              ),
                                              array(
                                                'id_mode' => 'yes_mand',
                                                'name' => $this->l('Yes, mandatory'),
                                              ),
                                            ),                                          
                              ),
                    ),
                ),
                'submit' => array(
                    'title' => $this->l('Save All'),
                    'name' => 'submitLDBrazilianRegisterModule-save',
                ),
            ),
        );
    }
    
    /**
     * Create the structure of your form.
     */
    protected function getCEPtest()
    {
        return array(
            'form' => array(
                'legend' => array(
                'title' => $this->l('CEP Testing'),
                'icon' => 'icon-cogs',
                ),
                'input' => array(
                    array(
                        'type' => 'select',
                        'lang' => false,
                        'label' => $this->l('Choose a web service for testing purpose'),
                        'required' => false,
                        'hint' => $this->l('Select one of the Provider'),
                        'desc' => $this->l('More information:').
                            '<a target="blank" href="http://www.republicavirtual.com.br/" >www.republicavirtual.com.br</a> - 
                            <a target="blank" href="http://avisobrasil.com.br/" >www.avisobrasil.com.br</a> - 
                            <a target="blank" href="http://postmon.com.br/" >www.postmon.com.br</a> - 
                            <a target="blank" href="http://viacep.com.br/" >www.viacep.com.br</a><br />'.
                            $this->l('If you need to use another provider, feel free to ask us: ').'<a target="blank" href="http://ld.com.br/contato/" >'.$this->l('Contact').'</a>',
                        'options' => array(
                            'id' => 'id_mode',
                            'name' => 'name', 
                            'query' => array(
                                          array(
                                            'id_mode' => 'republicavirtual', 
                                            'name' => $this->l('Republica Virtual'),
                                          ),
                                          array(
                                            'id_mode' => 'avisobrasil',
                                            'name' => $this->l('Aviso Brasil'),
                                          ),
                                          array(
                                            'id_mode' => 'postmon',
                                            'name' => $this->l('Postmon'),
                                          ),
                                          array(
                                            'id_mode' => 'viacep',
                                            'name' => $this->l('Viacep'),
                                          ),
                                        ),                                          
                          ),
                        'name' => 'LDBR_CEP_TEST_WEBSERVICE',
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('CEP to be tested'),
                        'name' => 'LDBR_CEP_TEST_NUM',
                        'desc' => $this->l('Choose one of the CEP provider, enter a CEP and click "TEST"').'<div id="resultCEP" dataurl="'.$this->context->link->getModuleLink('ldbrazilianregister', 'cep', array(), true).'" ></div>',
                    ),
                ),
                'submit' => array(
                    'title' => $this->l('TEST'),
                    'icon' => 'icon-magic',
                    'name' => 'submitLDBrazilianRegisterModule-test',
                    'id' => 'ajax-test',
                ),
            ),
        );
    }
    
    protected function getDataImport()
    {
        return array(
            'form' => array(
                'legend' => array(
                'title' => $this->l('Import Customers data'),
                'icon' => 'icon-cogs',
                ),
                'input' => array(
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Import Action'),
                        'name' => 'LDBR_IMPORT_ACTION',
                        'is_bool' => true,
                        'desc' => $this->l('Yes: Real Import | No: SQL Test only'),
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => true,
                                'label' => $this->l('Import')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => false,
                                'label' => $this->l('Test')
                            )
                        ),
                    ),
                    array(
                        'type' => 'textarea',
                        'label' => $this->l('Advanced Users ONLY - SQL Query'),
                        'name' => 'LDBR_IMPORT_QUERY',
                        'desc' => $this->l('The expected colums are: ').'id_customer | cpf | cnpj | cpf_or_cnpj | rg_or_ie . <div id="resultImport" ></div>',
                    ),
                ),
                'submit' => array(
                        'title' => $this->l('IMPORT'),
                        'icon' => 'icon-magic',
                        'name' => 'submitLDBrazilianRegisterModule-import',
                ),
            ),
        );
    }

    /**
     * Set values for the inputs.
     */
    protected function getConfigFormValues()
    {
        return array(
            'LDBR_CPF_CNPJ_ACTIVE' => Configuration::get('LDBR_CPF_CNPJ_ACTIVE'),
            'LDBR_VERSAOPHP' => Configuration::get('LDBR_VERSAOPHP'),
            'LDBR_CPF_CNPJ_MODE' => Configuration::get('LDBR_CPF_CNPJ_MODE'),
            'LDBR_CPF_CNPJ_RG' => Configuration::get('LDBR_CPF_CNPJ_RG'),
            'LDBR_CPF_CNPJ_IE' => Configuration::get('LDBR_CPF_CNPJ_IE'),
            'LDBR_ACCEPT_DUPLICATE_VALUES' => Configuration::get('LDBR_ACCEPT_DUPLICATE_VALUES'),
            'LDBR_ASK_COMP' => Configuration::get('LDBR_ASK_COMP'),
            'LDBR_CPF_CNPJ_MANDATORY' => Configuration::get('LDBR_CPF_CNPJ_MANDATORY'),
            'LDBR_CUTOMER_PERMISSIONS' => Configuration::get('LDBR_CUTOMER_PERMISSIONS'),
            'LDBR_CEP_DK' => Configuration::get('LDBR_CEP_DK'),
            'LDBR_CEP_MODE' => Configuration::get('LDBR_CEP_MODE'),
            'LDBR_CEP_WEBSERVICE' => Configuration::get('LDBR_CEP_WEBSERVICE'),
            'LDBR_CEP_TEST_NUM' => Configuration::get('LDBR_CEP_TEST_NUM'),
            'LDBR_CEP_TEST_WEBSERVICE' => Configuration::get('LDBR_CEP_TEST_WEBSERVICE'),
            'LDBR_CPF_CNPJ_PDF_INVOICE' => Configuration::get('LDBR_CPF_CNPJ_PDF_INVOICE'),
            'LDBR_CEP_PHONES' => Configuration::get('LDBR_CEP_PHONES'),
            'LDBR_STREET_NUM' => Configuration::get('LDBR_STREET_NUM'),
            'LDBR_STREET_COMPL' => Configuration::get('LDBR_STREET_COMPL'),
            'LDBR_IMPORT_QUERY' => Configuration::get('LDBR_IMPORT_QUERY'),
            'LDBR_IMPORT_ACTION' => Configuration::get('LDBR_IMPORT_ACTION'),
        );
    }

    /**
     * Save form data.
     */
    protected function postProcess()
    {
		$this->sendUsageStats();
        $form_values = $this->getConfigFormValues();

        foreach (array_keys($form_values) as $key){
            Configuration::updateValue($key, Tools::getValue($key));
		}
            
        //import
        if (((bool)Tools::isSubmit('submitLDBrazilianRegisterModule-import')) == true){
            $query = Configuration::get('LDBR_IMPORT_QUERY');
            $import = Configuration::get('LDBR_IMPORT_ACTION');
            
            if (!empty($query) && $results = Db::getInstance()->ExecuteS($query)) {
                $results = BrazilianRegister::importByRawData($results, (bool)$import);
                if((bool)$import === false){
                    $this->context->smarty->assign('import_res', $results);
                }
            }
        } else {
            return $this->displayConfirmation($this->l('Settings updated'));
        }
    }
    
    /**
     * Add the CSS & JavaScript files you want to be added on the FO.
     */
    public function hookHeader()
    {
        if (!$this->active) {
            return;
		}
                
		if($this->context->controller->php_self == 'my-account'){
			$this->context->controller->addCSS($this->_path.'/views/css/front-my-account.css');
		}
		
        if($this->context->controller->php_self == 'address' || $this->context->controller->php_self == 'order') {
            $this->context->controller->addJS($this->_path.'views/js/jquery.mask.mod.js');
            $this->context->controller->addCSS($this->_path.'views/css/address.css');
            $this->context->controller->addJS($this->_path.'views/js/address.js');
            
            $jsDef = array(
                'cep_search_mode' => Configuration::get('LDBR_CEP_MODE'),
                'cep_dk_button' => (bool)Configuration::get('LDBR_CEP_DK'),
                'cep_ws_url' => $this->context->link->getModuleLink('ldbrazilianregister', 'cep', array(), true),
                'phones_mask' => (bool)Configuration::get('LDBR_CEP_PHONES'),
                'street_num' => Configuration::get('LDBR_STREET_NUM'),
                'street_compl' => Configuration::get('LDBR_STREET_COMPL'),
                'translated_num' => $this->l('Number'),
                'translated_comp' => $this->l('Complement'));
            Media::addJsDef($jsDef);
        }
        
        if($this->context->controller->php_self == 'authentication' || $this->context->controller->php_self == 'order') {
            $this->context->controller->addJS($this->_path.'views/js/jquery.mask.mod.js');
            $this->context->controller->addJS($this->_path.'views/js/authentication.js');
        }
		
		//check if fiscal information is complete and if popup is necessary
		if($this->context->controller->php_self == 'order') {
			if($this->context->customer->isLogged(true)){
				if(Configuration::get('LDBR_CPF_CNPJ_MANDATORY') == 'yes-and-popup' && (bool)Configuration::get('LDBR_CPF_CNPJ_ACTIVE') == true) {
					$mode = Configuration::get('LDBR_CPF_CNPJ_MODE');
					$breg = BrazilianRegister::getByCustomerId($this->context->customer->id);
					$showPopUp = false;
					$breg['cpf'];
					$breg['cnpj'];
					
					if($mode == 'cpf-or-cnpj' || $mode == 'cpf-or-cnpj-or-passport') {
						if(empty($breg['cpf'].$breg['cnpj'].$breg['passport'])){
							$showPopUp = true;
						}
					} elseif($mode == 'cpf-and-cnpj') {
						if(empty($breg['cpf']) || empty($breg['cnpj'])){
							$showPopUp = true;
						}
					} elseif($mode == 'cpf-only') {
						if(empty($breg['cpf'])){
							$showPopUp = true;
						}
					} elseif($mode == 'cnpj-only') {
						if(empty($breg['cnpj'])){
							$showPopUp = true;
						}
					}
					
					if($showPopUp){
						$jsDef = array(
							'fiscal_popup_url' => $this->context->link->getModuleLink('ldbrazilianregister', 'fiscalinformation', array(
								'popup_mode' => 1,
								'content_only' => 1,
							), true),
							'cpf_cnpj_mode' => $mode,
						);
						Media::addJsDef($jsDef);
						
						$this->context->controller->addJS($this->_path.'views/js/jquery.fancybox.min.js');
						$this->context->controller->addCSS($this->_path.'views/css/jquery.fancybox.min.css');
						
						$this->context->controller->addJS($this->_path.'views/js/order-popup.js');
					}
				}
			}
		}
    }

    /**
    * Add the CSS & JavaScript files you want to be loaded in the BO.
    */
    public function hookBackOfficeHeader()
    {
        if (Tools::getValue('module_name') == $this->name)
        {
            $this->context->controller->addJquery();
            $this->context->controller->addJS($this->_path.'views/js/jquery.mask.mod.js');
            $this->context->controller->addJS($this->_path.'views/js/back.js');
            $this->context->controller->addCSS($this->_path.'views/css/back.css');
        }
    }
    
    
    public function hookCreateAccount($params)
    {
        if (!$this->active)
            return;
        
        
        $id_customer = $params['newCustomer']->id;
        $mode = Configuration::get('LDBR_CPF_CNPJ_MODE');
        
        if($mode == 'cpf-or-cnpj' || $mode == 'cpf-or-cnpj-or-passport') {
            $data = array();
            $doc_type = Tools::getValue('document_type');
            $doc_value = Tools::getValue('document_number');
            $rg = Tools::getValue('rg', null);
            $ie = Tools::getValue('ie', null);
            $comp = Tools::getValue('complementary_question', null);
            $doc_value = preg_replace('/[^0-9]/', '', $doc_value);
            
            $data[pSQL($doc_type)] = pSQL($doc_value);
            $data['rg'] = pSQL($rg);
            $data['ie'] = pSQL($ie);
            $data['comp'] = pSQL($comp);
            BrazilianRegister::insertByCustomerId($id_customer, $data);
            
        } elseif($mode == 'cpf-and-cnpj') {
            $br_document_cpf = Tools::getValue('cpf');
            $br_document_cnpj = Tools::getValue('cnpj');
            $rg = Tools::getValue('rg', null);
            $ie = Tools::getValue('ie', null);
            $comp = Tools::getValue('complementary_question', null);
            $br_document_cpf = preg_replace('/[^0-9]/', '', $br_document_cpf);
            $br_document_cnpj = preg_replace('/[^0-9]/', '', $br_document_cnpj);
            BrazilianRegister::insertByCustomerId($id_customer, array('cpf' => pSQL($br_document_cpf), 'cnpj' => pSQL($br_document_cnpj), 'rg' => $rg, 'ie' => $ie, 'comp' => pSQL($comp)));
        
        } elseif($mode == 'cpf-only') {
            $br_document_cpf = Tools::getValue('cpf');
            $rg = Tools::getValue('rg', null);
            $comp = Tools::getValue('complementary_question', null);
            $br_document_cpf = preg_replace('/[^0-9]/', '', $br_document_cpf);
            BrazilianRegister::insertByCustomerId($id_customer, array('cpf' => pSQL($br_document_cpf), 'rg' => $rg, 'comp' => pSQL($comp)));
        
        } elseif($mode == 'cnpj-only') {
            $br_document_cnpj = Tools::getValue('cnpj');
            $ie = Tools::getValue('ie', null);
            $comp = Tools::getValue('complementary_question', null);
            $br_document_cnpj = preg_replace('/[^0-9]/', '', $br_document_cnpj);
            BrazilianRegister::insertByCustomerId($id_customer, array('cnpj' => pSQL($br_document_cnpj), 'ie' => $ie,  'comp' => pSQL($comp)));
        }
    }
	
	public function hookDisplayCustomerAccount($params) {
		if (!$this->active || Configuration::get('LDBR_CUTOMER_PERMISSIONS') == 'none') {
			return;
		}
                
		return $this->display(__FILE__, 'views/templates/hook/my-account-link.tpl');
	}
    
    //public function hookDisplayCustomerIdentityForm($params)
    //{
    //    if (!$this->active)
    //        return;
    //    
    //    $this->smarty->assign('customer_permissions', Configuration::get('LDBR_CUTOMER_PERMISSIONS'));
    //    
    //    //return $this->cpfAndCnpjHook($params, 'identity');
    //}

    public function hookDisplayHeader()
    {
        return $this->hookHeader();
    }
    
    public function hookDisplayPDFInvoice($params)
    {
        if (!$this->active)
            return;
       
        if((bool)Configuration::get('LDBR_CPF_CNPJ_PDF_INVOICE') == false)
            return;
            
        $order = new Order($params['object']->id_order);
        $breg = BrazilianRegister::getByCustomerId($order->id_customer);
        $br_document_cpf = $breg['cpf'];
        $br_document_cnpj = $breg['cnpj'];
        $br_document_rg = $breg['rg'];
        $br_document_ie = $breg['ie'];
        $br_document_comp = null;
        if((bool)Configuration::get('LDBR_ASK_COMP') == true){
            $br_document_comp = '<br />Comp: '.$breg['comp'];
        }
        return  'CPF: '.LDbrazilianregister::mascaraString('###.###.###-##', $br_document_cpf).
                '<br />CNPJ: '.LDbrazilianregister::mascaraString('##.###.###/####-##', $br_document_cnpj).
                '<br />RG: '.$br_document_rg.
                '<br />IE: '.$br_document_ie.
                $br_document_comp;
    }
    
    public function hookDisplayAdminOrderTabOrder($params) {
        if (!$this->active)
        return;
    
        return $this->display(__FILE__, 'views/templates/hook/admin-order-tab.tpl');
    }
    
    public function hookDisplayAdminOrderContentOrder($params)
    {
        if (!$this->active)
        return;
    
        $customer = $params['customer'];
        $breg = BrazilianRegister::getByCustomerId($customer->id);
        $br_document_cpf = $breg['cpf'];
        $br_document_cnpj = $breg['cnpj'];
        $br_document_rg = $breg['rg'];
        $br_document_ie = $breg['ie'];
        
        $this->smarty->assign(array(
            'br_document_cpf' => $br_document_cpf,
            'br_document_cnpj' => $br_document_cnpj,
            'br_document_rg' => $br_document_rg,
            'br_document_ie' => $br_document_ie,
        ));
            
        return $this->display(__FILE__, 'views/templates/hook/admin-order-content.tpl');
    }
    
    public function hookActionObjectCustomerDeleteAfter($params)
    {
        BrazilianRegister::deleteByCustomerId($params['object']->id);
    }
    
    public function checkForDuplicateValues($type, $value) {
        if ($value != '')
        {
        switch ($type) {
            case 'cpf':
                return BrazilianRegister::cpfExist($value);
            case 'cnpj':
                return BrazilianRegister::cnpjExist($value);
            case 'passport':
                return BrazilianRegister::passportExist($value);
        }
        }
    }
    
    public function hookValidateCustomerFormFields($params) {
        if((bool)Configuration::get('LDBR_CPF_CNPJ_ACTIVE') == true) {
            $mode = Configuration::get('LDBR_CPF_CNPJ_MODE');
            $mandatory = true;
			if(Configuration::get('LDBR_CPF_CNPJ_MANDATORY') == 'no'){
				$mandatory = false;
			}
            $ask_rg = (bool)Configuration::get('LDBR_CPF_CNPJ_RG');
            $ask_ie = (bool)Configuration::get('LDBR_CPF_CNPJ_IE');
            $ask_comp = (bool)Configuration::get('LDBR_ASK_COMP');
            $acceptDuplicates = (bool)Configuration::get('LDBR_ACCEPT_DUPLICATE_VALUES');
            
            $values = array();
            $fields = array();
            
            $error_cpf = $this->l('The filled CPF is not valid');
            $error_cpf_empty = $this->l('The CPF has to be filled');
            $error_cpf_duplicate = $this->l('This CPF is already registred');
            $error_cnpj = $this->l('The filled CNPJ is not valid');
            $error_cnpj_empty = $this->l('The CNPJ has to be filled');
            $error_cnpj_duplicate = $this->l('This CNPJ is already registred');
            $error_rg = $this->l('The RG have to be filled');
            $error_ie = $this->l('The IE have to be filled');
            
            foreach($params['fields'] as $formField){
                $fields[$formField->getName()] = $formField;
                $values[$formField->getName()] = $formField->getValue();
            }
            
            /*if(empty($values['rg']) && $ask_rg && $mandatory){
                if($mode == 'cpf-and-cnpj' || $mode == 'cpf-only') {
                    $fields['rg']->addError($error_rg);
                }
                if($values['document_type'] == 'cpf' && ($mode == 'cpf-or-cnpj-or-passport' || $mode == 'cpf-or-cnpj')){
                    $fields['rg']->addError($error_rg);
                }
				if($values['document_type'] == 'cnpj' && ($mode == 'cpf-or-cnpj-or-passport' || $mode == 'cpf-or-cnpj')){
                    $fields['rg']->setRequired(0);
                }
            }
            if(empty($values['ie']) && $ask_ie && $mandatory){
                if($mode == 'cpf-and-cnpj' || $mode == 'cnpj-only') {
                    $fields['ie']->addError($error_ie);
                }
                if($values['document_type'] == 'cnpj' && ($mode == 'cpf-or-cnpj-or-passport' || $mode == 'cpf-or-cnpj')){
                    $fields['ie']->addError($error_ie);
                }
				if($values['document_type'] == 'cpf' && ($mode == 'cpf-or-cnpj-or-passport' || $mode == 'cpf-or-cnpj')){
				   $fields['ie']->setRequired(0);
                }
            }*/
            
            if($mode == 'cpf-or-cnpj-or-passport' || $mode == 'cpf-or-cnpj'){
                if($values['document_type'] == 'cpf') {
                    if(empty($values['document_number']) && $mandatory){
                        $fields['document_number']->addError($error_cpf_empty);
                    } elseif(!LDbrazilianregister::validateCPF($values['document_number'])){
                        $fields['document_number']->addError($error_cpf);
                    } elseif(!$acceptDuplicates && $this->checkForDuplicateValues('cpf', $values['document_number'])){
                        $fields['document_number']->addError($error_cpf_duplicate);
                    }
                } elseif($values['document_type'] == 'cnpj'){
                    if(empty($values['document_number']) && $mandatory){
                        $fields['document_number']->addError($error_cnpj_empty);
                    } elseif(!LDbrazilianregister::validateCNPJ($values['document_number'])){
                        $fields['document_number']->addError($error_cnpj);
                    } elseif(!$acceptDuplicates && $this->checkForDuplicateValues('cnpj', $values['document_number'])){
                        $fields['document_number']->addError($error_cnpj_duplicate);
                    }
                }
            } elseif($mode == 'cpf-and-cnpj'){
                if(empty($values['cpf']) && $mandatory){
                    $fields['cpf']->addError($error_cpf_empty);
                } elseif(!LDbrazilianregister::validateCPF($values['cpf'])){
                    $fields['cpf']->addError($error_cpf);
                } elseif(!$acceptDuplicates && $this->checkForDuplicateValues('cpf', $values['cpf'])){
                    $fields['cpf']->addError($error_cpf_duplicate);
                }
                if(empty($values['cnpj']) && $mandatory){
                    $fields['cnpj']->addError($error_cnpj_empty);
                } elseif(!LDbrazilianregister::validateCNPJ($values['cnpj'])){
                    $fields['cnpj']->addError($error_cnpj);
                } elseif(!$acceptDuplicates && $this->checkForDuplicateValues('cnpj', $values['cnpj'])){
                    $fields['cnpj']->addError($error_cnpj_duplicate);
                }
            } elseif($mode == 'cpf-only'){
                if(empty($values['cpf']) && $mandatory){
                    $fields['cpf']->addError($error_cpf_empty);
                } elseif(!LDbrazilianregister::validateCPF($values['cpf'])){
                    $fields['cpf']->addError($error_cpf);
                } elseif(!$acceptDuplicates && $this->checkForDuplicateValues('cpf', $values['cpf'])){
                    $fields['cpf']->addError($error_cpf_duplicate);
                }
            } elseif($mode == 'cnpj-only'){
                if(empty($values['cnpj']) && $mandatory){
                    $fields['cnpj']->addError($error_cnpj_empty);
                } elseif(!LDbrazilianregister::validateCNPJ($values['cnpj'])){
                    $fields['cnpj']->addError($error_cnpj);
                } elseif(!$acceptDuplicates && $this->checkForDuplicateValues('cnpj', $values['cnpj'])){
                    $fields['cnpj']->addError($error_cnpj_duplicate);
                }
            }
        }
        return $params['fields'];
    }
    
    public function hookAdditionalCustomerFormFields($params) {
        
		$fields = array();
		if($this->context->controller->php_self == 'identity') {
			return $fields;
		}
		
        if((bool)Configuration::get('LDBR_CPF_CNPJ_ACTIVE') == true) {
            $mode = Configuration::get('LDBR_CPF_CNPJ_MODE');
            $mandatory = true;
			if(Configuration::get('LDBR_CPF_CNPJ_MANDATORY') == 'no'){
				$mandatory = false;
			}
            $ask_rg = (bool)Configuration::get('LDBR_CPF_CNPJ_RG');
            $ask_ie = (bool)Configuration::get('LDBR_CPF_CNPJ_IE');
            $ask_comp = (bool)Configuration::get('LDBR_ASK_COMP');
            
            $label_cpf = $this->l('CPF');
            $label_cnpj = $this->l('CNPJ');
            $label_rg = $this->l('RG');
            $label_ie = $this->l('IE');
            $label_passport = $this->l('Passport');
            $label_document_type = $this->l('Document type');
            $label_document_number = $this->l('Document number');
            $label_complementary_question = $this->l('Complementary question');

            if($mode == 'cpf-or-cnpj-or-passport'){
                $fields[] = (new FormField())->setName('document_type')->setType('radio-buttons')->setLabel($label_document_type)->setAvailableValues(array(
                    'cpf' => $label_cpf,
                    'cnpj' => $label_cnpj,
                    'passport' => $label_passport,
                ))->setValue('cpf');
                $fields[] = (new FormField())->setName('document_number')->setType('text')->setLabel($label_document_number)->setRequired($mandatory);
            } elseif($mode == 'cpf-or-cnpj'){
                $fields[] = (new FormField())->setName('document_type')->setType('radio-buttons')->setLabel($label_document_type)->setAvailableValues(array(
                    'cpf' => $label_cpf,
                    'cnpj' => $label_cnpj,
                ))->setValue('cpf');
                $fields[] = (new FormField())->setName('document_number')->setType('text')->setLabel($label_document_number)->setRequired($mandatory);
            } elseif($mode == 'cpf-and-cnpj'){
                $fields[] = (new FormField())->setName('cpf')->setType('text')->setLabel($label_cpf)->setRequired($mandatory);
                $fields[] = (new FormField())->setName('cnpj')->setType('text')->setLabel($label_cnpj)->setRequired($mandatory);
            } elseif($mode == 'cpf-only'){
                $fields[] = (new FormField())->setName('cpf')->setType('text')->setLabel($label_cpf)->setRequired($mandatory);
            } elseif($mode == 'cnpj-only'){
                $fields[] = (new FormField())->setName('cnpj')->setType('text')->setLabel($label_cnpj)->setRequired($mandatory);
            }
            
            if($ask_rg && ($mode == 'cpf-or-cnpj-or-passport' || $mode == 'cpf-or-cnpj' || $mode == 'cpf-and-cnpj' || $mode == 'cpf-only')){
                $fields[] = (new FormField())->setName('rg')->setType('text')->setLabel($label_rg)->setRequired(false);
            }
            if($ask_ie && ($mode == 'cpf-or-cnpj-or-passport' || $mode == 'cpf-or-cnpj' || $mode == 'cpf-and-cnpj' || $mode == 'cnpj-only')){
                $fields[] = (new FormField())->setName('ie')->setType('text')->setLabel($label_ie)->setRequired(false);
            }
            if($ask_comp){
                $fields[] = (new FormField())->setName('complementary_question')->setType('text')->setLabel($label_complementary_question)->setRequired(false);
            }
        }
        return $fields;
    }
    public function hookDisplayAdminCustomers($params)
    {
        if (!$this->active)
        return ;

        $customer = new Customer((int)($params['id_customer']));
        $breg = BrazilianRegister::getByCustomerId($customer->id);
        $br_document_cpf = $breg['cpf'];
        $br_document_cnpj = $breg['cnpj'];
        $br_document_rg = $breg['rg'];
        $br_document_ie = $breg['ie'];
        $br_document_comp = $breg['comp'];
        
        $this->smarty->assign(array(
            'br_document_cpf' => $br_document_cpf,
            'br_document_cnpj' => $br_document_cnpj,
            'br_document_rg' => $br_document_rg,
            'br_document_ie' => $br_document_ie,
            'br_document_comp' => $br_document_comp,
        ));
            
        return $this->display(__FILE__, 'views/templates/hook/admin-customer.tpl');
    }
    
    /*public function cpfAndCnpjHook($params, $display)
    {
        if((bool)Configuration::get('LDBR_CPF_CNPJ_ACTIVE') == true) {
            $mode = Configuration::get('LDBR_CPF_CNPJ_MODE');
            $mandatory = (bool)Configuration::get('LDBR_CPF_CNPJ_MANDATORY');
            $ask_rg = (bool)Configuration::get('LDBR_CPF_CNPJ_RG');
            $ask_ie = (bool)Configuration::get('LDBR_CPF_CNPJ_IE');
            $ask_comp = (bool)Configuration::get('LDBR_ASK_COMP');
            
            $breg = BrazilianRegister::getByCustomerId($params['cookie']->id_customer);
            $br_document_cpf = $breg['cpf'];
            $br_document_cnpj = $breg['cnpj'];
            $br_document_passport = $breg['passport'];
            $br_document_rg = $breg['rg'];
            $br_document_ie = $breg['ie'];
            $br_document_comp = $breg['comp'];
            $br_document = ''; //CPF or CNPJ value
            
            $id_cp_mode = 'cpf';
            if($mode == 'cpf-or-cnpj' || $mode == 'cpf-or-cnpj-or-passport') {
                if(!empty($br_document_cpf)){
                    $id_cp_mode = 'cpf';
                    $br_document = $br_document_cpf;
                } elseif(!empty($br_document_cnpj)) {
                    $id_cp_mode = 'cnpj';
                    $br_document = $br_document_cnpj;
                } elseif(!empty($br_document_passport)){
                    $id_cp_mode = 'passport';
                    $br_document = $br_document_passport;
                }
            }
            
            $this->smarty->assign(array(
                'display' => $display,
                'mode' => $mode,
                'mandatory' => $mandatory,
                'ask_rg' => $ask_rg,
                'ask_ie' => $ask_ie,
                'ask_comp' => $ask_comp,
                'id_cp_mode' => $id_cp_mode,
                'br_document' => $br_document,
                'br_document_cpf' => $br_document_cpf,
                'br_document_cnpj' => $br_document_cnpj,
                'br_document_rg' => $br_document_rg,
                'br_document_ie' => $br_document_ie,
                'br_document_comp' => $br_document_comp,
            ));

            return $this->display(__FILE__, 'views/templates/hook/cpf-cnpj-'.$display.'.tpl');
        }
    }*/
    
    public static function validateCPF($cpf)
    {
        
        $cpf = preg_replace('/[^0-9]/', '', $cpf);
        $cpf = str_pad($cpf, 11, '0', STR_PAD_LEFT);
        
        if (Tools::strlen($cpf) != 11)
            return false;
        
        if ($cpf == '00000000000')
            $cpf = '';
        
        if ($cpf == '12345678909' || 
        $cpf == '00000000000' || 
        $cpf == '11111111111' || 
        $cpf == '22222222222' || 
        $cpf == '33333333333' || 
        $cpf == '44444444444' || 
        $cpf == '55555555555' || 
        $cpf == '66666666666' || 
        $cpf == '77777777777' || 
        $cpf == '88888888888' || 
        $cpf == '99999999999') {
            return false;
        }
        
        if (Tools::strlen($cpf) == 0)
        {
            return true;
        } else {
            for ($t = 9; $t < 11; $t++) {
                for ($d = 0, $c = 0; $c < $t; $c++) {
                    $d += $cpf{$c} * (($t + 1) - $c);
                }
                $d = ((10 * $d) % 11) % 10;
                if ($cpf{$c} != $d) {
                    return false;
                }
            }
        }
    
        
        return true;
    }
    
    public static function validateCNPJ($cnpj)
    {
        if (Tools::strlen($cnpj) == 0){
            return True;
        } else {
        $cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj);
        // Validate Size
        if (Tools::strlen($cnpj) != 14)
            return false;
        // Validate first control digit 
        for ($i = 0, $j = 5, $sum = 0; $i < 12; $i++)
        {
            $sum += $cnpj{$i} * $j;
            $j = ($j == 2) ? 9 : $j - 1;
        }
        $rest = $sum % 11;
        if ($cnpj{12} != ($rest < 2 ? 0 : 11 - $rest))
            return false;
        // Validate second control digit
        for ($i = 0, $j = 6, $sum = 0; $i < 13; $i++)
        {
            $sum += $cnpj{$i} * $j;
            $j = ($j == 2) ? 9 : $j - 1;
        }
        $rest = $sum % 11;
        return $cnpj{13} == ($rest < 2 ? 0 : 11 - $rest);
        }
    }
    
    public static function mascaraString($mascara,$string)
    {
         for($i=0;$i<Tools::strlen($string);$i++)
        {
             $mascara[Tools::strpos($mascara,'#')] = $string[$i];
        }
        return $mascara;
    }
	
	public function getPath()
    {
        return $this->_path;
    }
}
