<?php

class ModelShippingMelhorenvio extends Model{

  function newShippingLabel($orderId){
    $this->load->type('tipocomum');
    $this->load->type('tipofuturaserver');
    $this->load->type('tipofrete');

    $this->load->model('sale/order');
    $orderInfo = $this->model_sale_order->getOrder($orderId);

    $this->load->dmodel('sale/order');
    $orderVolumes = $this->dmodel_sale_order->getShippingVolumes($orderId);

    $orderVolumeProducts = $this->dmodel_sale_order->getShippingVolumeProducts($orderId);

    $this->load->dmodel('account/order');
    $orderProducts = $this->dmodel_account_order->getOrderProducts($orderId);

    $invoices = array();
    if (($orderInfo['status_futuraserver'] == Type_PedidoStatus::TpPSt_Faturado)) {
      $this->load->dmodel('notafiscal/notafiscal');
      $invoices = $this->dmodel_notafiscal_notafiscal->getOrderNfe($orderId);
    }

    $melhorenvioserviceid = substr($orderInfo['shipping_code'], strpos($orderInfo['shipping_code'], '.')+1, strlen($orderInfo['shipping_code']));

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

    // Se for correios tem que gerar uma etiqueta por volume, se não for pode gerar apenas uma etiqueta
    $result = array();
    if (in_array($melhorenvioserviceid, Array(Type_MelhorenvioServico::Tp_Pac, Type_MelhorenvioServico::Tp_Sedex, Type_MelhorenvioServico::Tp_MiniEnvios))){
      foreach ($orderVolumes as $value){
        $orderVolumeProductFiltered = array_filter($orderVolumeProducts, function($item) use ($value) {
          return $item['order_shipping_volume_id'] == $value['order_shipping_volume_id'];
        });
        $result[] = $this->generateShippingLabel($orderId, $orderInfo, $orderProducts, $invoices, array($value), $orderVolumeProductFiltered, $melhorenvioserviceid);
      }
    } else {
      $result[] = $this->generateShippingLabel($orderId, $orderInfo, $orderProducts, $invoices, $orderVolumes, $orderVolumeProducts, $melhorenvioserviceid);
    }

    foreach ($result as $value){
      if (isset($value['error'])){
        return $value;
      }
    }

    $buyResult = $this->melhorenvio->buyShippingLabel($result);
    if (isset($buyResult->error)){
      return array('error' => $buyResult->error);
    }

    // adiciona o id das etiquetas no banco
    $this->updateOrderShippingLabelId($orderId, $result);

    $this->melhorenvio->generateShippingLabel($result);

    $retorno = array();

    $labelUrl = $this->printShippingLabel($result);
    $retorno['label_id'] = implode("|", $result);
    $retorno['url'] = $labelUrl->url;

    return $retorno;
  }

  function generateShippingLabel($orderId, $orderInfo, $orderProducts, $invoices, $orderVolumes, $orderVolumeProducts, $melhorenvioServiceId){
    $this->load->type('tipocomum');
    $this->load->type('tipofrete');
    $this->load->type('tipofuturaserver');

    $insurance_value = 0;

    $volumes = array();
    foreach ($orderVolumes as $value) {
      $volumes[] = array(
        "height" => $value['height'],
        "width" => $value['width'],
        "length" => $value['length'],
        "weight" => $value['weight']
      );
    }

    $products = array();
    foreach ($orderVolumeProducts as $value) {
      $products[] = array(
        "name" => $value['name'],
        "quantity" => $value['quantity'],
        "unitary_value" => $value['price']
      );

      $insurance_value += $value['quantity'] * $value['price'];
    }

    $non_commercial = $this->config->get('melhorenvio_declaracao_conteudo') == Type_DsimDnao::Tp_Sim;

    $invoiceKeys = [];
    if (!$non_commercial){
      empty($invoices['chave_acesso']) ? $invoiceKey = '' : $invoiceKey = $invoices['chave_acesso'];
      $invoiceKeys = array(
        "key" => $invoiceKey
//      teste
//      "key" => '35200303652170000149550690000013001000001706'
      );
    }

    $optionTags = array();
    $optionTags[] = array(
      "tag" => $orderInfo['order_id'],
      "url" => null
    );

    empty($orderInfo['telephone']) ? $phone = '19999999999' : $phone = $orderInfo['telephone'];

    $param = array (
      "service" => $melhorenvioServiceId,
      "from" => array (
        "name" => $this->config->get('config_name'),
        "phone" => $this->config->get('melhorenvio_phone'),
        "company_document" => $this->config->get('config_cnpj'),
        "address" => $this->config->get('melhorenvio_address'),
        "city" => $this->config->get('melhorenvio_city'),
        "postal_code" => $this->config->get('melhorenvio_postcode'),
        "number" => $this->config->get('melhorenvio_number'),
        "district" => $this->config->get('melhorenvio_district'),
        "complement" => $this->config->get('melhorenvio_complement')
      ),
      "to" => array(
        "name" => $orderInfo['firstname'] . ' ' . $orderInfo['lastname'],
        "phone" => $phone,
        "email" => $orderInfo['email'],
        "document" => $orderInfo['cpf'],
        "company_document" => $orderInfo['cnpj'],
        "state_register" => $orderInfo['inscricao_estadual'],
        "address" => $orderInfo['shipping_address_1'],
        "complement" => $orderInfo['shipping_complemento'],
        "number" => $orderInfo['shipping_numero'],
        "district" => $orderInfo['shipping_address_2'],
        "city" => $orderInfo['shipping_city'],
        "state_abbr" => $orderInfo['shipping_zone_code'],
        "country_id" => $orderInfo['shipping_iso_code_2'],
        "postal_code" => $orderInfo['shipping_postcode']
      ),
      "products" => $products,
      "volumes" => $volumes,
      "options" => array(
        "insurance_value" => $insurance_value,
        "receipt" => false,
        "own_hand" => false,
        "reverse" => false,
        "non_commercial" => $non_commercial,
        "platform" => "Futura E-commerce",
        "tags" => $optionTags
      )
    );

    if (!empty($this->config->get('config_ie'))){
      $param["from"]["state_register"] = $this->config->get('config_ie');
    }

    if (!empty($invoiceKeys)){
      $param["options"]["invoice"] = $invoiceKeys;
    }

    if ((!empty($this->config->get('melhorenvio_jadlog_agency')))
      &&  (!empty($melhorenvioServiceId))
      &&  (in_array($melhorenvioServiceId, Array(Type_MelhorenvioServico::Tp_Com, Type_MelhorenvioServico::Tp_Package)))){
      $param['agency'] = $this->config->get('melhorenvio_jadlog_agency');
    }

    $result = $this->melhorenvio->addShippingLabelToCart(json_encode($param));

    if (!$result){
      return array('error' => "Não foi possível inserir as etiquetas no carrinho");
    }

    if (!($result instanceof StdClass) && (isset($result['error']))){
      return array('error' => $result['error']);
    }

    return $result->id;
  }

  function updateOrderShippingLabelId($orderId, $labelId){
    $this->load->type('tipofrete');
    $this->load->dmodel('shipping/shippinglabel');

    foreach ($labelId as $value) {
      $dataShippingLabel = array(
        'order_id' => $orderId,
        'shipping_code' => Type_ShippingCode::Tp_ShippingMelhorEnvio,
        'shipping_label' => $value,
        'complete' => Type_Status::Tp_Desabilitado
      );
      $this->dmodel_shipping_shippinglabel->addShippingLabel($dataShippingLabel);
    }
  }

  function printShippingLabel($labelId){
    if (!is_array($labelId)){
      $labelId = explode("|", $labelId);
    }

    return $this->melhorenvio->printShippingLabel($labelId);
  }

  function shippingLabelExists($labelId){
    $this->melhorenvio->getShippingLabel($labelId) ? $result = true : $result = false;
    return $result;
  }

}