<?php

class ControllerSaleCustomer extends Controller
{
    private $error = array();

    private $displayinfo = false;

    public function index()
    {

        $language = $this->language->load('sale/customer');
        $this->data = array_merge($this->data, $language);

        $this->document->setTitle($this->language->get('heading_title'));

        $this->data['showECommerceLinks'] = $this->config->get('config_sistema_ecommerce');
        $this->data['showMarketplaceLinks'] = $this->config->get('config_sistema_marketplace');

        $this->load->model('sale/customer');

        $this->getList();

    }

    public function insert()
    {
        $this->document->addScript("view/public/js/sale/customer.js");

        $this->language->load('sale/customer');

        $this->document->setTitle($this->language->get('heading_title'));

        $this->load->model('sale/customer');

    
        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
            $this->model_sale_customer->addCustomer($this->request->post);

            $this->session->data['success'] = $this->language->get('text_success_insert');

            $url = '';

            if (isset($this->request->get['filter_name'])) {
                $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
            }

            if (isset($this->request->get['filter_email'])) {
                $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
            }

            if (isset($this->request->get['filter_customer_group_id'])) {
                $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
            }

            if (isset($this->request->get['filter_status'])) {
                $url .= '&filter_status=' . $this->request->get['filter_status'];
            }

            if (isset($this->request->get['filter_email_validate']) && $this->config->get('email_validation_status') == 1) {
                $url .= '&filter_email_validate=' . $this->request->get['filter_email_validate'];
            }

            if (isset($this->request->get['filter_approved'])) {
                $url .= '&filter_approved=' . $this->request->get['filter_approved'];
            }

            if (isset($this->request->get['filter_origem_cadastro'])) {
                $url .= '&filter_origem_cadastro=' . $this->request->get['filter_origem_cadastro'];
            }

            if (isset($this->request->get['filter_pessoa'])) {
                $url .= '&filter_pessoa=' . $this->request->get['filter_pessoa'];
            }

            if (isset($this->request->get['filter_cpf_cnpj'])) {
                $url .= '&filter_cpf_cnpj=' . $this->request->get['filter_cpf_cnpj'];
            }

            if (isset($this->request->get['filter_ip'])) {
                $url .= '&filter_ip=' . $this->request->get['filter_ip'];
            }

            if (isset($this->request->get['filter_date_added'])) {
                $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
            }

            if (isset($this->request->get['filter_limiter_lock'])) {
                $url .= '&filter_limiter_lock=' . $this->request->get['filter_limiter_lock'];
            }

            if (isset($this->request->get['sort'])) {
                $url .= '&sort=' . $this->request->get['sort'];
            }

            if (isset($this->request->get['order'])) {
                $url .= '&order=' . $this->request->get['order'];
            }

            if (isset($this->request->get['page'])) {
                $url .= '&page=' . $this->request->get['page'];
            }

            $this->redirect($this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
        }

        $this->getForm();
    }

    public function update()
    {
        $this->language->load('sale/customer');
        $this->load->type('tipocomum');
        $this->load->type('tipomarketplace');
        $this->load->helper('ftr_geral');
        $this->load->model('sale/customer');
        $this->document->addScript("view/public/js/sale/customer.js");

        $this->displayinfo = true;

        $customer = $this->model_sale_customer->getCustomer($this->request->get['customer_id']);

        $this->data['disable_perfil_pj'] = ($this->config->get('fields_register_brazil_status_perfil_pj') == Type_Status::Tp_Desabilitado);
        $this->data['disable_contribuinte_pj'] = ($this->config->get('fields_register_brazil_status_contribuinte_pj') == Type_Status::Tp_Desabilitado);
        $this->data['disable_ie_pj'] = ($this->config->get('fields_register_brazil_status_ie_pj') == Type_Status::Tp_Desabilitado);
        $this->data['Type_StatusAccount'] = Type_StatusAccount::getEnumList();
        $this->data['approved'] = $customer['approved'];

        $this->document->setTitle($this->language->get('heading_title'));

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {

            $this->model_sale_customer->editCustomer($this->request->get['customer_id'], $this->request->post);

            $this->session->data['success'] = $this->language->get('text_success');

            $url = '';

            if (isset($this->request->get['filter_name'])) {
                $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
            }

            if (isset($this->request->get['filter_email'])) {
                $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
            }

            if (isset($this->request->get['filter_customer_group_id'])) {
                $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
            }

            if (isset($this->request->get['filter_status'])) {
                $url .= '&filter_status=' . $this->request->get['filter_status'];
            }

            if (isset($this->request->get['filter_email_validate']) && $this->config->get('email_validation_status') == 1) {
                $url .= '&filter_email_validate=' . $this->request->get['filter_email_validate'];
            }

            if (isset($this->request->get['filter_approved'])) {
                $url .= '&filter_approved=' . $this->request->get['filter_approved'];
            }

            if (isset($this->request->get['filter_origem_cadastro'])) {
                $url .= '&filter_origem_cadastro=' . $this->request->get['filter_origem_cadastro'];
            }

            if (isset($this->request->get['filter_pessoa'])) {
                $url .= '&filter_pessoa=' . $this->request->get['filter_pessoa'];
            }

            if (isset($this->request->get['filter_cpf_cnpj'])) {
                $url .= '&filter_cpf_cnpj=' . $this->request->get['filter_cpf_cnpj'];
            }

            if (isset($this->request->get['filter_ip'])) {
                $url .= '&filter_ip=' . $this->request->get['filter_ip'];
            }

            if (isset($this->request->get['filter_date_added'])) {
                $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
            }

            if (isset($this->request->get['filter_limiter_lock'])) {
                $url .= '&filter_limiter_lock=' . $this->request->get['filter_limiter_lock'];
            }

            if (isset($this->request->get['sort'])) {
                $url .= '&sort=' . $this->request->get['sort'];
            }

            if (isset($this->request->get['order'])) {
                $url .= '&order=' . $this->request->get['order'];
            }

            if (isset($this->request->get['page'])) {
                $url .= '&page=' . $this->request->get['page'];
            }

            $this->redirect($this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
        }

        $this->getForm();

    }

    public function getUrlLink($order = true)
    {

        $url = '';

        if (isset($this->request->get['filter_codl'])) {
            $url .= '&filter_codl=' . $this->request->get['filter_codl'];
        }

        if (isset($this->request->get['filter_codf'])) {
            $url .= '&filter_codf=' . $this->request->get['filter_codf'];
        }

        if (isset($this->request->get['filter_name'])) {
            $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_email'])) {
            $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_customer_group_id'])) {
            $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
        }

        if (isset($this->request->get['filter_status'])) {
            $url .= '&filter_status=' . $this->request->get['filter_status'];
        }

        if (isset($this->request->get['filter_email_validate']) && $this->config->get('email_validation_status') == 1) {
            $url .= '&filter_email_validate=' . $this->request->get['filter_email_validate'];
        }

        if (isset($this->request->get['filter_approved'])) {
            $url .= '&filter_approved=' . $this->request->get['filter_approved'];
        }

        if (isset($this->request->get['filter_origem_cadastro'])) {
            $url .= '&filter_origem_cadastro=' . $this->request->get['filter_origem_cadastro'];
        }

        if (isset($this->request->get['filter_integracao'])) {
            $url .= '&filter_integracao=' . $this->request->get['filter_integracao'];
        }

        if (isset($this->request->get['filter_marketplace'])) {
            $url .= '&filter_marketplace=' . $this->request->get['filter_marketplace'];
        }

        if (isset($this->request->get['filter_pessoa'])) {
            $url .= '&filter_pessoa=' . $this->request->get['filter_pessoa'];
        }

        if (isset($this->request->get['filter_cpf_cnpj'])) {
            $url .= '&filter_cpf_cnpj=' . $this->request->get['filter_cpf_cnpj'];
        }

        if (isset($this->request->get['filter_ip'])) {
            $url .= '&filter_ip=' . $this->request->get['filter_ip'];
        }

        if (isset($this->request->get['filter_date_added'])) {
            $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
        }

        if (isset($this->request->get['filter_uf'])) {
            $url .= '&filter_uf=' . $this->request->get['filter_uf'];
        }

        if (isset($this->request->get['filter_limiter_lock'])) {
            $url .= '&filter_limiter_lock=' . $this->request->get['filter_limiter_lock'];
        }

        $this->data['filter_count'] = count(explode('&', $url)) - 1;


        if ($order) {

            if (isset($this->request->get['sort'])) {
                $url .= '&sort=' . $this->request->get['sort'];
            }

            if (isset($this->request->get['order'])) {
                $url .= '&order=' . $this->request->get['order'];
            }

        }

        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }

        return $url;


    }

    private function changeTypeToTwig()
    {
        //aqui faz este procedimento com o Origem sistema pois ele alterna a forma de mostrar em tela se
        //for apenas Ecommerce ou Apenas Marketplace
        $show_ecommerce_links = $this->config->get('config_sistema_ecommerce');
        $show_marketplace_links = $this->config->get('config_sistema_marketplace');
        $origem_sistema_list = Type_OrigemSistema::getEnumList();
        if ($show_ecommerce_links && !$show_marketplace_links) {
            $key_to_remove = array_search(Type_OrigemSistema::getNickFromValue(Type_OrigemSistema::Tp_Marketplace), $origem_sistema_list);
            unset($origem_sistema_list[$key_to_remove]);
        }

        $this->data['filter_origem_cadastros'] = ftr_geral::setTypeInArray([
            'type' => $origem_sistema_list,
            'compare' => isset($this->request->get['filter_origem_cadastro']) ? $this->request->get['filter_origem_cadastro'] : null,
            'compare_type' => 'selected',
        ]);

        $this->data['filter_integracaos'] = ftr_geral::setTypeInArray([
            'type' => Type_MarketPlace::getEnumList(),
            'compare' => isset($this->request->get['filter_integracao']) ? $this->request->get['filter_integracao'] : null,
            'compare_type' => 'selected',
        ]);

        $this->data['filter_marketplace'] = ftr_geral::setTypeInArray([
            'type' => Type_MarketplaceInt::getEnumList(),
            'compare' => isset($this->request->get['filter_marketplace']) ? $this->request->get['filter_marketplace'] : null,
            'compare_type' => 'selected',
        ]);

        $this->data['filter_pessoa'] = ftr_geral::setTypeInArray([
            'type' => Type_CadastroPessoa::getEnumList(),
            'compare' => isset($this->request->get['filter_pessoa']) ? $this->request->get['filter_pessoa'] : null,
            'compare_type' => 'selected',
        ]);

        $this->data['contribuinte'] = ftr_geral::setTypeInArray([
            'type' => Type_PjContribuoIcms::getEnumList(),
            'compare' => isset($this->data['contribuinte']) ? $this->data['contribuinte'] : null,
            'compare_type' => 'selected',
        ]);

        $this->data['perfil'] = ftr_geral::setTypeInArray([
            'type' => Type_PerfilCustomerJuridico::getEnumList(),
            'compare' => isset($this->data['perfil']) ? $this->data['perfil'] : null,
            'compare_type' => 'selected',
        ]);

    }

    protected function getList()
    {

        $this->load->type('tipocomum');
        $this->load->type('tipomarketplace');

        $this->document->addScript(
            array(
                'public/js/page.customer.js'
            )
        );

        if (isset($this->request->get['filter_codl'])) {
            $filter_codl = $this->request->get['filter_codl'];
        } else {
            $filter_codl = null;
        }

        if (isset($this->request->get['filter_codf'])) {
            $filter_codf = $this->request->get['filter_codf'];
        } else {
            $filter_codf = null;
        }

        if (isset($this->request->get['filter_name'])) {
            $filter_name = $this->request->get['filter_name'];
        } else {
            $filter_name = null;
        }

        if (isset($this->request->get['filter_email'])) {
            $filter_email = $this->request->get['filter_email'];
        } else {
            $filter_email = null;
        }

        if (isset($this->request->get['filter_customer_group_id'])) {
            $filter_customer_group_id = $this->request->get['filter_customer_group_id'];
        } else {
            $filter_customer_group_id = null;
        }

        if (isset($this->request->get['filter_status'])) {
            $filter_status = $this->request->get['filter_status'];
        } else {
            $filter_status = null;
        }

        if (isset($this->request->get['filter_email_validate']) && $this->config->get('email_validation_status') == 1) {
            $filter_email_validate = $this->request->get['filter_email_validate'];
        } else {
            $filter_email_validate = null;
        }

        if (isset($this->request->get['filter_approved'])) {
            $filter_approved = $this->request->get['filter_approved'];
        } else {
            $filter_approved = null;
        }

        if (isset($this->request->get['filter_origem_cadastro'])) {
            $filter_origem_cadastro = $this->request->get['filter_origem_cadastro'];
        } else {
            $filter_origem_cadastro = null;
        }

        if (isset($this->request->get['filter_integracao'])) {
            $filter_integracao = $this->request->get['filter_integracao'];
        } else {
            $filter_integracao = null;
        }

        if (isset($this->request->get['filter_marketplace'])) {
            $filter_marketplace = $this->request->get['filter_marketplace'];
        } else {
            $filter_marketplace = null;
        }

        if (isset($this->request->get['filter_pessoa'])) {
            $filter_pessoa = $this->request->get['filter_pessoa'];
        } else {
            $filter_pessoa = null;
        }

        if (isset($this->request->get['filter_cpf_cnpj'])) {
            $filter_cpf_cnpj = $this->request->get['filter_cpf_cnpj'];
        } else {
            $filter_cpf_cnpj = null;
        }

        if (isset($this->request->get['filter_uf'])) {
            $filter_uf = $this->request->get['filter_uf'];
        } else {
            $filter_uf = null;
        }

        if (isset($this->request->get['filter_ip'])) {
            $filter_ip = $this->request->get['filter_ip'];
        } else {
            $filter_ip = null;
        }

        if (isset($this->request->get['filter_date_added'])) {
            $filter_date_added = $this->request->get['filter_date_added'];
        } else {
            $filter_date_added = null;
        }

        if (isset($this->request->get['filter_limiter_lock'])) {
            $filter_limiter_lock = $this->request->get['filter_limiter_lock'];
        } else {
            $filter_limiter_lock = null;
        }

        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'name';
        }

        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        } else {
            $order = 'ASC';
        }

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        $url = $this->getUrlLink();


        $this->data['breadcrumbs'] = array();

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => false
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'),
            'separator' => ' :: '
        );

        $this->data['approve'] = $this->url->link('sale/customer/approve', 'token=' . $this->session->data['token'] . $url, 'SSL');
        $this->data['insert'] = $this->url->link('sale/customer/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
        $this->data['delete'] = $this->url->link('sale/customer/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');

        $this->data['customers'] = array();

        $this->load->helper('ftr_geral');


        $data = array(
            'filter_codl' => $filter_codl,
            'filter_codf' => $filter_codf,
            'filter_name' => $filter_name,
            'filter_email' => $filter_email,
            'filter_customer_group_id' => $filter_customer_group_id,
            'filter_status' => $filter_status,
            'filter_approved' => $filter_approved,
            'filter_email_validate' => $filter_email_validate,
            'filter_origem_cadastro' => $filter_origem_cadastro,
            'filter_integracao' => $filter_integracao,
            'filter_marketplace' => $filter_marketplace,
            'filter_pessoa' => $filter_pessoa,
            'filter_cpf_cnpj' => $filter_cpf_cnpj,
            'filter_uf' => $filter_uf,
            'filter_date_added' => ftr_geral::formatDate($filter_date_added, 'en'),
            'filter_ip' => $filter_ip,
            'filter_limiter_lock' => $filter_limiter_lock,
            'sort' => $sort,
            'order' => $order,
            'start' => ($page - 1) * $this->config->get('config_admin_limit'),
            'limit' => $this->config->get('config_admin_limit')
        );

        $customer_total = $this->model_sale_customer->getTotalCustomers($data);

        $results = $this->model_sale_customer->getCustomers($data);

        foreach ($results as $result) {
            $lock = new limiterlock($this->registry);

            $this->data['customers'][] = array(
                'customer_id' => $result['customer_id'],
                'id_futura' => $result['id_futura'],
                'name' => $result['name'],
                'email' => $result['email'],
                'customer_group' => $result['customer_group'],
                'status' => ($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
                'approved' => ($result['approved'] ? $this->language->get('text_yes') : $this->language->get('text_no')),
                'valided' => ($this->config->get('email_validation_status') == 1 ? $result['valided'] : 1),
                'ip' => $result['ip'],
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                'origem_cadastro' => Type_OrigemSistema::getNickFromConstValue($result['origem_cadastro']),
                'selected' => isset($this->request->post['selected']) && in_array($result['customer_id'], $this->request->post['selected']),
                'lock' => $lock->operationsLock($result['time_lock'], $result['customer_id']),
                'href' => $this->url->link('sale/customer/update', 'token=' . $this->session->data['token'] . '&customer_id=' . $result['customer_id'] . $url, 'SSL')
            );
        }

        $this->data['token'] = $this->session->data['token'];

        $this->data['filter_email_validation_status'] = $this->config->get('email_validation_status');

        $this->load->model('localisation/zone');
        $states = $this->model_localisation_zone->getZonesByCountryId(Type_PaisId::Tp_Brasil);

        if (!is_null($filter_uf)) {
            $key = array_search($filter_uf, array_column($states, 'zone_id'));
            $states[$key]['status'] = ftr_geral::isSelected($filter_uf, $states[$key]['zone_id']);
        }

        $this->data['states'] = $states;

        if (isset($this->error['warning'])) {
            $this->data['error_warning'] = $this->error['warning'];
        } else {
            $this->data['error_warning'] = '';
        }

        if (isset($this->session->data['success'])) {
            $this->data['success'] = $this->session->data['success'];
            unset($this->session->data['success']);
        } else {
            $this->data['success'] = '';
        }

        $url = $this->getUrlLink(false);
        $orderLink = $url;

        if ($order == 'ASC') {
            $url .= '&order=ASC';
        } else {
            $url .= '&order=DESC';
        }

        $this->data['select_order'] = array(
            0 => array(
                'text' => 'Ordem Alfabética',
                'value' => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $orderLink . '&sort=name&order=ASC', 'SSL'),
                'selected' => false
            ),
            1 => array(
                'text' => 'Data de criação: Crescente',
                'value' => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $orderLink . '&sort=c.date_added&order=ASC', 'SSL'),
                'selected' => (isset($this->request->get['sort']) == 'c.date_added' && $this->request->get['order'] == 'ASC')
            ),
            2 => array(
                'text' => 'Data de criação: Decrescente',
                'value' => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $orderLink . '&sort=c.date_added&order=DESC', 'SSL'),
                'selected' => (isset($this->request->get['sort']) == 'c.date_added' && $this->request->get['order'] == 'DESC')
            ),
        );

        $this->data['sort_name'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=name' . $url, 'SSL');
        $this->data['sort_email'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.email' . $url, 'SSL');
        $this->data['sort_customer_group'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=customer_group' . $url, 'SSL');
        $this->data['sort_status'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.status' . $url, 'SSL');
        $this->data['sort_approved'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.approved' . $url, 'SSL');
        $this->data['sort_ip'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.ip' . $url, 'SSL');
        $this->data['sort_date_added'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.date_added' . $url, 'SSL');
        $this->data['sort_origem_cadastro'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.origem_cadastro' . $url, 'SSL');

        $url = $this->getUrlLink();

        $pagination = new Pagination();
        $pagination->total = $customer_total;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_admin_limit');
        $pagination->text = $this->language->get('text_pagination');
        $pagination->url = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

        $this->data['pagination'] = $pagination->render();

        $this->data['filter_codl'] = $filter_codl;
        $this->data['filter_codf'] = $filter_codf;
        $this->data['filter_name'] = $filter_name;
        $this->data['filter_email'] = $filter_email;
        $this->data['filter_customer_group_id'] = $filter_customer_group_id;
        $this->data['filter_status'] = $filter_status;
        $this->data['filter_email_validate'] = $filter_email_validate;
        $this->data['filter_approved'] = $filter_approved;
        $this->data['filter_origem_cadastro'] = $filter_origem_cadastro;
        $this->data['filter_integracao'] = $filter_integracao;
        $this->data['filter_marketplace'] = $filter_marketplace;
        $this->data['filter_pessoa'] = $filter_pessoa;
        $this->data['filter_cpf_cnpj'] = $filter_cpf_cnpj;
        $this->data['filter_uf'] = $filter_uf;
        $this->data['filter_ip'] = $filter_ip;
        $this->data['filter_date_added'] = $filter_date_added;
        $this->data['filter_limiter_lock'] = $filter_limiter_lock;
        $this->data['sort'] = $sort;
        $this->data['order'] = $order;

        $this->load->dmodel('sale/customer_group');

        $this->data['customer_groups'] = $this->dmodel_sale_customer_group->getCustomerGroups();

        $this->load->model('setting/store');

        $this->data['stores'] = $this->model_setting_store->getStores();

        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->changeTypeToTwig();

        $this->response->setOutput($this->render('sale/customer_list'));
    }

    public function unlock()
    {
        $this->load->model('sale/customer');

        $this->model_sale_customer->unlock();

    }

    protected function getForm()
    {
        $language = $this->language->load('sale/customer');
        $this->data = array_merge($this->data, $language);

        $this->load->helper('ftr_geral');
        $this->load->type('tipocomum');

        $this->document->addScript(
            array(
                'public/js/postcode.js',
                'view/javascript/costumer.form.js',
            )
        );

        $this->data['languageForJS'] = array(
            'sale/customer' => $language
        );

        /*
         * INICIO: Cria as variaveis para controle de exibição na .tpl por Dionis Mendanha
         */
        $arrayDataExibir = array(
            'fields_register_brazil_status_telefone',
            'fields_register_brazil_status_celular',
            'fields_register_brazil_status_telefone2',
            'fields_register_brazil_status_sexo',
            'fields_register_brazil_status_data_nascimento',
            'fields_register_brazil_status_rg',
            'fields_register_brazil_status_data_nascimento_required'
        );

        foreach ($arrayDataExibir as $dataexibir) {
            if (!ftr_geral::isIsset($this->config->get($dataexibir)) || $this->config->get($dataexibir)) {
                $this->data[$dataexibir] = true;
            } else {
                $this->data[$dataexibir] = false;
            }
        }
        /*
         * FIM: Cria as variaveis para controle de exibição na .tpl por Dionis Mendanha
         */

        $this->data['displayinfo'] = $this->displayinfo;

        $this->data['country_id'] = Type_PaisId::Tp_Brasil;

        $this->load->model('localisation/zone');
        $this->data['states'] = $this->model_localisation_zone->getZonesByCountryId(Type_PaisId::Tp_Brasil);

        $this->data['token'] = $this->session->data['token'];

        if (isset($this->request->get['customer_id'])) {
            $this->data['customer_id'] = $this->request->get['customer_id'];
        } else {
            $this->data['customer_id'] = 0;
        }

        if (isset($this->error['warning'])) {
            $this->data['error_warning'] = $this->error['warning'];
        } else {
            $this->data['error_warning'] = '';
        }

        if (isset($this->error['inscricao_estadual'])) {
            $this->data['error_inscricao_estadual'] = $this->error['inscricao_estadual'];
        } else {
            $this->data['error_inscricao_estadual'] = '';
        }

        if (isset($this->error['firstname'])) {
            $this->data['error_firstname'] = $this->error['firstname'];
        } else {
            $this->data['error_firstname'] = '';
        }

        if (isset($this->error['lastname'])) {
            $this->data['error_lastname'] = $this->error['lastname'];
        } else {
            $this->data['error_lastname'] = '';
        }

        if (isset($this->error['data_nascimento'])) {
            $this->data['error_data_nascimento'] = $this->error['data_nascimento'];
        } else {
            $this->data['error_data_nascimento'] = '';
        }

        if (isset($this->error['cpf'])) {
            $this->data['error_cpf'] = $this->error['cpf'];
        } else {
            $this->data['error_cpf'] = '';
        }

        if (isset($this->error['razao_social'])) {
            $this->data['error_razao_social'] = $this->error['razao_social'];
        } else {
            $this->data['error_razao_social'] = '';
        }

        if (isset($this->error['perfil'])) {
            $this->data['error_perfil'] = $this->error['perfil'];
        } else {
            $this->data['error_perfil'] = '';
        }

        if (isset($this->error['contribuinte'])) {
            $this->data['error_contribuinte'] = $this->error['contribuinte'];
        } else {
            $this->data['error_contribuinte'] = '';
        }

        if (isset($this->error['cnpj'])) {
            $this->data['error_cnpj'] = $this->error['cnpj'];
        } else {
            $this->data['error_cnpj'] = '';
        }

        if (isset($this->error['email'])) {
            $this->data['error_email'] = $this->error['email'];
        } else {
            $this->data['error_email'] = '';
        }

        if (isset($this->error['telephone'])) {
            $this->data['error_telephone'] = $this->error['telephone'];
        } else {
            $this->data['error_telephone'] = '';
        }

        if (isset($this->error['celular'])) {
            $this->data['error_celular'] = $this->error['celular'];
        } else {
            $this->data['error_celular'] = '';
        }

        if (isset($this->error['password'])) {
            $this->data['error_password'] = $this->error['password'];
        } else {
            $this->data['error_password'] = '';
        }

        if (isset($this->error['confirm'])) {
            $this->data['error_confirm'] = $this->error['confirm'];
        } else {
            $this->data['error_confirm'] = '';
        }

        if (isset($this->error['address_firstname'])) {
            $this->data['errors']['error_address_firstname'] = $this->error['address_firstname'];
        } else {
            $this->data['errors']['error_address_firstname'] = '';
        }

        if (isset($this->error['address_lastname'])) {
            $this->data['errors']['error_address_lastname'] = $this->error['address_lastname'];
        } else {
            $this->data['errors']['error_address_lastname'] = '';
        }

        if (isset($this->error['address_address_1'])) {
            $this->data['errors']['error_address_address_1'] = $this->error['address_address_1'];
        } else {
            $this->data['errors']['error_address_address_1'] = '';
        }

        if (isset($this->error['address_address_2'])) {
            $this->data['errors']['error_address_address_2'] = $this->error['address_address_2'];
        } else {
            $this->data['errors']['error_address_address_2'] = '';
        }

        if (isset($this->error['address_numero'])) {
            $this->data['errors']['error_address_numero'] = $this->error['address_numero'];
        } else {
            $this->data['errors']['error_address_numero'] = '';
        }

        if (isset($this->error['address_complemento'])) {
            $this->data['errors']['error_address_complemento'] = $this->error['address_complemento'];
        } else {
            $this->data['errors']['error_address_complemento'] = '';
        }

        if (isset($this->error['address_city'])) {
            $this->data['errors']['error_address_city'] = $this->error['address_city'];
        } else {
            $this->data['errors']['error_address_city'] = '';
        }

        if (isset($this->error['address_apelido'])) {
            $this->data['errors']['error_address_apelido'] = $this->error['address_apelido'];
        } else {
            $this->data['errors']['error_address_apelido'] = '';
        }

        if (isset($this->error['address_postcode'])) {
            $this->data['errors']['error_address_postcode'] = $this->error['address_postcode'];
        } else {
            $this->data['errors']['error_address_postcode'] = '';
        }

        if (isset($this->error['address_country'])) {
            $this->data['errors']['error_address_country'] = $this->error['address_country'];
        } else {
            $this->data['errors']['error_address_country'] = '';
        }

        if (isset($this->error['address_zone'])) {
            $this->data['errors']['error_address_zone'] = $this->error['address_zone'];
        } else {
            $this->data['errors']['error_address_zone'] = '';
        }

        if (!empty($this->data['errors'])) {
            $this->data['errors'] = json_encode($this->data['errors'], JSON_HEX_APOS);
        }

        $url = '';

        if (isset($this->request->get['filter_name'])) {
            $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_email'])) {
            $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_customer_group_id'])) {
            $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
        }

        if (isset($this->request->get['filter_status'])) {
            $url .= '&filter_status=' . $this->request->get['filter_status'];
        }

        if (isset($this->request->get['filter_email_validate']) && $this->config->get('email_validation_status') == 1) {
            $url .= '&filter_email_validate=' . $this->request->get['filter_email_validate'];
        }

        if (isset($this->request->get['filter_approved'])) {
            $url .= '&filter_approved=' . $this->request->get['filter_approved'];
        }

        if (isset($this->request->get['filter_origem_cadastro'])) {
            $url .= '&filter_origem_cadastro=' . $this->request->get['filter_origem_cadastro'];
        }

        if (isset($this->request->get['filter_date_added'])) {
            $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
        }

        if (isset($this->request->get['filter_pessoa'])) {
            $url .= '&filter_pessoa=' . $this->request->get['filter_pessoa'];
        }

        if (isset($this->request->get['filter_cpf_cnpj'])) {
            $url .= '&filter_cpf_cnpj=' . $this->request->get['filter_cpf_cnpj'];
        }

        if (isset($this->request->get['filter_limiter_lock'])) {
            $url .= '&filter_limiter_lock=' . $this->request->get['filter_limiter_lock'];
        }

        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }

        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }

        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }

        $this->data['breadcrumbs'] = array();

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => false
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'),
            'separator' => ' :: '
        );

        if (!isset($this->request->get['customer_id'])) {
            $this->data['action'] = $this->url->link('sale/customer/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
        } else {
            $this->data['action'] = $this->url->link('sale/customer/update', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . $url, 'SSL');
        }

        $this->data['cancel'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL');

        if (isset($this->request->get['customer_id'])) {
            $customer_info = $this->model_sale_customer->getCustomer($this->request->get['customer_id']);
        }

        if (!empty($customer_info) and ($this->config->get('config_sistema_marketplace'))) {
            if ($customer_info['mkt_integracao_tipo'] == Type_MarketPlace::Tp_Mercadolivre) {
                $this->data['display_mercadolivre'] = true;
            } else {
                $this->data['display_mercadolivre'] = false;
            }
        } else {
            $this->data['display_mercadolivre'] = false;
        }

        if (isset($this->request->post['firstname'])) {
            $this->data['firstname'] = trim($this->request->post['firstname']);
        } elseif (!empty($customer_info)) {
            $this->data['firstname'] = htmlspecialchars($customer_info['firstname'], ENT_QUOTES);
        } else {
            $this->data['firstname'] = '';
        }

        if (isset($this->request->post['lastname'])) {
            $this->data['lastname'] = $this->request->post['lastname'];
        } elseif (!empty($customer_info)) {
            $this->data['lastname'] = htmlspecialchars($customer_info['lastname'], ENT_QUOTES);
        } else {
            $this->data['lastname'] = '';
        }


        $userFuturaApp = false;
        if (isset($this->request->post['email'])) {
            $this->data['email'] = $this->request->post['email'];
        } elseif (!empty($customer_info)) {
            $this->data['email'] = $customer_info['email'];
            if ($customer_info['email'] == Type_DefaultValues::Tp_UserFuturaApp) {
                $userFuturaApp = true;
            }
        } else {
            $this->data['email'] = '';
        }

        //variavel usada para não deixar editar nenhuma informação do usuario usado como teste na playstore e appstore
        $this->data['userFuturaApp'] = $userFuturaApp;

        if (isset($this->request->post['telephone'])) {
            $this->data['telephone'] = $this->request->post['telephone'];
        } elseif (!empty($customer_info)) {
            $this->data['telephone'] = $customer_info['telephone'];
        } else {
            $this->data['telephone'] = '';
        }

        if (isset($this->request->post['pessoa'])) {
            $this->data['pessoa'] = $this->request->post['pessoa'];
        } else {
            $this->data['pessoa'] = '';
        }

        if (!empty($customer_info)) {

            if ($customer_info['cpf'] != '') {
                $this->data['tipo_pessoa'] = Type_CadastroPessoa::Tp_Fisico;
            } else {
                $this->data['tipo_pessoa'] = Type_CadastroPessoa::Tp_Juridico;
            }

        } else {
            if (ftr_geral::isIsset($this->config->get('fields_register_brazil_tipo_de_pessoa'))) {
                $this->data['tipo_pessoa'] = $this->config->get('fields_register_brazil_tipo_de_pessoa');
            }
        }

        $this->data['tipo_pessoa_ambos'] = Type_CadastroPessoa::Tp_Ambos;
        $this->data['tipo_pessoa_fisica'] = Type_CadastroPessoa::Tp_Fisico;
        $this->data['tipo_pessoa_juridica'] = Type_CadastroPessoa::Tp_Juridico;

        if (isset($this->request->post['sexo'])) {
            $this->data['sexo'] = $this->request->post['sexo'];
        } elseif (isset($customer_info)) {
            $this->data['sexo'] = $customer_info['sexo'];
        } else {
            $this->data['sexo'] = '';
        }

        if (isset($this->request->post['data_nascimento'])) {
            $this->data['data_nascimento'] = $this->request->post['data_nascimento'];
        } elseif (isset($customer_info)) {
            $this->data['data_nascimento'] = ftr_geral::formatDate($customer_info['data_nascimento'], 'br');
        } else {
            $this->data['data_nascimento'] = '';
        }

        if (isset($this->request->post['cpf'])) {
            $this->data['cpf'] = preg_replace('/([^0-9])/i', '', $this->request->post['cpf']);
        } elseif (isset($customer_info)) {
            $this->data['cpf'] = $customer_info['cpf'];
        } else {
            $this->data['cpf'] = '';
        }

        if (isset($this->request->post['rg'])) {
            $this->data['rg'] = preg_replace('/([^0-9])/i', '', $this->request->post['rg']);
        } elseif (isset($customer_info)) {
            $this->data['rg'] = $customer_info['rg'];
        } else {
            $this->data['rg'] = '';
        }

        if (isset($this->request->post['cnpj'])) {
            $this->data['cnpj'] = preg_replace('/([^0-9])/i', '', $this->request->post['cnpj']);
        } elseif (isset($customer_info)) {
            $this->data['cnpj'] = $customer_info['cnpj'];
        } else {
            $this->data['cnpj'] = '';
        }

        if (isset($this->request->post['perfil'])) {
            $this->data['perfil'] = $this->request->post['perfil'];
        } elseif (isset($customer_info)) {
            $this->data['perfil'] = $customer_info['perfil'];
        } else {
            $this->data['perfil'] = '';
        }

        if (isset($this->request->post['contribuinte'])) {
            $this->data['contribuinte'] = $this->request->post['contribuinte'];
        } elseif (isset($customer_info)) {
            $this->data['contribuinte'] = $customer_info['contribuinte'];
        } else {
            $this->data['contribuinte'] = '';
        }

        if (isset($this->request->post['celular'])) {
            $this->data['celular'] = $this->request->post['celular'];
        } elseif (!empty($customer_info)) {
            $this->data['celular'] = $customer_info['celular'];
        } else {
            $this->data['celular'] = '';
        }

        if (isset($this->request->post['razao_social'])) {
            $this->data['razao_social'] = $this->request->post['razao_social'];
        } elseif (isset($customer_info)) {
            $this->data['razao_social'] = $customer_info['razao_social'];
        } else {
            $this->data['razao_social'] = '';
        }


        if (isset($this->request->post['inscricao_estadual'])) {
            $this->data['inscricao_estadual'] = $this->request->post['inscricao_estadual'];
        } elseif (isset($customer_info)) {
            $this->data['inscricao_estadual'] = $customer_info['inscricao_estadual'];
        } else {
            $this->data['inscricao_estadual'] = '';
        }

        if (isset($this->request->post['fax'])) {
            $this->data['fax'] = $this->request->post['fax'];
        } elseif (!empty($customer_info)) {
            $this->data['fax'] = $customer_info['fax'];
        } else {
            $this->data['fax'] = '';
        }

        if (isset($this->request->post['newsletter'])) {
            $this->data['newsletter'] = $this->request->post['newsletter'];
        } elseif (!empty($customer_info)) {
            $this->data['newsletter'] = $customer_info['newsletter'];
        } else {
            $this->data['newsletter'] = '';
        }

        $this->load->dmodel('sale/customer_group');

        $this->data['customer_groups'] = $this->dmodel_sale_customer_group->getCustomerGroups();

        if (isset($this->request->post['customer_group_id'])) {
            $this->data['customer_group_id'] = $this->request->post['customer_group_id'];
        } elseif (!empty($customer_info)) {
            $this->data['customer_group_id'] = $customer_info['customer_group_id'];
        } else {
            $this->data['customer_group_id'] = $this->config->get('config_customer_group_id');
        }

        if (isset($this->request->post['status'])) {
            $this->data['status'] = $this->request->post['status'];
        } elseif (!empty($customer_info)) {
            $this->data['status'] = $customer_info['status'];
        } else {
            $this->data['status'] = 1;
        }

        if (isset($this->request->post['password'])) {
            $this->data['password'] = $this->request->post['password'];
        } else {
            $this->data['password'] = '';
        }

        if (isset($this->request->post['confirm'])) {
            $this->data['confirm'] = $this->request->post['confirm'];
        } else {
            $this->data['confirm'] = '';
        }

        $this->load->model('localisation/country');

        $this->data['countries'] = $this->model_localisation_country->getCountries();

        if (isset($this->request->post['address'])) {
            $this->data['addresses'] = json_encode($this->request->post['address'], JSON_HEX_APOS);
        } elseif (isset($this->request->get['customer_id'])) {
            $this->data['addresses'] = json_encode($this->model_sale_customer->getAddresses($this->request->get['customer_id']), JSON_HEX_APOS);
        } else {
            $this->data['addresses'] = json_encode(array(), JSON_HEX_APOS);
        }


        if (isset($this->request->post['address_id'])) {
            $this->data['address_id'] = json_encode($this->request->post['address_id'], JSON_HEX_APOS);
        } elseif (!empty($customer_info)) {
            $this->data['address_id'] = json_encode($customer_info['address_id'], JSON_HEX_APOS);
        } else {
            $this->data['address_id'] = json_encode('', JSON_HEX_APOS);
        }

      
    

        $this->data['ips'] = array();

        if (!empty($customer_info)) {
            $results = $this->model_sale_customer->getIpsByCustomerId($this->request->get['customer_id']);

            foreach ($results as $result) {
                $ban_ip_total = $this->model_sale_customer->getTotalBanIpsByIp($result['ip']);

                $this->data['ips'][] = array(
                    'ip' => $result['ip'],
                    'total' => $this->model_sale_customer->getTotalCustomersByIp($result['ip']),
                    'date_added' => date('d/m/y', strtotime($result['date_added'])),
                    'filter_ip' => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&filter_ip=' . $result['ip'], 'SSL'),
                    'ban_ip' => $ban_ip_total
                );
            }
        }

        $this->load->dmodel('tool/image');
        $this->load->type('tipocomum');
        $this->load->dmodel('catalog/product');
        $this->data['cartlist'] = array();
        if (!empty($customer_info)) {

            $results = $this->model_sale_customer->getProductsCartByCustomerID($this->request->get['customer_id']);

            $totalquantity = 0;
            $total = 0;

            foreach ($results as $result) {

                if (isset($result['lista_escolar_id']) && $result['lista_escolar_id'] > 0) {
                    $tipoLista = Type_ProductCart::Tp_ListaEscolar;
                    $id_lista = $result['lista_escolar_id'];
                    $this->data['cartlist'][$tipoLista][$id_lista]['listaescolar_descricao'] = $result['listaescolar_descricao'];
                    $this->data['cartlist'][$tipoLista][$id_lista]['escola'] = $result['listaescolar_escola'];
                    $this->data['cartlist'][$tipoLista][$id_lista]['serie'] = $result['listaescolar_serie'];
                    $this->data['cartlist'][$tipoLista][$id_lista]['isListaEscolar'] = true;
                } else {
                    $tipoLista = Type_ProductCart::Tp_Default;
                    $id_lista = 0;
                    $this->data['cartlist'][$tipoLista][$id_lista]['isListaEscolar'] = false;
                }

                //Brinde
                $produto_brinde = $this->dmodel_catalog_product->getProductBrinde($result['product_id']);
                $brinde = false;
                if ($produto_brinde && $produto_brinde['quantity'] > 0) {
                    $brinde['product_name'] = $produto_brinde['name'];
                    $brinde['href'] = $this->url->link('product/product', 'product_id=' . $produto_brinde['product_brind_id']);
                }
                //Brinde

                //KIT
                $itens_kit = $this->dmodel_catalog_product->getProductKitItens($result['product_kit_id']);
                //KIT

                if ($result['image'] && file_exists(DIR_IMAGE . $result['image'])) {
                    $image = $this->dmodel_tool_image->resize(
                        $result['image'],
                        Type_MiniatureMedium::Tp_width,
                        Type_MiniatureMedium::Tp_height
                    );
                } else {
                    $image = $this->dmodel_tool_image->resize(
                        'no_image.jpg',
                        Type_MiniatureMedium::Tp_width,
                        Type_MiniatureMedium::Tp_height
                    );
                }

                $totalquantity = $totalquantity + $result['quantity'];
                $total = $total + $result['quantity'] * $result['price'];

                $this->data['cartlist'][$tipoLista][$id_lista]['products'][] = array(
                    'product_id' => $result['product_id'],
                    'image' => $image,
                    'name' => $result['name'],
                    'href' => $this->url->link('catalog/product/update', 'token=' . $this->session->data['token'] . '&product_id=' . $result['product_id'], 'SSL'),
                    'model' => $result['model'],
                    'quantity' => $result['quantity'],
                    'price' => $this->currency->format($result['price'], $this->config->get('config_currency')),
                    'total' => $this->currency->format($result['quantity'] * $result['price'], $this->config->get('config_currency')),
                    'color_description' => $result['color_description'],
                    'size_description' => $result['size_description'],
                    'specification_description' => $result['specification_description'],
                    'brinde' => $brinde,
                    'itens_kit' => $itens_kit
                );

            }
            ksort($this->data['cartlist']);


            $this->data['totals'] = array(
                'totalquantity' => $totalquantity,
                'total' => $this->currency->format($total, $this->config->get('config_currency'))
            );

        }

        $this->changeTypeToTwig();

        $this->data['futuragrade_status'] = $this->config->get('futuragrade_status');

        $this->children = array(
            'common/header',
            'common/footer'
        );
        if (!empty($customer_info)) {
            $lock = new limiterlock($this->registry);

            $customer_lock = $lock->operationsLock($customer_info['time_lock'], $customer_info['customer_id']);
            $this->data['customer_lock'] = $customer_lock;

            if ($customer_lock) {
                $this->data['text_limiter_information'] = $lock->getInformation();
            }
        }

        $this->response->setOutput($this->render('sale/customer_form'));
    }

    protected function validateForm()
    {
        $this->load->helper('ftr_validacao');
        $this->load->helper('ftr_geral');
        $this->load->model('sale/customer');

        if (!$this->user->hasPermission('modify', 'sale/customer')) {
            $this->error['warning'] = $this->language->get('error_permission');
        }

        if ((utf8_strlen(trim($this->request->post['firstname'])) < 1) || (utf8_strlen(trim($this->request->post['firstname'])) > 32)) {
            $this->error['firstname'] = $this->language->get('error_firstname');
        }

        if ((utf8_strlen($this->request->post['lastname']) < 1) || (utf8_strlen($this->request->post['lastname']) > 32)) {
            $this->error['lastname'] = $this->language->get('error_lastname');
        }

        if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email']) || !filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL) || !preg_match('/^[a-zA-Z0-9\._-]+@/', $this->request->post['email'])) {
            $this->error['email'] = $this->language->get('error_email');
        }

        if (!isset($this->error['email'])) {
            if ($this->model_sale_customer->getRepeatMail($this->request->post)) {
                $this->error['email'] = $this->language->get('error_email_repeat');
            }
        }
        // Pessoa Física
        if ($this->request->post['pessoa'] == "F") {
            // Valida o CPF
            if (isset($this->request->post['cpf'])) {
                $cpf = preg_replace('/([^0-9])/i', '', $this->request->post['cpf']);
                if ((strlen(utf8_decode($cpf)) < 1) || (strlen(utf8_decode($cpf)) > 14)) {
                    $this->error['cpf'] = "Atenção: O CPF não deve passar de 14 caracteres";
                } elseif (!ftr_validacao::isCpf($cpf)) {
                    $this->error['cpf'] = "Atenção: O CPF informado é inválido";
                }
            }

            // Valida campo Data de Nascimento
            if (isset($this->request->post['data_nascimento'])) {
                if (!empty($this->request->post['data_nascimento'])) {
                    if (strlen(utf8_decode($this->request->post['data_nascimento'])) > 0 && ftr_geral::validaDate($this->request->post['data_nascimento'])) {
                        $date = new DateTime(ftr_geral::formatDate($this->request->post['data_nascimento'], 'en'));
                        $today = new DateTime();

                        if ($date > $today) {
                            $this->error['data_nascimento'] = 'A data deve ser menor que a de hoje';
                        }
                    } else {
                        $this->error['data_nascimento'] = "Atenção: A data informada é inválida";
                    }
                } else if ($this->config->get('fields_register_brazil_status_data_nascimento_required')) {
                    $this->error['data_nascimento'] = "Data de nascimento inválida!";
                }
            }
            // Pessoa Jurídica
        } else if ($this->request->post['pessoa'] == "J") {
            // Valida o CNPJ
            if (isset($this->request->post['cnpj'])) {
                $cnpj = preg_replace('/([^0-9])/i', '', $this->request->post['cnpj']);
                if ((strlen(utf8_decode($cnpj)) < 1) || (strlen(utf8_decode($cnpj)) > 18) && ($this->request->post['pessoa'] == "J")) {
                    $this->error['cnpj'] = "Atenção: O CNPJ não deve passar de 18 caracteres";
                } elseif (!ftr_validacao::isCnpj($cnpj)) {
                    $this->error['cnpj'] = "Atenção: O CNPJ informado é inválido";
                }
            }

            // Valida o campo Razão Social
            if ($this->request->post['razao_social'] == '') {
                $this->error['razao_social'] = "Por favor, informe a razao social da empresa!";
            }

        }

        if (($this->config->get('fields_register_brazil_status_cnpgcpf')) && (!isset($this->request->get['customer_id']))) {
            $dados = preg_replace('/([^0-9])/i', '', (isset($this->request->post['cpf']) && ($this->request->post['cpf'] <> '')) ? $this->request->post['cpf'] : $this->request->post['cnpj']);
            if (isset($dados) && ($dados <> '')) {
                $this->load->dmodel('account/customer');
                if (($this->dmodel_account_customer->getTotalCustomersByCnpjCpf($dados))) {

                    if (isset($this->request->post['cpf']) && ($this->request->post['cpf'] <> '')) {
                        $this->error['cpf'] = $this->language->get('error_cpf_exists');
                    }
                    if (isset($this->request->post['cnpj']) && ($this->request->post['cnpj'] <> '')) {
                        $this->error['cnpj'] = $this->language->get('error_cnpj_exists');
                    }

                }
            }
        }

        $obtem_celular_sem_mascara = preg_replace('/([^0-9])/i', '', $this->request->post['celular']);
        if (!ftr_geral::isIsset($this->config->get('fields_register_brazil_status_celular')) || $this->config->get('fields_register_brazil_status_celular')) {
            if ((utf8_strlen($obtem_celular_sem_mascara) != 10 && utf8_strlen($obtem_celular_sem_mascara) != 11)) {
                $this->error['celular'] = $this->language->get('error_celular');
            }
        } else {
            if ((utf8_strlen($obtem_celular_sem_mascara) > 0) && (utf8_strlen($obtem_celular_sem_mascara) != 10 && utf8_strlen($obtem_celular_sem_mascara) != 11)) {
                $this->error['celular'] = $this->language->get('error_celular');
            }
        }

        if (!isset($this->request->get['customer_id']) && (isset($this->request->post['email']) && ($this->request->post['email'] != ''))) {
            $customer_info = $this->model_sale_customer->getCustomerByEmail($this->request->post['email']);
            if ($customer_info) {
                $this->error['warning'] = $this->language->get('error_exists');
            } else {
                if ($customer_info && ($this->request->get['customer_id'] != $customer_info['customer_id'])) {
                    $this->error['warning'] = $this->language->get('error_exists');
                }
            }
        }

        if (!ftr_geral::isIsset($this->config->get('fields_register_brazil_status_telefone')) || $this->config->get('fields_register_brazil_status_telefone')) {
            $obtem_telefone_sem_mascara = preg_replace('/([^0-9])/i', '', $this->request->post['telephone']);
            if ((utf8_strlen($obtem_telefone_sem_mascara) < 3) || (utf8_strlen($obtem_telefone_sem_mascara) > 32)) {
                $this->error['telephone'] = $this->language->get('error_telephone');
            }
        }

        if ($this->request->post['password'] || (!isset($this->request->get['customer_id']))) {
            if ((utf8_strlen($this->request->post['password']) < 4) || (utf8_strlen($this->request->post['password']) > 20)) {
                $this->error['password'] = $this->language->get('error_password');
            }

            if ($this->request->post['password'] != $this->request->post['confirm']) {
                $this->error['confirm'] = $this->language->get('error_confirm');
            }
        }

        if (isset($this->request->post['address'])) {

            $addresses = $this->request->post['address'];

            $module_errors = [];

            foreach ($addresses as $key => $value) {

                if ((utf8_strlen($value['firstname']) < 1) || (utf8_strlen($value['firstname']) > 32)) {
                    $this->error['address_firstname'][$key] = $this->language->get('error_firstname');
                }

                if ((utf8_strlen($value['lastname']) < 1) || (utf8_strlen($value['lastname']) > 32)) {
                    $this->error['address_lastname'][$key] = $this->language->get('error_lastname');
                }

                if ((utf8_strlen($value['address_1']) < 1) || (utf8_strlen($value['address_1']) > 128)) {
                    $this->error['address_address_1'][$key] = $this->language->get('error_address_1');
                }

                $numero = preg_replace('/([^0-9])/i', '', $value['numero']);
                if ((utf8_strlen($numero) < 1) || (utf8_strlen($numero) > 6)) {
                    $this->error['address_numero'][$key] = 'Atenção: O número deve ter entre 1 e 6 caracteres!';
                }

                if ((utf8_strlen($value['address_2']) < 1) || (utf8_strlen($value['address_2']) > 128)) {
                    $this->error['address_address_2'][$key] = $this->language->get('error_address_2');
                }

                if ((utf8_strlen($value['complemento']) > 0) && (utf8_strlen($value['complemento']) < 3) || (utf8_strlen($value['complemento']) > 60)) {
                    $this->error['address_complemento'][$key] = $this->language->get('error_complemento');
                }

                if ((utf8_strlen($value['city']) < 2) || (utf8_strlen($value['city']) > 128)) {
                    $this->error['address_city'][$key] = $this->language->get('error_city');
                }

                if ((utf8_strlen($value['apelido']) < 1) || (utf8_strlen($value['apelido']) > 80)) {
                    $this->error['address_apelido'][$key] = $this->language->get('error_apelido');
                }

                $module_errors = $this->validate->execute([
                    'address_postcode' => [
                        'value' => $value['postcode'],
                        'validates' => [
                            [
                                'method' => 'isEmpty',
                                'message' => $this->language->get('error_postcode'),
                                'condition' => isset($value['zone_id']) && isset($value['codigo_municipio']),
                            ],
                            [
                                'method' => 'isCep',
                                'message' => $this->language->get('error_postcode'),
                            ],
                        ]
                    ]
                ]);

                if ($module_errors) {
                    $this->error['address_postcode'][$key] = $module_errors['address_postcode'][0];
                }

                if (isset($value['zone_id']) && isset($value['codigo_municipio'])) {

                    $this->load->dmodel('localisation/ibge');

                    if (!$this->dmodel_localisation_ibge->getEstadoCidade($value['zone_id'], $value['codigo_municipio'])) {
                        $this->error['address_city'][$key] = 'A cidade não pertence ao estado selecionado';
                    }

                }

                if (!isset($value['zone_id']) || $value['zone_id'] == '') {
                    $this->error['address_zone'][$key] = $this->language->get('error_zone');
                }

                if (isset($value['zone_id']) && $value['zone_id'] && isset($value['default']) && $value['default']) {
                    $default_address_zone_id = $value['zone_id'];
                }
            }

        } else {
            $this->error['warning'] = 'Atenção: O cadastro deve conter pelo menos um endereço';
        }

        if ($this->request->post['pessoa'] == "J" && isset($this->request->post['contribuinte']) && $this->request->post['contribuinte'] === Type_PjContribuoIcms::Tp_Contribuinte) {
            if (!isset($this->request->post['inscricao_estadual']) || utf8_strlen($this->request->post['inscricao_estadual']) < 1) {
                $this->error['inscricao_estadual'] = $this->language->get('error_inscricao_estadual');
            } else {
                if (isset($default_address_zone_id) && $default_address_zone_id) {
                    $this->load->model('localisation/zone');
                    $zone_info = $this->model_localisation_zone->getZone($default_address_zone_id);

                    $inscricaoEstadual = $this->request->post['inscricao_estadual'];
                    $params = array();
                    $params['uf'] = $zone_info['code'];
                    $ie_error = $this->validate->isValidIE($inscricaoEstadual, '', $params);

                    if ($ie_error) {
                        $this->error['inscricao_estadual'] = $ie_error;
                    }
                } else {
                    $this->error['inscricao_estadual'] = $this->language->get('error_inscricao_estadual_not_found_uf');
                }
            }
        }

        if ($this->error && !isset($this->error['warning'])) {
            $this->error['warning'] = $this->language->get('error_warning');
        }

        if (!$this->error) {
            return true;
        } else {
            return false;
        }
    }

    protected function validateDelete()
    {
        if (!$this->user->hasPermission('modify', 'sale/customer')) {
            $this->error['warning'] = $this->language->get('error_permission');
        }

        if (!$this->error) {
            return true;
        } else {
            return false;
        }
    }

    public function login()
    {
        $json = array();

        if (isset($this->request->get['customer_id'])) {
            $customer_id = $this->request->get['customer_id'];
        } else {
            $customer_id = 0;
        }

        $this->load->model('sale/customer');

        $customer_info = $this->model_sale_customer->getCustomer($customer_id);

        if ($customer_info) {

            $token = md5(mt_rand());

            $this->model_sale_customer->editToken($customer_id, $token);

            if (isset($this->request->get['store_id'])) {
                $store_id = $this->request->get['store_id'];
            } else {
                $store_id = 0;
            }

            $this->customer->logout();
            $this->cart->clear();

            unset($this->session->data['wishlist']);
            unset($this->session->data['buy_later']);
            unset($this->session->data['shipping_address_id']);
            unset($this->session->data['shipping_country_id']);
            unset($this->session->data['shipping_zone_id']);
            unset($this->session->data['shipping_postcode']);
            unset($this->session->data['shipping_method']);
            unset($this->session->data['shipping_methods']);
            unset($this->session->data['payment_address_id']);
            unset($this->session->data['payment_country_id']);
            unset($this->session->data['payment_zone_id']);
            unset($this->session->data['payment_method']);
            unset($this->session->data['payment_methods']);
            unset($this->session->data['comment']);
            unset($this->session->data['order_id']);
            unset($this->session->data['coupon']);
            unset($this->session->data['reward']);
            unset($this->session->data['voucher']);
            unset($this->session->data['vouchers']);

            $this->redirect($this->urlloja->link('account/register&token=' . $token));

        } else {
            $this->language->load('error/not_found');

            $this->document->setTitle($this->language->get('heading_title'));

            $this->data['heading_title'] = $this->language->get('heading_title');

            $this->data['text_not_found'] = $this->language->get('text_not_found');

            $this->data['breadcrumbs'] = array();

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_home'),
                'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
                'separator' => false
            );

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL'),
                'separator' => ' :: '
            );

            $this->template = 'error/not_found.tpl';
            $this->children = array(
                'common/header',
                'common/footer'
            );

            $this->response->setOutput($this->render());
        }
    }

    public function history()
    {
        $this->language->load('sale/customer');

        $this->load->model('sale/customer');

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->user->hasPermission('modify', 'sale/customer')) {
            $this->model_sale_customer->addHistory($this->request->get['customer_id'], $this->request->post['comment']);

            $this->data['success'] = $this->language->get('text_success');
        } else {
            $this->data['success'] = '';
        }

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && !$this->user->hasPermission('modify', 'sale/customer')) {
            $this->data['error_warning'] = $this->language->get('error_permission');
        } else {
            $this->data['error_warning'] = '';
        }

        $this->data['text_no_results'] = $this->language->get('text_no_results');

        $this->data['column_date_added'] = $this->language->get('column_date_added');
        $this->data['column_comment'] = $this->language->get('column_comment');

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        $this->data['histories'] = array();

        $results = $this->model_sale_customer->getHistories($this->request->get['customer_id'], ($page - 1) * 10, 10);

        foreach ($results as $result) {
            $this->data['histories'][] = array(
                'comment' => $result['comment'],
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
            );
        }

        $transaction_total = $this->model_sale_customer->getTotalHistories($this->request->get['customer_id']);

        $pagination = new Pagination();
        $pagination->total = $transaction_total;
        $pagination->page = $page;
        $pagination->limit = 10;
        $pagination->text = $this->language->get('text_pagination');
        $pagination->url = $this->url->link('sale/customer/history', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

        $this->data['pagination'] = $pagination->render();

        $this->response->setOutput($this->render('sale/customer_history'));
    }

    public function transaction()
    {
        $this->language->load('sale/customer');

        $this->load->model('sale/customer');

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->user->hasPermission('modify', 'sale/customer')) {
            $this->model_sale_customer->addTransaction($this->request->get['customer_id'], $this->request->post['description'], $this->request->post['amount']);

            $this->data['success'] = $this->language->get('text_success');
        } else {
            $this->data['success'] = '';
        }

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && !$this->user->hasPermission('modify', 'sale/customer')) {
            $this->data['error_warning'] = $this->language->get('error_permission');
        } else {
            $this->data['error_warning'] = '';
        }

        $this->data['text_no_results'] = $this->language->get('text_no_results');
        $this->data['text_balance'] = $this->language->get('text_balance');

        $this->data['column_date_added'] = $this->language->get('column_date_added');
        $this->data['column_description'] = $this->language->get('column_description');
        $this->data['column_amount'] = $this->language->get('column_amount');

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        $this->data['transactions'] = array();

        $results = $this->model_sale_customer->getTransactions($this->request->get['customer_id'], ($page - 1) * 10, 10);

        foreach ($results as $result) {
            $this->data['transactions'][] = array(
                'amount' => $this->currency->format($result['amount'], $this->config->get('config_currency')),
                'description' => $result['description'],
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
            );
        }

        $this->data['balance'] = $this->currency->format($this->model_sale_customer->getTransactionTotal($this->request->get['customer_id']), $this->config->get('config_currency'));

        $transaction_total = $this->model_sale_customer->getTotalTransactions($this->request->get['customer_id']);

        $pagination = new Pagination();
        $pagination->total = $transaction_total;
        $pagination->page = $page;
        $pagination->limit = 10;
        $pagination->text = $this->language->get('text_pagination');
        $pagination->url = $this->url->link('sale/customer/transaction', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

        $this->data['pagination'] = $pagination->render();

        $this->template = 'sale/customer_transaction.tpl';

        $this->response->setOutput($this->render());
    }

    public function reward()
    {
        $this->language->load('sale/customer');

        $this->load->model('sale/customer');

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->user->hasPermission('modify', 'sale/customer')) {
            $this->model_sale_customer->addReward($this->request->get['customer_id'], $this->request->post['description'], $this->request->post['points']);

            $this->data['success'] = $this->language->get('text_success');
        } else {
            $this->data['success'] = '';
        }

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && !$this->user->hasPermission('modify', 'sale/customer')) {
            $this->data['error_warning'] = $this->language->get('error_permission');
        } else {
            $this->data['error_warning'] = '';
        }

        $this->data['text_no_results'] = $this->language->get('text_no_results');
        $this->data['text_balance'] = $this->language->get('text_balance');

        $this->data['column_date_added'] = $this->language->get('column_date_added');
        $this->data['column_description'] = $this->language->get('column_description');
        $this->data['column_points'] = $this->language->get('column_points');

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        $this->data['rewards'] = array();

        $results = $this->model_sale_customer->getRewards($this->request->get['customer_id'], ($page - 1) * 10, 10);

        foreach ($results as $result) {
            $this->data['rewards'][] = array(
                'points' => $result['points'],
                'description' => $result['description'],
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
            );
        }

        $this->data['balance'] = $this->model_sale_customer->getRewardTotal($this->request->get['customer_id']);

        $reward_total = $this->model_sale_customer->getTotalRewards($this->request->get['customer_id']);

        $pagination = new Pagination();
        $pagination->total = $reward_total;
        $pagination->page = $page;
        $pagination->limit = 10;
        $pagination->text = $this->language->get('text_pagination');
        $pagination->url = $this->url->link('sale/customer/reward', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

        $this->data['pagination'] = $pagination->render();

        $this->template = 'sale/customer_reward.tpl';

        $this->response->setOutput($this->render());
    }

    public function addBanIP()
    {
        $this->language->load('sale/customer');

        $json = array();

        if (isset($this->request->post['ip'])) {
            if (!$this->user->hasPermission('modify', 'sale/customer')) {
                $json['error'] = $this->language->get('error_permission');
            } else {
                $this->load->model('sale/customer');

                $this->model_sale_customer->addBanIP($this->request->post['ip']);

                $json['success'] = $this->language->get('text_success');
            }
        }

        $this->response->setOutput(json_encode($json));
    }

    public function removeBanIP()
    {
        $this->language->load('sale/customer');

        $json = array();

        if (isset($this->request->post['ip'])) {
            if (!$this->user->hasPermission('modify', 'sale/customer')) {
                $json['error'] = $this->language->get('error_permission');
            } else {
                $this->load->model('sale/customer');

                $this->model_sale_customer->removeBanIP($this->request->post['ip']);

                $json['success'] = $this->language->get('text_success');
            }
        }

        $this->response->setOutput(json_encode($json));
    }

    public function autocomplete()
    {
        $json = array();

        if (isset($this->request->get['filter_name'])) {
            $this->load->model('sale/customer');

            $data = array(
                'filter_name' => $this->request->get['filter_name'],
                'start' => 0,
                'limit' => 20
            );

            $results = $this->model_sale_customer->getCustomers($data);

            foreach ($results as $result) {
                $json[] = array(
                    'customer_id' => $result['customer_id'],
                    'customer_group_id' => $result['customer_group_id'],
                    'name' => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
                    'customer_group' => $result['customer_group'],
                    'firstname' => $result['firstname'],
                    'lastname' => $result['lastname'],
                    'email' => $result['email'],
                    'telephone' => $result['telephone'],
                    'celular' => $result['celular'],
                    'sexo' => $result['sexo'],
                    'fax' => $result['fax'],
                    'data_nascimento' => $result['data_nascimento'],
                    'cpf' => $result['cpf'],
                    'rg' => $result['rg'],
                    'cnpj' => $result['cnpj'],
                    'perfil' => $result['perfil'],
                    'contribuinte' => $result['contribuinte'],
                    'razao_social' => $result['razao_social'],
                    'inscricao_estadual' => $result['inscricao_estadual'],
                    'address' => $this->model_sale_customer->getAddresses($result['customer_id'])
                );
            }
        }

        $sort_order = array();

        foreach ($json as $key => $value) {
            $sort_order[$key] = $value['name'];
        }

        array_multisort($sort_order, SORT_ASC, $json);

        $this->response->setOutput(json_encode($json));
    }

    public function autocompleteAddress()
    {
        $json = array();

        //neste caso o adicional param vai ser o ID do cliente
        if (isset($this->request->get['aditional_param'])) {
            $customer_id = $this->request->get['aditional_param'];
            $this->load->model('sale/customer');

            $data = array(
                'filter_name' => $this->request->get['filter_name'],
                'start' => 0,
                'limit' => 20
            );

            $json = $this->model_sale_customer->getAddresses($customer_id);
        }

        $sort_order = array();

        foreach ($json as $key => $value) {
            $sort_order[$key] = $value['address_id'];
        }

        array_multisort($sort_order, SORT_ASC, $json);

        $this->response->setOutput(json_encode($json));
    }

    public function address()
    {
        $json = array();

        if (!empty($this->request->get['address_id'])) {
            $this->load->model('sale/customer');

            $json = $this->model_sale_customer->getAddress($this->request->get['address_id']);
        }

        $this->response->setOutput(json_encode($json));
    }
}