<?php
class ControllerCheckoutRegister extends Controller {
  public function index() {

    $this->language->load('checkout/checkout');
    $this->load->helper('ftr_geral');
    $this->loadscripts();
    $this->data['scripts']            = $this->document->getScripts();
    $this->data['text_your_details']  = $this->language->get('text_your_details');
    $this->data['text_your_address']  = $this->language->get('text_your_address');
    $this->data['text_your_password'] = $this->language->get('text_your_password');
    $this->data['text_select']        = $this->language->get('text_select');
    $this->data['text_none']          = $this->language->get('text_none');
    $this->data['entry_firstname']    = $this->language->get('entry_firstname');
    $this->data['entry_lastname']     = $this->language->get('entry_lastname');
    $this->data['entry_email']        = $this->language->get('entry_email');
    $this->data['entry_telephone']    = $this->language->get('entry_telephone');
    $this->data['entry_fax']          = $this->language->get('entry_fax');
    $this->data['entry_address_1']    = $this->language->get('entry_address_1');
    $this->data['entry_address_2']    = $this->language->get('entry_address_2');
    $this->data['text_interests']    = $this->language->get('text_interests');
    $this->data['entry_postcode']     = $this->language->get('entry_postcode');
    $this->data['entry_city']         = $this->language->get('entry_city');
    $this->data['entry_country']      = $this->language->get('entry_country');
    $this->data['entry_zone']         = $this->language->get('entry_zone');
    $this->data['entry_newsletter']   = sprintf($this->language->get('entry_newsletter'), $this->config->get('config_name'));
    $this->data['entry_password']     = $this->language->get('entry_password');
    $this->data['entry_confirm']      = $this->language->get('entry_confirm');
    $this->data['entry_shipping']     = $this->language->get('entry_shipping');
    $this->data['button_continue']    = $this->language->get('button_continue');
    $this->data['entry_captcha']      = $this->language->get('entry_captcha');
		$this->data['entry_captcha_placeholder'] = $this->language->get('entry_captcha_placeholder');

    $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);

    //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'
    );

    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['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;

    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');
    }

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

    if (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->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');
    }


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

    $this->data['shipping_required'] = $this->cart->hasShipping();

    $this->data['customer_interests_remember'] = ($this->config->get('fields_register_brazil_status_interests')) ? true : false;
    $this->data['interests_categories'] = $this->getChild('account/interests_categories');

    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/register.tpl')) {
      $this->template = $this->config->get('config_template') . '/template/checkout/register.tpl';
    } else {
      $this->template = 'default/template/checkout/register.tpl';
    }

    $this->response->setOutput($this->render('checkout/register'));
  }


  public function isCpf($cpf){
    $cpf        = preg_replace('/([^0-9])/i','',$cpf);

    if (strlen($cpf) != 11) {
      return false;
    };

    $digitoUm   = 0;
    $digitoDois = 0;

    for($i = 0, $x = 10; $i <= 8; $i++, $x--){
      $digitoUm += $cpf[$i] * $x;
    }

    for($i = 0, $x = 11; $i <= 9; $i++, $x--){
      if(str_repeat($i, 11) == $cpf){
        return false;
      }
      $digitoDois += $cpf[$i] * $x;
    }

    $calculoUm   = (($digitoUm % 11) < 2) ? 0 : 11 - ($digitoUm % 11);
    $calculoDois = (($digitoDois % 11) < 2) ? 0 : 11 - ($digitoDois % 11);

    if($calculoUm != $cpf[9] || $calculoDois != $cpf[10]){
      return false;
    }

    return true;
  }

  public function isCnpj($cnpj){
    $cnpj = str_pad(str_replace(array('.','-','/'),'',$cnpj),14,'0',STR_PAD_LEFT);

    if($cnpj == '00000000000000'){
      return false;
    }

    if (strlen($cnpj) != 14){
      return false;
    }else{
      for($t = 12; $t < 14; $t++){
        for($d = 0, $p = $t - 7, $c = 0; $c < $t; $c++){
          $d += $cnpj{$c} * $p;
          $p  = ($p < 3) ? 9 : --$p;
        }
        $d = ((10 * $d) % 11) % 10;
        if($cnpj{$c} != $d){
          return false;
        }
      }
      return true;
    }
  }


  public function validate() {
    $this->language->load('checkout/checkout');
    $this->load->helper('ftr_geral');
    $this->load->type('tipocomum');
    $this->load->model('account/customer');

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

      if ((utf8_strlen($this->request->post['lastname']) < 1) || (utf8_strlen($this->request->post['lastname']) > 32)) {
        $json['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'])) {
        $json['error']['email'] = $this->language->get('error_email');
      }


      if(isset($this->request->post['data_nascimento'])){
        // Valida campo Data de Nascimento
        $dataparts = explode("/",$this->request->post['data_nascimento']);
        if (strlen(utf8_decode($this->request->post['data_nascimento'])) > 0) {
          // Se o array não tiver 3 posições a data esta incorreta
          if (sizeof($dataparts) != '3'){
            $json['error']['data_nascimento']  = "Atenção: A data informada é inválida";
          }else{
            // Checa validade da data
            if (!checkdate($dataparts[1],$dataparts[0],$dataparts[2])) {
              $json['error']['data_nascimento'] = "Atenção: A data informada é inválida";
            }
          }
        }
      }

      // Valida CPF e CNPJ
      if ($this->request->post['pessoa'] == "F"){
        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)) {
            $json['error']['cpf'] = "Atenção: O CPF não deve passar de 14 caracteres";
          }elseif(!$this->isCpf($cpf)){
            $json['error']['cpf'] = "Atenção: O CPF informado é inválido";
          }
        }
      }else if ($this->request->post['pessoa'] == "J"){
        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")) {
            $json['error']['cnpj'] =  "Atenção: O CNPJ não deve passar de 18 caracteres";
          }elseif(!$this->isCnpj($cnpj)){
            $json['error']['cnpj'] = "Atenção: O CNPJ informado é inválido";
          }
        }

        if(isset($this->request->post['razao_social'])){
          if(($this->request->post['razao_social'] == '') || ((strlen($this->request->post['razao_social']) < 1)) ){
            $json['error']['razao_social'] = "Por favor, informe a razao social da empresa!";
          }
        }

      }



      if ($this->model_account_customer->getTotalCustomersByEmail($this->request->post['email'])) {
        $json['error']['warning'] = $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']<>'') ) ? $this->request->post['cpf'] : $this->request->post['cnpj']);
        if ((isset($dados))&&($dados<>'')) {
          $this->load->dmodel('account/customer');
          if ($this->dmodel_account_customer->getTotalCustomersByCnpjCpf($dados)) {
            $json['error']['warning'] = (isset($this->request->post['cpf']) && ($this->request->post['cpf']<>'') ) ? $this->language->get('error_cpf_exists') : $this->language->get('error_cnpj_exists');
          }
        }
      }

      // INICIO - Validação de Telefone e Celular - por Henrique R. Pohl
      if(!ftr_geral::isIsset($this->config->get('fields_register_brazil_status_telefone')) || $this->config->get('fields_register_brazil_status_telefone') ){
        // INICIO - Validação de Telefone e Celular - por Henrique R. Pohl
        $obtem_telefone_sem_mascara  = preg_replace('/([^0-9])/i','',$this->request->post['telephone']);
        if ( (utf8_strlen($obtem_telefone_sem_mascara) != 10) ) {
          $json['error']['telephone'] = $this->language->get('error_telephone');
        }
      }

      $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) ) {
          $json['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) ) {
          $json['error']['celular'] = $this->language->get('error_celular');
        }
      }

      // FIM - Validação de Telefone e Celular - por Henrique R. Pohl

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

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

      if(isset($data['cpf']) &&  ($data['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($data['cnpj']) && ($data['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 ((utf8_strlen($this->request->post['address_1']) < 3) || (utf8_strlen($this->request->post['address_1']) > 70)) {
        $json['error']['address_1'] = $this->language->get('error_address_1');
      }

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

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

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

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



      if ((utf8_strlen($this->request->post['city']) < 2) || (utf8_strlen($this->request->post['city']) > 50)) {
        $json['error']['city'] = $this->language->get('error_city');
      }

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

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

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

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

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

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

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

      if ($this->request->post['confirm'] != $this->request->post['password']) {
        $json['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($this->request->post['agree'])) {
          $json['error']['warning'] = sprintf($this->language->get('error_agree_as'), $information_info['title']);
        }
      }

      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($this->request->post['g-recaptcha-response']) ? $this->request->post['g-recaptcha-response'] : '', $this->request->server['REMOTE_ADDR']);

        if (!$recaptcha["success"]) {
          $json['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'] != $this->request->post['captcha'])) {
          $json['error']['captcha'] = 'O código de verificação não coincide com a imagem!';
        }
      }
    }

    if (!$json) {
      $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']);

    }

    $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 loadscripts(){

    // Adiciona o Plugin que mostra o qualidade da senha - por Henrique R. Pohl
    $this->document->addScript('catalog/view/theme/vista/public/js/medidor-de-senha.js');
  }

}
