<?php
class ControllerShippingTnt extends Controller {
  private function loadLanguage() {
    $language = $this->load->language('shipping/tnt');
    $this->data = array_merge($this->data, $language);
  }

  private function breadcrumbs() {
    $token = $this->session->data['token'];
    $type = $this->request->get['type'];

    $this->data['breadcrumbs'] = [
      [
        'href' => $this->url->link('common/home', 'token=' . $token, 'SSL'),
       	'text' => $this->language->get('text_home'),
      ],
      [
        'href' => $this->url->linkAnchor('extension/module', 'token=' . $token, 'tab-info=' . $type, 'SSL'),
       	'text' => $this->language->get('text_shipping'),
      ],
      [
        'href' => $this->url->link('shipping/tnt', 'token=' . $token . '&type=' . $type, 'SSL'),
       	'text' => $this->language->get('heading_title'),
      ]
    ];
  }

	public function index() {
    $this->loadLanguage();
    $this->breadcrumbs();

    $this->document->setTitle($this->language->get('heading_title'));
    $this->document->addScript('admin/public/js/shipping/tnt.js');

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

		$this->data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();

    $this->data['Type_CadastroPessoa'] = Type_CadastroPessoa::getEnumList();
    $this->data['Type_TntServico'] = Type_TntServico::getEnumList();
    $this->data['Type_TntFrete'] = Type_TntFrete::getEnumList();
    $this->data['Type_TntPeso'] = Type_TntPeso::getEnumList();
    $this->data['Type_Status'] = Type_Status::getEnumList();

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

    $url_action = $this->url->link(
      'shipping/tnt/save',
      'token=' . $token . '&type=' . $this->request->get['type'],
      'SSL'
    );

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

    $this->data['data'] = [
      'configurations' => $this->model_setting_setting->getSetting('tnt'),
      'action' => str_replace('&amp;', '&', $url_action),
      'back' => str_replace('&amp;', '&', $url_back),
    ];

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

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

  public function save() {
    $this->loadLanguage();

    $response = [];

    $this->removeMask();

    if (!$this->user->hasPermission('modify', 'shipping/tnt')) {
      $response['warning'] = $this->language->get('error_permission');
      return $this->response->setOutputJson($response);
		}

    $validate = $this->validate();
    if ($validate) {
      $response['errors'] = $validate;
      return $this->response->setOutputJson($response);
    }

		$this->load->model('setting/setting');
		$this->model_setting_setting->editSetting('tnt', $this->request->post);
		$response['success'] = $this->language->get('text_success');

    return $this->response->setOutputJson($response);
  }

  private function removeMask() {
    // $this->request->post['tnt_padrao'] = 'true';
    $this->request->post['tnt_cnpj'] = ftr_geral::removeMaskToDouble($this->request->post['tnt_cnpj']);
    $this->request->post['tnt_adicional'] = ftr_geral::removeMaskToInt($this->request->post['tnt_adicional']);
    $this->request->post['tnt_prazo_adicional'] = ftr_geral::removeMaskToInt($this->request->post['tnt_prazo_adicional']);
  }

	private function validate() {
    $this->loadLanguage();
    $this->load->type('tipocomum');

    extract($this->request->post);

    $errors = [];

    $errors = $this->validate->execute([
      'tnt_status' => [
        'value' => $tnt_status,
        'validates' => ['isEmpty', 'isEnabledOrDisabled']
      ],
      'tnt_sort_order' => [
        'value' => $tnt_sort_order,
        'validates' => ['isIntegerNumber']
      ],
      'tnt_user_login' => [
        'value' => $tnt_user_login,
        'validates' => ['isEmpty', 'isEmail']
      ],
      'tnt_tipo_pessoa' => [
        'value' => $tnt_tipo_pessoa,
        'validates' => ['isEmpty', 'isNaturalOrLegalPerson']
      ],
      'tnt_situacao_trib' => [
        'value' => $tnt_situacao_trib,
        'validates' => ['isEmpty']
      ],
      'tnt_postcode' => [
        'value' => $tnt_postcode,
        'validates' => ['isEmpty', 'isCep']
      ],
      'tnt_divisao_cliente' => [
        'value' => $tnt_divisao_cliente,
        'validates' => ['isEmpty']
      ],
      'tnt_geo_zone_id' => [
        'value' => $tnt_geo_zone_id,
        'validates' => ['isEmpty']
      ],
    ]);

    $tntServico = Type_TntServico::getEnumList();
    $tntServicoIsValid = false;
    foreach ($tntServico as $key => $value) {
      if ($tnt_tipo_servico == $key) {
        $tntServicoIsValid = true;
      }
    }
    if (!$tntServicoIsValid) {
      $errors['tnt_tipo_servico'][] = $this->language->get('error_tipo_servico');
    }


    $tntFrete = Type_TntFrete::getEnumList();
    $tntFreteIsValid = false;
    foreach ($tntFrete as $key => $value) {
      if ($tnt_tipo_frete == $key) {
        $tntFreteIsValid = true;
      }
    }
    if (!$tntFreteIsValid) {
      $errors['tnt_tipo_frete'][] = $this->language->get('error_tipo_frete');
    }


    $tntPeso = Type_TntPeso::getEnumList();
    $tntPesoIsValid = false;
    foreach ($tntPeso as $key => $value) {
      if ($tnt_tipo_peso == $key) {
        $tntPesoIsValid = true;
      }
    }
    if (!$tntPesoIsValid) {
      $errors['tnt_tipo_peso'][] = $this->language->get('error_tipo_peso');
    }


    $errorsCnpjOrCpf = [];
    if ($tnt_tipo_pessoa == Type_CadastroPessoa::Tp_Juridico) {
      $errorsCnpjOrCpf = $this->validate->execute([
        'tnt_cnpj' => [
          'value' => $tnt_cnpj,
          'validates' => ['isEmpty', 'isCnpj']
        ],
        'tnt_ie' => [
          'value' => $tnt_ie,
          'validates' => ['isEmpty']
        ],
      ]);
    }
    if ($tnt_tipo_pessoa == Type_CadastroPessoa::Tp_Fisico) {
      $errorsCnpjOrCpf = $this->validate->execute([
        'tnt_cnpj' => [
          'value' => $tnt_cnpj,
          'validates' => ['isEmpty', 'isCpf']
        ]
      ]);
    }
    if ($errorsCnpjOrCpf) {
      $errors = array_merge($errors, $errorsCnpjOrCpf);
    }

    return $errors;
	}
}
