<?php
require_once('freteutils.php');

class ModelShippingKangu extends FreteUtils
{
    function getQuote($address, $pProduct = array())
    {
        $this->load->type('tipocomum');
        $this->load->type('tipofrete');
        $this->load->helper('ftr_geral');

        if ((!$address['zone_id']) && ($address['layout_id'] == Type_SendPostcode::Tp_Product)) {
            $status = true;
        } else {
            $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('kangu_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");

            if (!$this->config->get('kangu_geo_zone_id')) {
                $status = true;
            } elseif ($query->num_rows) {
                $status = true;
            } else {
                $status = false;
            }
        }

        $method_data = array();

        if ($status) {
            $this->setUnidadesMedida();

            try {
                if (sizeof($pProduct) > 0) {
                    $products = $pProduct;
                } else {
                    $products = $this->cart->getProducts();
                }

                $dataSend = array();
                $dataSend['cepOrigem'] = str_replace('-', '', $this->config->get('kangu_postcode'));
                $dataSend['cepDestino']  = str_replace('-', '', $address['postcode']);

                $dataSend['origem'] = 'Futura Sistemas';

                // Frete por produto
                $this->load->dmodel('catalog/product');
                $this->load->model('catalog/category');


                foreach ($products as $product) {
                    $dataSend['produtos'][] = array(
                        "peso"          => $product['weight_unit'] ?? $product['weight'], // Se esta no carrinho ou na finalização de pedido, o campo chama weight_unit, se for na tela do produto chama weight,
                        "largura"       => $product['width'],
                        "altura"        => $product['height'],
                        "comprimento"   => $product['length'],
//                        "tipo"          => 'C',
                        "valor"         => $product['price'],
                        "produto"       => $product['name'],
                        "quantidade"    => $product['quantity']
                    );
                }
                /* "E" Entrega normal  “X”,  Entrega expressa  “R”  Retira */
                $dataSend['servicos'] = $this->config->get('kangu_inShop')? array('E','X','R') : array('E','X');
                $dataSend['ordernar']  = $this->config->get('kangu_postcode') == Type_sort_order::Tp_Preco ? Type_sort_order::Tp_Preco : Type_sort_order::Tp_Prazo;

                $fretes = $this->kangu->getQuote(json_encode($dataSend));

                //Gambinhas pois quando vem apenas um frete ele retorna o objeto direto ao inves de um array de objetos. (Ai dava mil erros no "foreach" abaixo)
                $return = array();

                if(!is_array($fretes) && is_object($fretes)){
                    $return[] = $fretes;
                } else {
                    $return = $fretes;
                }
              $method_data = $this->getMethodData($return, $products);

            } catch (Exception $e) {
                $this->log->write(print_r($e, true));
            }
        }
        return $method_data;
    }

    private function getMethodData($return, $products){
      $pickup = [];
      // Após retorno
      foreach ($return as $itemQuote) {
        if (is_object($itemQuote)) {
          if (isset($itemQuote->error) AND ($itemQuote->error->codigo != '')) {
            continue;
          }

          $prazo = $itemQuote->prazoEnt;
          $preco = $itemQuote->vlrFrete;

          $previsão = '';
          $address = '';

          if ($itemQuote->prazoEnt > 0) {
            $previsão = ' - Previsão: ' . $prazo . ' dias.';
          }

          $text = $itemQuote->descricao;

          $volumesList = array();

          if($itemQuote->servico == 'R'){
            $pickup = $itemQuote;
            continue;
          }

          foreach ($products as  $vol){
            $vol2 = (object) $vol;
            if(is_object($vol2)){
              $volumesList[] = array(
                'weight'  => $vol2->weight,
                'width'   => $vol2->width,
                'height'  => $vol2->height,
                'lenght'  => $vol2->length,
                'cost_of_goods' => $vol2->total,
                //'products' => $products,
              );
            }

          }

          $quote_data[$itemQuote->idTransp] = array(
            'code' => 'kangu.'.$itemQuote->idTransp,    //ftr_geral::getStrToIndex(trim($itemQuote->delivery_method_name)),
            'title' => $text . $previsão,
            'cost' => round((float)$preco, 2, PHP_ROUND_HALF_UP),
            'days' => $prazo,
            'text' => $this->currency->format($preco),
            'volumes_info' => $volumesList,
            'quote_reference_code' => $itemQuote->referencia,
            'pickup_address' => $address
          );
        }
      }


      if (empty($quote_data)) {
        return false;
      }

      if ($return) {
        $method_data[] = array(
          'code' => 'kangu',
          'title' => 'Métodos de envio Kangu',
          'quote' => $quote_data,
          'sort_order' => $this->config->get('kangu_sort_order'),
          'error' => false
        );
      }

      if($pickup){
        $quote_pickup = [];
        $previsão = '';
        $address = '';

        if ($pickup->prazoEnt > 0) {
          $previsão = ' - Previsão: ' . $prazo . ' dias.';
        }

        $text = $pickup->descricao;

        $volumesList = array();

        foreach ($products as  $vol){
          $vol2 = (object) $vol;
          if(is_object($vol2)){
            $volumesList[] = array(
              'weight'  => $vol2->weight,
              'width'   => $vol2->width,
              'height'  => $vol2->height,
              'lenght'  => $vol2->length,
              'cost_of_goods' => $vol2->total,
              //'products' => $products,
            );
          }
        }

        foreach ($pickup->pontosRetira as $value){


            $this->load->model('localisation/zone');
            $states = $this->model_localisation_zone->getZonesByCountryId(Type_PaisId::Tp_Brasil);
            foreach ($states as $title_info => $info){
              if ($info['code'] == $value->endereco->uf){
                $zone_id = $info['zone_id'];
              }
            }


          $address = $value->endereco->logradouro. ',  ' .
            $value->endereco->numero. ',  ' .
            $value->endereco->bairro. ',  ' .
            $value->endereco->cidade. ',  ' .
            $value->endereco->uf. ',  ' .
            $value->endereco->cep;

          $quote_pickup[$value->id] = [
            'code' => 'kanguPickup.'.$value->id,    //ftr_geral::getStrToIndex(trim($pickup->delivery_method_name)),
            'title' => $value->nome . $previsão,
            'cost' => round((float)$preco, 2, PHP_ROUND_HALF_UP),
            'days' => $prazo,
            'text' => $this->currency->format($preco),
            'volumes_info' => $volumesList,
            'quote_reference_code' => $value->referencia,
            'pickup_address' => $address,
            'isPickup' => 'Retirar na loja',
            'pickup_zone_id' => $zone_id,
          ];
        }

        if($quote_pickup){
          $method_data[] = array(
            'code' => 'kanguPickup',
            'title' => 'Pontos de retirada Kangu',
            'cost' => $this->currency->format($preco),
            'quote' => $quote_pickup,
            'sort_order' => $this->config->get('kangu_sort_order'),
            'error' => false
          );
        }
      }
      return $method_data;
    }
}

?>