<?php

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

  public function index()
  {

    $language = $this->language->load('shipping/pickup');
    $this->data = array_merge($this->data, $language);

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

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

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

		$this->data['ftr_geral'] = new ftr_geral();

		$this->data['Type_Status'] = $this->load->typeForTwig('Type_Status');

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

        $address_info = array(
            "postcode"	        => isset($this->request->post['postcode']) ? $this->request->post['postcode'] : '',
            "address_1"	        => isset($this->request->post['address_1']) ? $this->request->post['address_1'] : '',
            "tipo_logradouro"	=> isset($this->request->post['tipo_logradouro']) ? $this->request->post['tipo_logradouro'] : '',
            "logradouro"	    => isset($this->request->post['logradouro']) ? $this->request->post['logradouro'] : '',
            "city"	            => isset($this->request->post['city']) ? $this->request->post['city'] : '',
            "numero"	        => isset($this->request->post['numero']) ? $this->request->post['numero'] : '',
            "address_2"	        => isset($this->request->post['address_2']) ? $this->request->post['address_2'] : '',
            "complemento"	    => isset($this->request->post['complemento']) ? $this->request->post['complemento'] : '',
            "zone_id"	        => isset($this->request->post['zone_id']) ? $this->request->post['zone_id'] : '',
            "country_id"	    => isset($this->request->post['country_id']) ? $this->request->post['country_id'] : '',
            "codigo_municipio"	=> isset($this->request->post['codigo_municipio']) ? $this->request->post['codigo_municipio'] : ''
        );

        unset($this->request->post['postcode']);
        unset($this->request->post['address_1']);
        unset($this->request->post['tipo_logradouro']);
        unset($this->request->post['logradouro']);
        unset($this->request->post['city']);
        unset($this->request->post['numero']);
        unset($this->request->post['address_2']);
        unset($this->request->post['complemento']);
        unset($this->request->post['zone_id']);
        unset($this->request->post['country_id']);
        unset($this->request->post['codigo_municipio']);

        $this->request->post['pickup_address_info'] = $address_info;

        $arrayJson = array('pickup_address_info');

        $this->model_setting_setting->editSetting('pickup', $this->request->post, 0, $arrayJson);

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

        $this->redirect($this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'));
    }

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

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

    $this->data['text_enabled'] = $this->language->get('text_enabled');
    $this->data['text_disabled'] = $this->language->get('text_disabled');
    $this->data['text_all_zones'] = $this->language->get('text_all_zones');
    $this->data['text_none'] = $this->language->get('text_none');

    $this->data['entry_geo_zone'] = $this->language->get('entry_geo_zone');
    $this->data['entry_status'] = $this->language->get('entry_status');
    $this->data['entry_message'] = $this->language->get('entry_message');
    $this->data['entry_sort_order'] = $this->language->get('entry_sort_order');


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

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

    $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('text_shipping'),
      'href' => $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'),
      'separator' => ' :: '
    );

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

    $this->data['action'] = $this->url->link('shipping/pickup', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL');

    $this->data['cancel'] = $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL');

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

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

    /* ENDEREÇO */
    $this->data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();
    $address_info = $this->config->get('pickup_address_info');

    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['numero'])) {
        $this->data['numero'] = preg_replace('/([^0-9])/i', '', $this->request->post['numero']);
    } elseif (!empty($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 (!empty($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');
    }

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

    /* ENDEREÇO */

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

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

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

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

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

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

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

    $this->response->setOutput($this->render('shipping/pickup'));
  }

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

    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']) < 1) || (utf8_strlen($this->request->post['address_2']) > 50)) {
        $this->error['address_2'] = $this->language->get('error_address_2');
    }

    $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) ||  (utf8_strlen(trim($this->request->post['codigo_municipio'])) == 0)) {
        $this->error['city'] = $this->language->get('error_city');
    }


    if ((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 (!$this->error) {
      return true;
    } else {
      return false;
    }
  }
}
