<?php

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

  public function index()
  {

    if (!$this->customer->isLogged()) {
      $this->session->data['redirect'] = $this->url->link('account/address', '', 'SSL');

      $this->redirect($this->url->link('account/register', '', 'SSL'));
    }

    $language = $this->language->load('account/address');
    $this->data = array_merge($this->data, $language);

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

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

    $this->getList();
  }

  public function insert()
  {

    $language = $this->language->load('account/address');
    $this->data = array_merge($this->data, $language);

    $this->loadscripts();

    if (!$this->customer->isLogged()) {
      $this->session->data['redirect'] = $this->url->link('account/address', '', 'SSL');

      $this->redirect($this->url->link('account/register', '', 'SSL'));
    }

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

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

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

    $this->data['postcode_visible'] = false;

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

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

      $this->redirect($this->url->link('account/address', '', 'SSL'));
    }
    $this->getForm();
  }

  public function update()
  {

    $language = $this->language->load('account/address');
    $this->data = array_merge($this->data, $language);

    $this->loadscripts();

    if (!$this->customer->isLogged()) {
      $this->session->data['redirect'] = $this->url->link('account/address', '', 'SSL');

      $this->redirect($this->url->link('account/register', '', 'SSL'));
    }

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

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

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

    $this->data['postcode_visible'] = true;

    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
      $this->model_account_address->editAddress($this->request->get['address_id'], $this->request->post);

      // Default Shipping Address
      if (isset($this->session->data['shipping_address_id']) && ($this->request->get['address_id'] == $this->session->data['shipping_address_id'])) {
        $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'];

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

      // Default Payment Address
      if (isset($this->session->data['payment_address_id']) && ($this->request->get['address_id'] == $this->session->data['payment_address_id'])) {
        $this->session->data['payment_country_id'] = $this->request->post['country_id'];
        $this->session->data['payment_zone_id'] = $this->request->post['zone_id'];

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

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

      $this->redirect($this->url->link('account/address', '', 'SSL'));
    }
    $this->getForm();
  }

  public function delete()
  {

    if (!$this->customer->isLogged()) {
      $this->session->data['redirect'] = $this->url->link('account/address', '', 'SSL');

      $this->redirect($this->url->link('account/register', '', 'SSL'));
    }

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

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

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

    if (isset($this->request->get['address_id']) && $this->validateDelete()) {
      $this->model_account_address->deleteAddress($this->request->get['address_id']);

      // Default Shipping Address
      if (isset($this->session->data['shipping_address_id']) && ($this->request->get['address_id'] == $this->session->data['shipping_address_id'])) {
        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']);
      }

      // Default Payment Address
      if (isset($this->session->data['payment_address_id']) && ($this->request->get['address_id'] == $this->session->data['payment_address_id'])) {
        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']);
      }

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

      $this->redirect($this->url->link('account/address', '', 'SSL'));
    }

    $this->getList();
  }

  protected function getList()
  {

    $language = $this->language->load('account/address');
    $this->data = array_merge($this->data, $language);

    $this->document->addScriptApp(array(
      'catalog/view/theme/appmobile/js/page.address-list.js'
    ));

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

    $this->data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_account'),
      'href' => $this->url->link('account/account', '', 'SSL'),
      'separator' => $this->language->get('text_separator')
    );

    $this->data['breadcrumbs'][] = array(
      'text' => $this->language->get('heading_title'),
      'href' => $this->url->link('account/address', '', 'SSL'),
      'separator' => $this->language->get('text_separator')
    );

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

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

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

    $results = $this->model_account_address->getAddresses();

    foreach ($results as $key => $result) {
      $this->data['addresses'][$key] = array(
        'default' => $this->customer->getAddressId() == $result['address_id'],
        'update' => $this->url->link('account/address/update', 'address_id=' . $result['address_id'], 'SSL'),
        'delete' => $this->url->link('account/address/delete', 'address_id=' . $result['address_id'], 'SSL')
      );

      $this->data['addresses'][$key] = array_merge($this->data['addresses'][$key], $result);
    }

    $this->data['insert'] = $this->url->link('account/address/insert', '', 'SSL');
    $this->data['back'] = $this->url->link('account/account', '', 'SSL');

    $this->document->addScript(array(
      'catalog/view/theme/vista/public/js/account/address_list.js',
    ));

    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/address_list.twig')) {
      $this->template = $this->config->get('config_template') . '/template/account/address_list.twig';
    } else {
      $this->template = 'default/template/account/address_list.twig';
    }

    $this->children = array(
      'common/breadcrumbs',
      'common/column_left',
      'common/column_right',
      'common/content_top',
      'common/content_bottom',
      'common/footer',
      'common/header'
    );

    if (!$this->ftrgeralregistry->isApp()) {
      array_push($this->children, 'module/account');
    }

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

  protected function getForm()
  {

    $this->app();

    $this->document->addScript(array(
      'catalog/view/theme/vista/js/jquery/jquery.validate.js',
      'catalog/view/theme/vista/js/jquery/additional-methods.js',
      'catalog/view/theme/vista/js/jquery/jquery.validate.futura-methods.js',
      'public/js/postcode.js'
    ));



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

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

    $this->data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_account'),
      'href' => $this->url->link('account/account', '', 'SSL'),
      'separator' => $this->language->get('text_separator')
    );

    if (!isset($this->request->get['address_id'])) {
      $this->data['breadcrumbs'][] = array(
        'text' => $this->language->get('text_edit_address'),
        'href' => $this->url->link('account/address/insert', '', 'SSL'),
        'separator' => $this->language->get('text_separator')
      );
    } else {
      $this->data['breadcrumbs'][] = array(
        'text' => $this->language->get('text_edit_address'),
        'href' => $this->url->link('account/address/update', 'address_id=' . $this->request->get['address_id'], 'SSL'),
        'separator' => $this->language->get('text_separator')
      );
    }

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

    $this->data['heading_title'] = $this->language->get('heading_title');
    $this->data['text_edit_address'] = $this->language->get('text_edit_address');
    $this->data['text_yes'] = $this->language->get('text_yes');
    $this->data['text_no'] = $this->language->get('text_no');
    $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_company'] = $this->language->get('entry_company');
    $this->data['entry_address_1'] = $this->language->get('entry_address_1');
    $this->data['entry_address_2'] = $this->language->get('entry_address_2');
    $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_default'] = $this->language->get('entry_default');
    $this->data['button_continue'] = $this->language->get('button_continue');
    $this->data['button_back'] = $this->language->get('button_back');

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

    $this->data['postcode_readonly'] = true;

    if (!isset($this->request->get['address_id'])) {
      $this->data['action'] = $this->url->link('account/address/insert', '', 'SSL');
    } else {
      $this->data['action'] = $this->url->link('account/address/update', 'address_id=' . $this->request->get['address_id'], 'SSL');
    }

    if (isset($this->request->get['address_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
      $address_info = $this->model_account_address->getAddress($this->request->get['address_id']);
    }

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

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

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

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

    $customer_group_info = $this->model_account_customer_group->getCustomerGroup($this->customer->getCustomerGroupId());

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

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

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

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

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

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

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

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


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

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

      //para quando for cliente antigo não perder a descrição da cidade
      $this->data['text_select'] = $address_info['city'];
    } else {
      $this->data['city'] = '';
    }

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


    if (isset($this->request->post['default'])) {
      $this->data['default'] = $this->request->post['default'];
    } elseif (isset($this->request->get['address_id'])) {
      $this->data['default'] = $this->customer->getAddressId() == $this->request->get['address_id'];
    } else {
      $this->data['default'] = false;
    }

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

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

    $this->data['back'] = $this->url->link('account/address', '', 'SSL');

    $this->document->addScript(array(
      'catalog/view/theme/vista/public/js/account/address_form.js',
    ));

    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/address_form.twig')) {
      $this->template = $this->config->get('config_template') . '/template/account/address_form.twig';
    } else {
      $this->template = 'default/template/account/address_form.twig';
    }

    $this->children = array(
      'common/breadcrumbs',
      'common/column_left',
      'common/column_right',
      'common/content_top',
      'common/content_bottom',
      'common/footer',
      'common/header'
    );

    if (!$this->ftrgeralregistry->isApp()) {
      array_push($this->children, 'module/account');
    }

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

  protected function validateForm()
  {
    if ((utf8_strlen($this->request->post['firstname']) < 1) || (utf8_strlen($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['address_1']) < 1) || (utf8_strlen($this->request->post['address_1']) > 70)) {
      $this->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)) {
      $this->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)) {
      $this->error['complemento'] = $this->language->get('error_complemento');
    }

    if ((utf8_strlen($this->request->post['apelido']) < 3) || (utf8_strlen($this->request->post['apelido']) > 80)) {
      $this->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)) {
      $this->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) || ((trim($this->request->post['codigo_municipio']) == '') || (utf8_strlen($this->request->post['codigo_municipio']) == 0))) {
      $this->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)) {
        $this->error['postcode'] = $this->language->get('error_postcode');
      }
    }

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

    if(isset($this->request->post['zone_id']) && isset($this->request->post['codigo_municipio'])){

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

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

    }

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


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

  protected function validateDelete()
  {
    if ($this->model_account_address->getTotalAddresses() == 1) {
      $this->error['warning'] = $this->language->get('error_delete');
    }

    if ($this->customer->getAddressId() == $this->request->get['address_id']) {
      $this->error['warning'] = $this->language->get('error_default');
    }

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

  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 getAddressByPostcode()
  {

    $cep = $this->request->post['postcode'];

    $json = array();

    $wsdl = "https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl";
    $old = ini_get('default_socket_timeout');
    ini_set('default_socket_timeout', 5);
    $params = array("trace" => true, "connection_timeout" => 4);
    $clientSoap = new SoapClient($wsdl, $params);

    $soapArgs = array(
      'cep' => $cep
    );

    try {
      $result = $clientSoap->consultaCep($soapArgs);

      $json['endereco']['end'] = $result->return->end;
      $json['endereco']['bairro'] = $result->return->bairro;
      $json['endereco']['complemento'] = $result->return->complemento . ' ' . $result->return->complemento2;
      $json['endereco']['cidade'] = $result->return->cidade;

      $this->load->model('localisation/zone');
      $zone_id = $this->model_localisation_zone->getZoneByCountryId(Type_PaisId::Tp_Brasil, $result->return->uf);
      $json['endereco']['uf'] = $zone_id;

    } catch (Exception $e) {
      $log = new Log('errorBuscarCep.txt');
      $log->write('Excecao capturada: ' . $e->getMessage() . ": " . $cep);
      $json['error'] = true;
      ini_set('default_socket_timeout', $soaptimeoutini);//caso de erro assegura que voltou o timeout padrão...
    }
    ini_set('default_socket_timeout', $old);
    $this->response->setOutput(json_encode($json));

  }

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

  protected function app()
  {
    if ($this->ftrgeralregistry->isApp()) {
      $this->document->addScriptApp(array(
        'catalog/view/theme/appmobile/public/js/mainheaderform.js',
        'catalog/view/theme/appmobile/js/page.address-form.js',
        'public/js/postcode.js'
      ));

      $this->data['dont_know_cep'] = $this->getChild('postcode/postcode');
    }
  }

}
