<?php
class ControllerPostcodePostcode extends Controller
{

  public function index()
  {

    $this->load->helper('ftr_geral');
    $language = $this->load->language('postcode/postcode');
    $this->data = array_merge($this->data, $language);

    $this->data['loading'] = $this->url->link('assets/img/loading-black.svg', '', 'SSL', false, true);

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

  public function listAddressData()
  {

    $this->listAddress();

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

  }

  public function listAddress()
  {

    if (trim(isset($this->request->post['dados'])) && ($this->request->post['dados'] != '')) {
      $dados = trim($this->request->post['dados']);
    } else {
      $this->data['error'] = 'O campo busca esta em branco!';
    }

    if (!isset($this->data['error'])) {
      try {
        $this->load->dmodel('localisation/zone');
        $results = $this->cep->getCepEndereco($dados);
        if ($results) {
          foreach (array_slice($results, 0, 100) as $key => $result) {
            $this->data['dados'][] = array(
              'postcode' => substr_replace($result['cep'], '-', 5, 0),
              'address_1' => ucwords(mb_strtolower(html_entity_decode(trim($result['logradouro_completo']), ENT_QUOTES, 'UTF-8'))),
              'complemento' => ucwords(mb_strtolower(html_entity_decode(trim($result['complemento']), ENT_QUOTES, 'UTF-8'))),
              'address_2' => ucwords(mb_strtolower(html_entity_decode(trim($result['bairro']), ENT_QUOTES, 'UTF-8'))),
              'city' => ucwords(mb_strtolower(html_entity_decode(trim($result['cidade']), ENT_QUOTES, 'UTF-8'))) . '/' . $result['uf']
            );
          }
        } else {
          $this->data['error'] = 'A busca não retornou nenhuma informação, altere o endereço ou tente novamente mais tarde!';
        }
      } catch (Exception $e) {
        $this->data['error'] = 'Ocorreu um erro ao consultar as informações. Tente novamente mais tarde!';
      }
    }

    $this->response->setOutput($this->render('postcode/listAddress'));

  }

  public function search($forQuote = false)
  {

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

    $json = array();

    if (isset($this->request->post['cep']) && ($this->request->post['cep'] != '')) {
      $cep = preg_replace("/[^0-9]/", "", $this->request->post['cep']);
    } else {
      $json['error'] = 'Nenhum cep foi informado!';
    }

    if (!$json) {

      if (isset($this->request->post['app'])) {
        //para rodar no success do ajax somente oq for especifico para o app
        $json['app'] = true;
      } elseif (isset($this->request->post['frete'])) {
        //para rodar no success do ajax somente oq for especifico para o calculo do frete
        $json['frete'] = true;
      }

      try {
        $this->load->dmodel('localisation/zone');
        $result = $this->cep->getCep($cep);

        if ($result) {
          if (isset($this->request->post['customer_id'])) {
            $this->updateAddress($result);
          }

          $zone_id = $this->dmodel_localisation_zone->getZoneIdByUf($result['uf']);

          $format = fn($value) => ucwords(mb_strtolower($value));

          $json['dados'] = array(
            'postcode' => substr_replace($result['cep'], '-', 5, 0),
            'address_1' => !empty($result['logradouro_completo']) ? $result['logradouro_completo'] : $result['logradouro'],
            'tipo_logradouro' => $result['tipo_logradouro'] ?? $result['tipoLogradouro'],
            'logradouro' => $result['logradouro'] ?? $result['nomeLogradouro'],
            'address_2' => $result['bairro'],
            'city' => $result['cidade'] ?? $result['localidade'],
            'zone_id' => $zone_id,
            'codigo_municipio' => $result['codigo_municipio'] ?? null,
          );

          if (isset($result['logradouro_completo'])) {
            $json['dados'] = array_map($format, $json['dados']);
          }
        } else {
          $json['error'] = 'CEP não encontrado, cadastre seu endereço.';
        }

      } catch (Exception $e) {
        $json['error'] = 'Ocorreu um erro ao consultar o CEP. Tente novamente mais tarde!';
      }
    }

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

    if ($forQuote) {
      return $json;
    } else {
      $this->response->setOutputJson($json);
    }

  }

  public function listCities()
  {
    $this->load->dmodel('localisation/ibge');
    $json = array();
    $json['cities'] = $this->dmodel_localisation_ibge->getMunicipios($this->request->post['zone_id']);
    $this->response->setOutputJson($json);
  }

  public function listStates()
  {
    $this->load->model('localisation/zone');
    $this->response->setOutputJson($this->model_localisation_zone->getZonesByCountryId(Type_PaisId::Tp_Brasil));
  }

  public function updateAddress(&$addressdata) {
    $this->load->dmodel('account/customer');
    $addresses = $this->dmodel_account_customer->getAddresses($this->request->post['customer_id']);
    foreach ($addresses as $address) {
      if ($address['postcode'] == $this->request->post['cep']) {
        if (empty($addressdata['logradouro']) && (!empty($address['address_1']) || !empty($address['logradouro']))) {
          $addressdata['logradouro'] = $address['address_1'] ?? $address['logradouro'];
          $addressdata['bairro'] = !empty($addressdata['bairro']) ? $addressdata['bairro'] : $address['address_2'];
        }

        if (!empty($addressdata['logradouro']) && (empty($address['address_1']) && empty($address['logradouro']))) {
          $dataToSave = [
            'logradouro' => $addressdata['logradouro'],
            'address_1' => $addressdata['logradouro'],
            'address_2' => !empty($addressdata['bairro']) ? $addressdata['bairro'] : $address['address_2']
          ];
          $this->dmodel_account_customer->updateAddress($address['address_id'], $dataToSave);
        }
      }
    }
  }

}
?>