<?php

class ControllerAccountRegisterContent extends Controller
{
  private $error = array();
  private $debug = false;

  public function index()
  {

    $this->app();

    $this->setDebug();

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

    if ($this->customer->isLogged() && (!isset($this->request->get['checkout']) || !$this->request->get['checkout'])) {
      $this->redirect($this->url->link('account/account', '', 'SSL'));
    }

    $this->language->load('account/register');

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

    $this->load->model('account/customer');
    $this->load->helper('ftr_geral');


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

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

      // Default Shipping Address
      if ($this->config->get('config_tax_customer') == 'shipping') {
        $this->session->data['shipping_country_id'] = $this->request->post['country_id'];
        $this->session->data['shipping_zone_id'] = $this->request->post['zone_id'];
        $this->session->data['shipping_postcode'] = $this->request->post['postcode'];
      }

      // Default Payment Address
      if ($this->config->get('config_tax_customer') == 'payment') {
        $this->session->data['payment_country_id'] = $this->request->post['country_id'];
        $this->session->data['payment_zone_id'] = $this->request->post['zone_id'];
      }
      if (!isset($this->request->get['checkout']) || !$this->request->get['checkout']) {

        if (isset($this->session->data['tbp'])) {
          $this->request->post['tbp'] = $this->session->data['tbp'];
          unset($this->session->data['tbp']);
        }

        if (isset($this->session->data['customerml'])) {
          $this->request->post['customerml'] = $this->session->data['customerml'];
          $this->model_account_customer->editCustomer($this->request->post);
        } else {
          $postData = $this->request->post;
          $postData['origem_cadastro'] = $this->ftrgeralregistry->isApp() ? Type_OrigemSistema::Tp_App : Type_OrigemSistema::Tp_Ecommerce;
          if (isset($this->session->data['indication_customer_id'])) {
              $postData['indicator_id'] = $this->session->data['indication_customer_id'];
          }
          $this->model_account_customer->addCustomer($postData);
        }

        unset($this->session->data['guest']);
        unset($this->session->data['customerml']);

        $this->customer->login($this->request->post['email'], $this->request->post['password']);

        $this->redirect($this->url->link('account/success'));
      }
    }

    $this->data['site_key'] = $this->config->get('google_recaptcha_site_key');
    $this->data['google_captcha'] = ($this->data['site_key'] && $this->config->get('google_recaptcha_secret_key') && $this->config->get('wg24_google_recaptcha_status')) ? 1 : 0;

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

    $perfis = Type_PerfilCustomerJuridico::getEnumlist();
    $this->data['perfis'] = array();
    foreach ($perfis as $key => $perfil) {
      $this->data['perfis'][] = array(
        'value' => $key,
        'name' => $perfil,
        'selected' => (isset($this->request->post['perfil']) && ($this->request->post['perfil'] == $key)) ? true : false
      );
    }

    $contribuintes = Type_PjContribuoIcms::getEnumlist();
    $this->data['contribuintes'] = array();
    foreach ($contribuintes as $key => $contribuinte) {
      $this->data['contribuintes'][] = array(
        'value' => $key,
        'name' => $contribuinte,
        'selected' => (isset($this->request->post['contribuinte']) && ($this->request->post['contribuinte'] == $key)) ? true : false
      );
    }

    $language = $this->language->load('account/register');
    $this->data = array_merge($this->data, $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) {

      //validação feita para que não torne esses campos obrigatorios nos aplicativos
      if (in_array($dataexibir, ['fields_register_brazil_status_telefone', 'fields_register_brazil_status_celular', 'fields_register_brazil_status_data_nascimento_required']) && $this->ftrgeralregistry->isApp()) {
        $this->data[$dataexibir] = false;
      } else {
        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->load->type('tipocomum');
    $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);

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

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

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

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

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

    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['cnpj'])) {
      $this->data['error_cnpj'] = $this->error['cnpj'];
    } else {
      $this->data['error_cnpj'] = '';
    }

    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['inscricao_estadual'])) {
      $this->data['error_inscricao_estadual'] = $this->error['inscricao_estadual'];
    } else {
      $this->data['error_inscricao_estadual'] = '';
    }


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

    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['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['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['company_id'])) {
      $this->data['error_company_id'] = $this->error['company_id'];
    } else {
      $this->data['error_company_id'] = '';
    }

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

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

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

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

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

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

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

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

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

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

    if (isset($this->data['postcode_readonly'])) {
      $this->data['postcode_readonly'] = $this->data['postcode_readonly'];
    } else {
      $this->data['postcode_readonly'] = true;
    }

    $actionUrl = '';

    if (isset($this->request->get['cml'])) {
      $actionUrl = '&cml=' . $this->request->get['cml'];
    } elseif (isset($this->request->get['debug'])) {
      $actionUrl = '&debug=true';
    }

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


    $this->data['action'] = $this->url->link('account/register', '&old=true' . $actionUrl, 'SSL');

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

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

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

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

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

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

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

    // pega o tipo de pessoa para gerar a lista
    if (isset($this->request->post['fields_register_brazil_tipo_de_pessoa'])) {
      $this->data['fields_register_brazil_tipo_de_pessoa'] = $this->request->post['fields_register_brazil_tipo_de_pessoa'];
    } else {
      $this->data['fields_register_brazil_tipo_de_pessoa'] = $this->config->get('fields_register_brazil_tipo_de_pessoa');
    }

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

    foreach (Type_CadastroPessoa::getEnumList(true) as $key => $value) {
      $this->data['fields_register_brazil_tipo_de_pessoa_array'][] = $key;
    }

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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


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

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

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

    if (isset($this->request->post['country_id'])) {
      $this->data['country_id'] = $this->request->post['country_id'];
    } elseif (isset($this->session->data['shipping_country_id'])) {
      $this->data['country_id'] = $this->session->data['shipping_country_id'];
    } else {
      $this->data['country_id'] = Type_PaisId::Tp_Brasil;
    }

    if (isset($this->request->post['zone_id'])) {
      $this->data['zone_id'] = $this->request->post['zone_id'];
    } elseif (isset($this->session->data['shipping_zone_id']) && ($this->session->data['shipping_zone_id'] != 'undefined') && ($this->session->data['shipping_zone_id'] != '')) {
      $this->data['zone_id'] = $this->session->data['shipping_zone_id'];
    } else {
      $this->data['zone_id'] = $this->config->get('config_zone_id');
    }
    $this->load->model('localisation/zone');
    $this->data['zone_name'] = $this->model_localisation_zone->getZone($this->data['zone_id'])['name'];

    $this->load->model('localisation/country');
    $this->data['countries'] = $this->model_localisation_country->getCountries();

    $this->load->dmodel('localisation/ibge');
    $this->data['cities'] = $this->dmodel_localisation_ibge->getMunicipios($this->data['zone_id']);

    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'] = '';
    }

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

    if ($this->config->get('config_account_id')) {
      $this->load->model('catalog/information');

      $information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));

      if ($information_info) {
        $this->data['text_agree'] = sprintf($this->language->get('text_agree'), $this->url->link('information/information/info', 'information_id=' . $this->config->get('config_account_id'), 'SSL'), $information_info['title'], $information_info['title']);
        $this->data['agree_link'] = $this->url->link('information/information/info', 'information_id=' . $this->config->get('config_account_id'), 'SSL');
      } else {
        $this->data['text_agree'] = '';
      }
    } else {
      $this->data['text_agree'] = '';
    }

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

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


    $this->data['custom_scripts'] = array(
      $this->ftrgeralregistry->getScriptManifest('catalog/view/theme/vista/public/js/medidor-de-senha.js', false),
      'catalog/view/theme/vista/js/jquery/jquery.validate.js?version=' . filesize('catalog/view/theme/vista/js/jquery/jquery.validate.js'),
      'catalog/view/theme/vista/js/jquery/additional-methods.js?version=' . filesize('catalog/view/theme/vista/js/jquery/additional-methods.js'),
      'catalog/view/theme/vista/js/jquery/jquery.validate.futura-methods.js?version=' . filesize('catalog/view/theme/vista/js/jquery/jquery.validate.futura-methods.js'),
      'catalog/view/theme/vista/js/jquery/localization/messages_pt_BR.js?version=' . filesize('catalog/view/theme/vista/js/jquery/localization/messages_pt_BR.js'),
      $this->ftrgeralregistry->getScriptManifest('public/js/postcode.js', false),
    );

    $this->data['customer_interests_remember'] = ($this->config->get('fields_register_brazil_status_interests')) ? true : false;
    $this->data['interests_categories'] = $this->getChild('account/interests_categories', isset($this->request->post['categories']) ? $this->request->post['categories'] : '');
    $this->data['login'] = $this->getChild('account/login', isset($this->request->post) ? $this->request->post : '');
    $this->data['forgotten'] = $this->getChild('account/forgotten');

    if (isset($this->request->get['cmltoken'])) {
      $id = ftr_geral::cripty($this->request->get['id'], $this->config->get('config_encryption'));
      if ($id == $this->request->get['cmltoken']) {
        $this->getDadosClienteMl($this->request->get['id']);
      }
    }

    $this->children = array();

    $this->data['session_id'] = $this->session->getId();

    $this->response->setOutput($this->render('account/register_content'));
  }

  protected function setDebug()
  {
    $dataCaptcha = array(
      'debug' => isset($this->request->get['debug']) ? true : false,
      'ambiente' => defined('AMBIENTE_TESTE') ? true : false
    );

    if (count(array_filter($dataCaptcha)) == 2) {
      $this->debug = true;
    }

  }

  protected function getDadosClienteMl($clienteMl)
  {

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

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

    $customer = $this->model_account_customer->getCustomer($clienteMl);

    if (($customer) && (!$customer['cadastro_atualizado_ml'])) {

      $dataCustomer = array(
        'firstname',
        'lastname',
        'telephone',
        'celular',
        'pessoa' => array(
          'cpf',
          'cnpj'
        )
      );

      $this->setData($dataCustomer, $this->request->post, $customer);

      $this->load->model('account/address');
      $address = $this->model_account_address->getAddressCustomer($clienteMl);

      if ($address) {
        $dataAdress = array(
          'address_1',
          'numero',
          'address_2',
          'city',
          'postcode',
          'zone_id',
          'country_id',
          'tipo_logradouro',
          'logradouro',
          'codigo_municipio'
        );
        $this->setData($dataAdress, $this->request->post, $address);
      }

      $this->session->data['customerml'] = $clienteMl;
    }else{
      $this->data['customerml'] = 'Seu cadastro está atualizado, entre com sua conta.';
    }

  }

  protected function setData($data, $post, $info)
  {

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

      if (is_array($value)) {
        foreach ($value as $key => $val) {
          if (isset($post[$val])) {
            $this->data[$val] = $post[$val];
          } elseif ($info[$val]) {
            $this->data[$val] = $info[$val];
          }
        }
        if (isset($value['pessoa'])) {
          $this->data['fields_register_brazil_tipo_de_pessoa'] = (isset($this->data['cnpj']) && ($this->data['cnpj'] != "")) ? Type_CadastroPessoa::Tp_Juridico : Type_CadastroPessoa::Tp_Fisico;
          $this->data['pessoa'] = (isset($this->data['cnpj']) && ($this->data['cnpj'] != "")) ? Type_CadastroPessoa::Tp_Juridico : Type_CadastroPessoa::Tp_Fisico;
        }

      } else {
        if (isset($post[$value])) {
          $this->data[$value] = $post[$value];
        } elseif ($info[$value]) {
          $this->data[$value] = $info[$value];
        } else {
          $this->data[$value] = '';
        }
      }
    }

  }

  public function getValidateErros($data)
  {
    $this->setDebug();

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

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

    $this->language->load('checkout/checkout');

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

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

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

    if ($this->config->get('fields_register_brazil_status_data_nascimento_required') && !$this->ftrgeralregistry->isApp() && $data['pessoa'] == "F") {
      if (isset($data['data_nascimento']) && (empty(trim($data['data_nascimento'])))) {
        $this->error['data_nascimento'] = "Data de nascimento inválida!";
      }
    }

    if (isset($data['data_nascimento'])) {
      $dataparts = explode("/", $data['data_nascimento']);
      if (strlen(utf8_decode($data['data_nascimento'])) > 0) {
        if (sizeof($dataparts) != '3') {
          $this->error['data_nascimento'] = "Atenção: A data informada é inválida";
        } else {
          if (!checkdate($dataparts[1], $dataparts[0], $dataparts[2])) {
            $this->error['data_nascimento'] = "Atenção: A data informada é inválida";
          }
        }

            $day = $dataparts[0];
            $month = $dataparts[1];
            $year = $dataparts[2];

            $date = new DateTime($year . '-' . $month . '-' . $day);
            $today = new DateTime();

            if ($date > $today) {
                $this->error['data_nascimento'] = "A data deve ser menor que a de hoje";
            }
        }
    }



    if ($data['pessoa'] == "F") {
      if (isset($data['cpf'])) {
        $cpf = preg_replace('/([^0-9])/i', '', $data['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";
        }
      }
    } else if ($data['pessoa'] == "J") {
      if (isset($data['cnpj'])) {
        $cnpj = preg_replace('/([^0-9])/i', '', $data['cnpj']);
        if ((strlen(utf8_decode($cnpj)) < 1) || (strlen(utf8_decode($cnpj)) > 18)) {
          $this->error['cnpj'] = "Atenção: O CNPJ não deve passar de 18 caracteres";
        } else if (!ftr_validacao::isCnpj($cnpj)) {
          $this->error['cnpj'] = "Atenção: O CNPJ informado é inválido";
        }

      }

      if ($data['razao_social'] == '') {
        $this->error['razao_social'] = "Por favor, informe a razao social da empresa!";
      }

      if (isset($data['inscricao_estadual']) && isset($data['zone_id']) && ($data['contribuinte'] == 'S')) {
        if (($data['inscricao_estadual'] == '') || ((strlen($data['inscricao_estadual']) < 1))) {
          $this->error['inscricao_estadual'] = "Atenção: Informe a Inscrição Estadual";
        } else {
//          $this->load->model('account/address');
//          $siglaEstado = $this->model_account_address->getSiglaByZone($data['zone_id']);
//          if (!ftr_validacao::isIE($data['inscricao_estadual'],$siglaEstado)){
//            $this->error['inscricao_estadual'] = "Atenção: Inscrição estadual inválida";
//          }
        }
      }
    }

    if (($this->model_account_customer->getTotalCustomersByEmail($data['email']))) {
      $this->error['email'] = $this->language->get('error_exists');
    }

    if ($this->config->get('fields_register_brazil_status_cnpgcpf')) {
      $dados = preg_replace('/([^0-9])/i', '', (isset($this->request->post['cpf']) && ($this->request->post['cpf'] <> '')) ? $data['cpf'] : $data['cnpj']);
      if ((isset($dados)) && ($dados <> '') && (!isset($this->session->data['customerml']))) {
        $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');
          }

        }
      }
    }

    if (!ftr_geral::isIsset($this->config->get('fields_register_brazil_status_telefone')) || $this->config->get('fields_register_brazil_status_telefone') && !$this->ftrgeralregistry->isApp()) {
      $obtem_telefone_sem_mascara = preg_replace('/([^0-9])/i', '', $data['telephone']);
      if ((utf8_strlen($obtem_telefone_sem_mascara) != 10)) {
        $this->error['telephone'] = $this->language->get('error_telephone');
      }
    }

    $obtem_celular_sem_mascara = preg_replace('/([^0-9])/i', '', $data['celular']);
    if (!ftr_geral::isIsset($this->config->get('fields_register_brazil_status_celular')) || $this->config->get('fields_register_brazil_status_celular') && !$this->ftrgeralregistry->isApp()) {
      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($data['feedback_whatsapp_status']) && $data['feedback_whatsapp_status']){
        $obtem_whatsapp_sem_mascara = preg_replace('/([^0-9])/i', '', $data['feedback_whatsapp_number']);
        if ((utf8_strlen($obtem_whatsapp_sem_mascara) != 10 && utf8_strlen($obtem_whatsapp_sem_mascara) != 11)) {
            $this->error['whatsapp'] = $this->language->get('error_whatsapp');
        }
    }


    if ((utf8_strlen($data['address_1']) < 1) || (utf8_strlen($data['address_1']) > 70)) {
      $this->error['address_1'] = $this->language->get('error_address_1');
    }

    if ((utf8_strlen($data['address_2']) > 0) && (utf8_strlen($data['address_2']) < 1)) {
      $this->error['address_2'] = $this->language->get('error_address_2');
    }

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

    if ((utf8_strlen($data['apelido']) < 3) || (utf8_strlen($data['apelido']) > 80)) {
      $this->error['apelido'] = $this->language->get('error_apelido');
    }

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

    if (((utf8_strlen($data['city']) < 2) || (utf8_strlen($data['city']) > 50)) || ((trim($data['codigo_municipio']) == '') || (utf8_strlen($data['codigo_municipio']) == 0))) {
      $this->error['city'] = $this->language->get('error_city');
    }

    $country_info = $this->model_localisation_country->getCountry($data['country_id']);

    if ($country_info) {
      if ($country_info['postcode_required'] && (utf8_strlen($data['postcode']) < 2) || (utf8_strlen($data['postcode']) > 10)) {
        $this->error['postcode'] = $this->language->get('error_postcode');
      }
    }

    if ($data['country_id'] == '') {
      $json['error']['country'] = $this->language->get('error_country');
    }

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

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

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

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

    }
    $this->load->model('account/address');
    if ($data['country_id'] <> $this->model_account_address->getCountryByZone($data['zone_id'])) {
      $data['zone_id'] = '';
      $this->error['zone'] = $this->language->get('error_zone');
    }

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

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

    if ($this->config->get('config_account_id')) {
      $this->load->model('catalog/information');

      $information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));

      if ($information_info && !isset($data['agree'])) {
        $this->error['agree'] = $this->language->get('error_agree');
      }
    }

    if (isset($this->request->post['tipo_logradouro']) && $this->request->post['tipo_logradouro'] == '') {
      $this->data['postcode_readonly'] = false;
    }

    //validação do recaptcha sempre tem que ser a ultima a ser feita
    if (!$this->debug) {

      if (isset($data['g-recaptcha-response']) && (count($this->error) == 0)) {
        if (!$this->config->get('google_recaptcha_site_key') || !$this->config->get('google_recaptcha_secret_key') || !$this->config->get('wg24_google_recaptcha_status')) {
          if (empty($this->session->data['captcha']) || ($this->session->data['captcha'] != $data['captcha'])) {
            $this->error['captcha'] = $this->language->get('error_captcha');
          }
        }

        if ($this->config->get('google_recaptcha_site_key') && $this->config->get('google_recaptcha_secret_key') && $this->config->get('wg24_google_recaptcha_status')) {
          $recaptcha = $this->ftrgeralregistry->validateGoogleCaptha($this->config->get('google_recaptcha_secret_key'), isset($data['g-recaptcha-response']) ? $data['g-recaptcha-response'] : '', $this->request->server['REMOTE_ADDR']);
          if (!$recaptcha["success"]) {
            $this->error['google_recaptcha'] = 'Erro de validação no reCaptcha! Efetue a validação para continuar';
          }
        }
      } else if ((empty($this->session->data['captcha']) || ($this->session->data['captcha'] != $data['captcha'])) && (count($this->error) == 0)) {
        $this->error['captcha'] = 'O código de verificação não coincide com a imagem!' . $this->debug;
      }

    }

  }


  public function validate()
  {

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

    $checkout = false;

    if (isset($this->request->get['checkout']) && $this->request->get['checkout']) {
      $checkout = true;
    }

    if (!$checkout) {

      $this->getValidateErros($this->request->post);
      if (count($this->error) > 0) {
        $this->error['warning'] = $this->language->get('error_warning_register');
      }

      if (!$this->error) {
        return true;
      } else {
        $this->error['postcode_visible'] = true;
        return false;
      }

    } else {

      $json = array();

      // Validate if customer is already logged out.
      if ($this->customer->isLogged()) {
        $json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
      }

      // Validate cart has products and has stock.
      if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
        $json['redirect'] = $this->url->link('checkout/cart');
      }

      // Validate minimum quantity requirments.
      $products = $this->cart->getProducts();

      foreach ($products as $product) {
        $product_total = 0;

        foreach ($products as $product_2) {
          if ($product_2['product_id'] == $product['product_id']) {
            $product_total += $product_2['quantity'];
          }
        }

        if ($product['minimum'] > $product_total) {
          $json['redirect'] = $this->url->link('checkout/cart');
          break;
        }
      }

      if (!$json) {
        $this->getValidateErros($this->request->post);
        if (count($this->error) > 0) {
          foreach ($this->error as $key => $value) {
            $json['error'][$key] = $value;
          }
        }
      }

      if (!$json) {

        // Customer Group
        $this->load->model('account/customer_group');

        $customer_group_id = $this->config->get('config_customer_group_id');

        if (isset($this->request->post['cpf']) && ($this->request->post['cpf'] != '') && ftr_geral::isIsset($this->config->get('config_customer_group_id_cpf')) && $this->config->get('config_customer_group_id_cpf') != Type_DefaultValues::Tp_Nenhum) {
          $customer_group_id = $this->config->get('config_customer_group_id_cpf');
        }

        if (isset($this->request->post['cnpj']) && ($this->request->post['cnpj'] != '') && ftr_geral::isIsset($this->config->get('config_customer_group_id_cnpj')) && $this->config->get('config_customer_group_id_cnpj') != Type_DefaultValues::Tp_Nenhum) {
          $customer_group_id = $this->config->get('config_customer_group_id_cnpj');
        }

        $customer_group = $this->model_account_customer_group->getCustomerGroup($customer_group_id);

        if (isset($this->session->data['customerml'])) {
          $this->request->post['customerml'] = $this->session->data['customerml'];
          $this->model_account_customer->editCustomer($this->request->post);
          unset($this->session->data['customerml']);
        } else {
          $this->model_account_customer->addCustomer($this->request->post);
        }

        $this->session->data['account'] = 'register';

        if ($customer_group && !$customer_group['approval']) {
          $this->customer->login($this->request->post['email'], $this->request->post['password']);

          $this->session->data['payment_address_id'] = $this->customer->getAddressId();
          $this->session->data['payment_country_id'] = $this->request->post['country_id'];
          $this->session->data['payment_zone_id'] = $this->request->post['zone_id'];

          if (!empty($this->request->post['shipping_address'])) {
            $this->session->data['shipping_address_id'] = $this->customer->getAddressId();
            $this->session->data['shipping_country_id'] = $this->request->post['country_id'];
            $this->session->data['shipping_zone_id'] = $this->request->post['zone_id'];
            $this->session->data['shipping_postcode'] = $this->request->post['postcode'];
          }
        } else {
          $json['redirect'] = $this->url->link('account/success');
        }

        unset($this->session->data['guest']);
        unset($this->session->data['shipping_method']);
        unset($this->session->data['shipping_methods']);
        unset($this->session->data['payment_method']);
        unset($this->session->data['payment_methods']);
      }

      if (isset($json['error'])) {
        $json['error']['warning'] = $this->language->get('error_warning_register');
      }

      if ($this->customer->isLogged()) {
        $json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
      }

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

  public function captcha()
  {
    $this->load->library('captcha');

    $captcha = new Captcha();

    $this->session->data['captcha'] = $captcha->getCode();

    $captcha->showImage();
  }

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

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

    $country_info = $this->model_localisation_country->getCountry($this->request->get['country_id']);

    if ($country_info) {
      $this->load->model('localisation/zone');

      $json = array(
        'country_id' => $country_info['country_id'],
        'name' => $country_info['name'],
        'iso_code_2' => $country_info['iso_code_2'],
        'iso_code_3' => $country_info['iso_code_3'],
        'address_format' => $country_info['address_format'],
        'postcode_required' => $country_info['postcode_required'],
        'zone' => $this->model_localisation_zone->getZonesByCountryId($this->request->get['country_id']),
        'status' => $country_info['status']
      );
    }

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


  public function email()
  {

    $json = array();

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

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

    $this->load->model('account/customer');
    $this->language->load('checkout/checkout');

    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->request->post['email'] == '')) {
      $json['error'] = $this->language->get('error_email');
    } elseif (($this->model_account_customer->getTotalCustomersByEmail($this->request->post['email']))) {
      $json['error'] = $this->language->get('error_exists');
    }

    if (!$json) {
      $json['success'] = true;
    }

    $this->response->setOutputJson($json);

  }


  public function app()
  {
    if ($this->ftrgeralregistry->isApp()) {
      $this->document->addScriptApp(array(
        'catalog/view/theme/appmobile/public/js/medidor-de-senha.js',
        'catalog/view/theme/appmobile/public/js/mainheaderform.js',
        'catalog/view/theme/appmobile/public/js/page.register.js',
        'public/js/postcode.js',
      ));
      $this->data['scriptsApp'] = json_encode($this->document->getScriptsApp());

      $this->document->addStyleApp(array(
        'catalog/view/theme/appmobile/public/css/mdDateTimePicker.css'
      ));
      $this->data['stylesApp'] = json_encode($this->document->getStylesApp());
      $this->data['dont_know_cep'] = $this->getChild('postcode/postcode');
    }
  }

}
