<?php
require_once('freteutils.php');
class ModelShippingIntelipost extends FreteUtils {

	function getQuote($address, $pProduct = Array()) {
    $this->load->type('tipocomum');
    $this->load->type('tipofrete');
    $this->load->helper('ftr_geral');

    //feito a principio para skyhub Frete, mais pode ser utilizado para qualquer frete que
    //não tenha informações do estado...
    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('intelipost_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('intelipost_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['origin_zip_code']      = str_replace('-','',$this->config->get('intelipost_cep_origem'));
        $dataSend['destination_zip_code'] = str_replace('-','',$address['postcode']);

        $dataSend['additional_information'] = array(
          "sales_channel" => "ecommerce",
          "lead_time_business_days" => $this->config->get('intelipost_prazo_extra'),
        );

        if ($this->config->get('intelipost_valor_extra') > 0){
          if ($this->config->get('intelipost_tipo_valor_extra') == Type_AcrescimoDesconto::Tp_Porcentagem){
            $dataSend['additional_information']['extra_cost_percentage'] = $this->config->get('intelipost_valor_extra');
          }else{
            $dataSend['additional_information']['extra_cost_absolute'] = $this->config->get('intelipost_valor_extra');
          }
        }

        $dataSend['identification']['url'] = $this->config->get('config_ssl');

        if ($this->config->get('intelipost_tipo_cotacao') == Type_IntelipostTipoCote::Tp_InteliProduto){
          $this->load->dmodel('catalog/product');
          $this->load->model('catalog/category');
          foreach ($products as $product){

            $categories = $this->dmodel_catalog_product->getProductCategories($product['product_id']);
            $category_info = end($categories);
            $category_info = $this->model_catalog_category->getCategory($category_info);

            $dataSend['products'][] = array(
              "weight"        => $product['weight'],
              "cost_of_goods" => $product['price'],
              "width"         => $product['width'],
              "height"        => $product['height'],
              "length"        => $product['length'],
              "quantity"      => $product['quantity'],
              "sku_id"        => $product['sku'],
              "product_category"=> isset($category_info['name']) ? $category_info['name'] : ''
            );
          }
          $return = $this->intelipost->getQuoteProduto(json_encode($dataSend));
        }else{
          $caixas = $this->organizarEmCaixas($products);

          foreach ($caixas as $caixa){
            $dataSend['volumes'][] = array(
              "weight"        => $caixa['weight'],
              "cost_of_goods" => $this->getTotalCaixa($caixa['produtos']),
              "width"         => $caixa['width'],
              "height"        => $caixa['height'],
              "length"        => $caixa['length'],
              "volume_type"  => "BOX"
            );
          }
          $return = $this->intelipost->getQuoteVolume(json_encode($dataSend));
        }

        $volumesList = array();
        foreach ($return->volumes as $vol){
          if(is_object($vol)){
            $volumesList[] = array(
              'weight'  => $vol->weight,
              'width'   => $vol->width,
              'height'  => $vol->height,
              'lenght'  => $vol->length,
              'cost_of_goods' => $vol->cost_of_goods
            );
          }
        }

        foreach ($return->delivery_options as $itemQuote){
          if (is_object($itemQuote)){
            $text = '';
            $previsão = '';
            $totalFrete = 0;
            if ($itemQuote->delivery_estimate_business_days>0){
              $previsão = ' - Previsão: ' . $itemQuote->delivery_estimate_business_days .' dias uteis.';
            }

            if (strpos($itemQuote->delivery_method_name, $itemQuote->logistic_provider_name) === false){
              $text = $itemQuote->logistic_provider_name.' ('.$itemQuote->delivery_method_name.')';
            }else{
              $text = $itemQuote->delivery_method_name;
            }

            $quote_data[$itemQuote->delivery_method_id] = array(
              'code'         => 'intelipost.'.$itemQuote->delivery_method_id,    //ftr_geral::getStrToIndex(trim($itemQuote->delivery_method_name)),
              'title'        => $text.$previsão,
              'cost'         => round((float)$itemQuote->final_shipping_cost, 2, PHP_ROUND_HALF_UP),
              'days'         => $itemQuote->delivery_estimate_business_days,
              'text'         => $this->currency->format($itemQuote->final_shipping_cost),
              'volumes_info' => $volumesList
            );
          }
        }

        if ($return) {
            $method_data = array(
              'code'       => 'intelipost',
              'title'      => $this->config->get('intelipost_descricao'),
              'quote'      => $quote_data,
              'sort_order' => $this->config->get('intelipost_sort_order'),
              'error'      => false
             );
          }

      }catch (Exception $e){
        $logData = [
            'event'    => 'ShippingIntelipost::getQuote',
            'exception'=> [
                'type'    => get_class($e),
                'message' => $e->getMessage(),
                'code'    => $e->getCode(),
                'file'    => $e->getFile(),
                'line'    => $e->getLine(),
                'trace'   => $e->getTraceAsString()
            ],
            'datetime' => date('c'), // data/hora no padrão ISO
        ];
        $this->log->write(json_encode($logData, JSON_UNESCAPED_UNICODE));
      }

    }
		return $method_data;
	}


}
