<?php

class SkyHubUtils extends WebServiceMktp
{
    public $header;
    public $pathEtiqueta;

    public function __construct($registry)
    {
        parent::__construct($registry);
        $this->API_DOMAIN = 'https://api.skyhub.com.br';

        /*
            O x-accountmanager-key é especifico da futura e unico para todos os clientes,
            é ele quem indica para o skyhub que o cliente utiliza a nossa integração,
            por isso é fixo na requisição
            x-accountmanager-key: Wmz5zTSxcf
        */

        $this->header = array(
            'X-User-Email: ' . $this->config->get('skyhub_email'),
            'x-Api-Key: ' . $this->config->get('skyhub_api_key'),
            'x-accountmanager-key: '. $this->config->get('skyhub_account_manager_key'),
            'Accept: application/json;charset=UTF-8',
            'Content-Type: application/json'
        );

        $this->pathEtiqueta = DIR_CACHE.'cachefiles/';
    }

    public function validateReturnCredentials($data){
        $message = '';
        if( property_exists($data, 'message')  ){
            $message = $data->message;
        }else if ( property_exists($data, 'error' ) ){
            $message = $data->error;
        }

        if( ( strtolower($message) == 'invalid authentication credentials') || ( strtolower($message) == 'conta bloqueada ou inexistente') ||
        ( substr_count($message,'account')>0 && substr_count($message,'inactive')>0   )){
            $this->db->query("UPDATE oc_setting SET `value` = '0' WHERE `group` = 'skyhub' AND `key` = 'skyhub_status' AND store_id = '0'");
            $this->db->query("INSERT INTO oc_setting SET store_id = '0', `group` = 'skyhub', `key` = 'skyhub_invalid_credential', `value` = '1'");
        }

    }

    public function callAPI($url, $method = 'GET', $dataSend = false, $header = array(), $file = false, &$httpcode = false, $dataType = Type_DadosSend::TpDados_Identificar, $returnFile = false)
    {
        $httpcode = 0;

        $this->error = '';
        // coloquei o url_encode pra nao bugar os endpoints com "Lojas Americanas" que não funciona apenas em produção
        // por causa do espaço no meio que tem que ser trocado por %20, caso der algum problema terá que fazer de outra forma
        $data = parent::callAPI($this->url_encode($url), $method, $dataSend, $header, $file, $httpcode, $dataType, $returnFile);

        /* função substr_compare retonar 0 caso a comparação seja verdadeira
         * esta comparadando se o httocode retornado pelo skyhub começa com 2 que é
         * o digito inicial dos codigos de sucesso retornados por eles. (200,201,204)
         */
        if (substr_compare($this->httpcode, '2', 0, 1) == 0) {

            //retornamos true quando o data for vazio por que no httpcode 204 ele não retorna o objeto editado mas é um codgo de sucesso.
            return (empty($data)) ? true : $data;

        } else {

            $translatedMessage = null;
            if ((!is_null($data)) && (property_exists($data, 'error'))){
                foreach (TypeSkyHubReturnApiError::getEnumListConst() as $err) {
                    if ( strpos($data->error,TypeSkyHubReturnApiError::getNickFromConstValue($err))>0 ){
                        $translatedMessage = str_replace(
                            TypeSkyHubReturnApiError::getNickFromConstValue($err),
                            TypeSkyHubReturnApiError::getDescriptionFromConstValue($err),
                            $data->error
                        );
                    }
                }
            }

            if ((!is_null($data)) && (property_exists($data, 'message'))) {
                $this->validateReturnCredentials($data);
                $this->error = $data->message;
            } elseif ((!is_null($data)) && (property_exists($data, 'status')) && (property_exists($data, 'error'))) {
                $this->validateReturnCredentials($data);
                $this->error = '(' . $data->status . ') ' . $translatedMessage ? $translatedMessage : $data->error;
            } elseif ((!is_null($data)) && (property_exists($data, 'error'))) {
                $this->validateReturnCredentials($data);
                $this->error = $translatedMessage ? $translatedMessage : $data->error;
            }  elseif ((!is_null($data)) && (property_exists($data, 'errors')) && (property_exists($data->errors, 'detail'))) {
                $this->validateReturnCredentials($data);
                $this->error = $translatedMessage ? $translatedMessage : $data->errors->detail;
            }

            if (empty($this->error)) {
                $this->error = $this->httpcode . ' - ' . TypeSkyHubHttpCode::getNickFromValue($this->httpcode);
            }

            return false;
        }
    }


    public function convertPicturesObject($picturesobj)
    {
        $pictures = $picturesobj->getImagens();
        $retorno = array();

        if (count($pictures) <= 0) {
            return $retorno;
        };

        foreach ($pictures as $img) {
            $retorno[] = $img->getLink();
        }
        return $retorno;

    }

    public function getOrderQueue()
    {
        $url = $this->API_DOMAIN . '/queues/orders/';
        $metodo = 'GET';
        $retorno = $this->callAPI($url, $metodo, null, $this->header);

        if (!empty($retorno)) {
            if ($retorno instanceOf StdClass) {
              $this->marketplace->logArray[] = array('tipoEnviado' => Type_LogEnviado::Tp_LogRecebido, 'tipoIntegracao' => Type_MarketPlace::Tp_SkyHub,
                'origem' => __METHOD__, 'tipoLog' => Type_Log::Tp_LogPedido, 'tipoId' => Type_LogId::Tp_LogIdMktPedido, 'entidadeId' => $retorno->code ?? '',
                'url' => $url, 'metodo' => $metodo, 'httpCode' => $this->httpcode, 'retorno' => $retorno, 'dataHora' => $this->db->dataAtual());
            }
            return $retorno;
        } else {
            return false;
        }
    }

    public function getOrderWs($mktOrder)
    {
        $url = $this->API_DOMAIN . '/orders/' . $mktOrder;
        $metodo = 'GET';
        $retorno = $this->callAPI($url, $metodo, null, $this->header);

        if (!empty($retorno)) {
            $this->marketplace->logArray[] = array('tipoEnviado' => Type_LogEnviado::Tp_LogRecebido, 'tipoIntegracao' => Type_MarketPlace::Tp_SkyHub,
              'origem' => __METHOD__, 'tipoLog' => Type_Log::Tp_LogPedido, 'tipoId' => Type_LogId::Tp_LogIdMktPedido, 'entidadeId' => $mktOrder, 'url' => $url,
              'metodo' => $metodo, 'httpCode' => $this->httpcode, 'retorno' => $retorno, 'dataHora' => $this->db->dataAtual());
            return $retorno;
        } else {
            return false;
        }
    }

    protected function setFilterURL(&$result, $filtro, $param)
    {
        if (isset($param) && $param) {
            $result .= $result == '' ? '?' . $filtro . $param : '&' . $filtro . $param;
        }
    }

    public function getOrders($data)
    {
        $filtro = '';

        $this->setFilterURL($filtro, 'filters[remote_code]=', $data['filter_id']);
        $this->setFilterURL($filtro, 'filters[start_date]=', $data['filter_date_start']);
        $this->setFilterURL($filtro, 'filters[end_date]=', $data['filter_date_end']);
        foreach ($data['filter_status'] as $value) {
            $this->setFilterURL($filtro, 'filters[statuses][]=', $value);
        }
        $this->setFilterURL($filtro, 'page=', $data['page']);
        $this->setFilterURL($filtro, 'per_page=', $data['per_page']);

        $retorno = $this->callAPI($this->API_DOMAIN . '/orders/' . $filtro, 'GET', null, $this->header);

        if (!empty($retorno)) {
            return json_decode(json_encode($retorno), true);
        } else {
            return false;
        }
    }

    public function getErrors($error_type)
    {
        $retorno = $this->callAPI($this->API_DOMAIN . '/sync_errors/' . $error_type, 'GET', null, $this->header);

        if (!empty($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }


    public function deleteOrderQueue($mktOrder)
    {
        $retorno = $this->callAPI($this->API_DOMAIN . '/queues/orders/' . $mktOrder, 'DELETE', null, $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function orderJsonToObject($jsonOrder)
    {
        try {
            $this->load->helper('ftr_validacao');
            $buyer = new MktBuyer();
            $buyerSendAdd = new MktAddress();
            $buyerBillingAdd = new MktAddress();
            $pedido = new MktPedido();

            if (ftr_validacao::isCpf($jsonOrder->customer->vat_number)) {
                $tipo_doc = Type_Pessoa::TpPess_fisica;
            } elseif (ftr_validacao::isCnpj($jsonOrder->customer->vat_number)) {
                $tipo_doc = Type_Pessoa::TpPess_Juridica;
            } else {
                $tipo_doc = Type_Pessoa::TpPess_naoInformado;
            }

            $splitName = explode(' ', $jsonOrder->customer->name);
            $firstname = $splitName[0];

            if (isset($splitName[1])) {
                $lastName = substr($jsonOrder->customer->name, strlen($firstname) + 1, strlen($jsonOrder->customer->name) - strlen($firstname) + 1);
            } else {
                $lastName = '';
            }

            if (isset($jsonOrder->customer->phones[0])) {
                $phone = $jsonOrder->customer->phones[0];
                $phone = preg_replace('/[^0-9]/', '', $phone);

                //validação para remover codigo DDI
                $pos55 = stripos($phone, '55');
                if (strlen($phone) >= 12) {
                  $pedido->setComment($pedido->getComment().' Telefone: '.$phone);
                  $phone = ($pos55 !== false) ? substr($phone, 2, strlen($phone)) : $phone;
                }

                //Validação para tirar o primeiro zero caso digite 019 ou 011 por exemplo
                if (substr($phone, 0, 1) == '0'){
                  $phone = substr($phone, 1, strlen($phone));
                }

                $phone = substr($phone,-11);
            } else {
                $phone = '';
            }

            $gender = null;
            if (strtoupper($jsonOrder->customer->gender) == "MALE") {
                $gender = Type_Genero::TpGen_Masc;
            } elseif (strtoupper($jsonOrder->customer->gender) == "FEMALE") {
                $gender = Type_Genero::TpGen_Fem;
            }

            $buyer
                ->setDocumento($jsonOrder->customer->vat_number)
                ->setTipoPessoa($tipo_doc)
                ->setFirstName($firstname)
                ->setLastName($lastName)
                ->setGenero($gender)
                ->setPhone($phone);

            if (!is_null($jsonOrder->customer->date_of_birth)) {
                $buyer->setDateBirth(DateTime::createFromFormat('Y-m-d', $jsonOrder->customer->date_of_birth));
            }

            // Send address
            $postcode = substr(preg_replace('/[^0-9]/', '', $jsonOrder->shipping_address->postcode),-8);
            $buyerSendAdd
                ->setUf($jsonOrder->shipping_address->region)
                ->setPostCode($postcode)
                ->setPais($jsonOrder->shipping_address->country)
                ->setBairro($jsonOrder->shipping_address->neighborhood)
                ->setCidade($jsonOrder->shipping_address->city)
                ->setComplemento($jsonOrder->shipping_address->complement)
                ->setLogradouroTipo('')
                ->setLogradouro($jsonOrder->shipping_address->street);


            //se tiver virgula ele tira e trata igual era antes.
            $shippingAddressNumber = $jsonOrder->shipping_address->number;
            if(strpos($shippingAddressNumber, ',') !== false){
                $shippingAddressNumber = str_replace(',','', $shippingAddressNumber);
            }

            if (is_numeric($shippingAddressNumber)) {
                $buyerSendAdd->setNumero($shippingAddressNumber);
            } else if (strtoupper($shippingAddressNumber) == 'S/N') {
                $buyerSendAdd->setNumero(0);
            } else {

                $complemento = substr($jsonOrder->shipping_address->number . ' ' . $jsonOrder->shipping_address->complement, 0, 60);


                $buyerSendAdd
                    ->setNumero(0)
                    ->setComplemento($complemento);
            }

            $buyer->setSendAddress($buyerSendAdd);

            // Billing address
            $postcode = substr(preg_replace('/[^0-9]/', '', $jsonOrder->shipping_address->postcode),-8);
            if (!empty($jsonOrder->billing_address)) {
              $buyerBillingAdd
                ->setUf($jsonOrder->billing_address->region)
                ->setPostCode($postcode)
                ->setPais($jsonOrder->billing_address->country)
                ->setBairro($jsonOrder->billing_address->neighborhood)
                ->setCidade($jsonOrder->billing_address->city)
                ->setComplemento($jsonOrder->billing_address->complement)
                ->setLogradouroTipo('')
                ->setLogradouro($jsonOrder->billing_address->street);

              //se tiver virgula ele tira e trata igual era antes.
              $billingAddressNumber = $jsonOrder->billing_address->number;
              if(strpos($billingAddressNumber, ',') !== false){
                  $billingAddressNumber = str_replace(',','', $billingAddressNumber);
              }

              if (is_numeric($billingAddressNumber)) {
                $buyerBillingAdd->setNumero($billingAddressNumber);
              } else if (strtoupper($billingAddressNumber) == 'S/N') {
                $buyerBillingAdd->setNumero(0);
              } else {

                $complemento = substr($jsonOrder->billing_address->number . ' ' . $jsonOrder->billing_address->complement, 0, 60);

                $buyerBillingAdd
                  ->setNumero(0)
                  ->setComplemento($complemento);
              }

              $buyer->setBillingAddress($buyerBillingAdd);
            } else {
              // Se não tem endereço de faturamento, copia as informações do endereço de entrega
              $buyer->setBillingAddress($buyerSendAdd);
            }

            $acrescimo = 0;
            if (property_exists($jsonOrder, 'interest')) {
                $acrescimo = $jsonOrder->interest;
            }

            $discount = 0;
            if (property_exists($jsonOrder, 'discount')) {
                $discount = $jsonOrder->discount;
            }

            $shippingName = $jsonOrder->shipping_method;
            if(property_exists($jsonOrder, 'delivery_contract_type') &&
              in_array($jsonOrder->delivery_contract_type, [TypeSkyhub_DeliveryContractType::Tp_Pickup, TypeSkyhub_DeliveryContractType::Tp_Shipstore])){
              $shippingName = $jsonOrder->delivery_contract_type;
            }

            $pedido
                ->setMktId($jsonOrder->code)
                ->setDateCreated($jsonOrder->placed_at)
                ->setShippingCost($jsonOrder->shipping_cost)
                ->setShippingName($shippingName)
                ->setmktIntegration(Type_MarketPlace::Tp_SkyHub)
                ->setMkTipo(Type_MarketplaceInt::getConstFromNickValue($jsonOrder->channel))
                ->setAddressCombinar(false)
                ->setAcres($acrescimo)
                ->setDiscount($discount)
                ->setBuyer($buyer)
                ->setParam('status', $jsonOrder->status->code)
                ->setParam('status_type', $jsonOrder->status->type)
                ->setParam('calculation_type', $jsonOrder->calculation_type)
                ->setParam('approved_date', $jsonOrder->approved_date)
                ->setParam('shipped_date', $jsonOrder->shipped_date)
                ->setParam('hasInvoice', empty($jsonOrder->invoices->key));

            if (property_exists($jsonOrder, 'shipments') && count($jsonOrder->shipments) > 0) {
                foreach ($jsonOrder->shipments as $shipment) {
                    if (property_exists($shipment, 'tracks') && count($shipment->tracks) > 0) {
                        foreach ($shipment->tracks as $track) {
                            $pedido
                                ->setParam('shipments_carrier', $track->carrier)
                                ->setParam('shipments_code', $track->code);
                        }
                    }
                }
            }

            foreach ($jsonOrder->payments as $payments) {
                $paymentObj = new MktPedidoPayment();

                $paymentObj
                    ->setCode($payments->method)
                    ->setDate($payments->transaction_date)
                    ->setDescription($payments->description)
                    ->setParcels($payments->parcels)
                    ->setAuthorizationCode($payments->autorization_id)
                    ->setValue($payments->value)
                    ->setStatus($payments->status)
                    ->setFlagText($payments->description ?? '');

                $pedido->addPayments($paymentObj);
            }

            $subTotal = 0;
            foreach ($jsonOrder->items as $item) {
                $itemObj = new MktPedidoItem();

                $variation = null;

                if ($item->product_id != $item->id) {
                    $variation = $item->id;
                }

                $original_price = ($item->original_price != 'null') ? $item->original_price : 0;

                $itemObj
                    ->setMktId($item->product_id)
                    ->setPrice($original_price)
                    ->setProductName($item->name)
                    ->setQuantity($item->qty)
                    ->setMktVariationId($variation)
                    ->setMktIdOrderItem($item->product_id);

                $pedido->addItens($itemObj);
                $subTotal += ($original_price * $item->qty);
            }

            $pedido->setSubTotal($subTotal);

            return $pedido;
        } catch (Throwable $e) {
            $this->log->write("Erro ao baixar pedido do SkyHub: " . $e->getMessage());
            throw $e;
        }
    }


    public function addProduct($jsonSend)
    {
        $retorno = $this->callAPI($this->API_DOMAIN . '/products/', 'POST', $jsonSend, $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function updateProduct($mktID, $jsonSend)
    {
        $retorno = $this->callAPI($this->API_DOMAIN . '/products/' . $mktID, 'PUT', $jsonSend, $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function delVariation($varSku)
    {
        $retorno = $this->callAPI($this->API_DOMAIN . '/variations/' . $varSku, 'DELETE', null, $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function updateVariation($varSku, $jsonSend)
    {
        $retorno = $this->callAPI($this->API_DOMAIN . '/variations/' . $varSku, 'PUT', $jsonSend, $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function getAttributes()
    {
        $retorno = $this->callAPI($this->API_DOMAIN . '/attribute/', 'GET', null, $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function createAttribute($jsonSend)
    {
        $retorno = $this->callAPI($this->API_DOMAIN . '/attributes/', 'POST', $jsonSend, $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function updateAttribute($attName, $jsonSend)
    {
        $retorno = $this->callAPI($this->API_DOMAIN . '/attributes/' . $attName, 'PUT', $jsonSend, $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function getProduct($mktID)
    {
        $httpcode = 0;
        $retorno = $this->callAPI($this->API_DOMAIN . '/products/' . $mktID, 'GET', null, $this->header, false, $httpcode);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function getProducts($data)
    {

        $filtro = array();

        if (!empty($data['filter_name'])) {
            $filtro[] = 'filters[name]=' . $data['filter_name'];
        }

        if (!empty($data['filter_sku'])) {
            $filtro[] = 'filters[sku]=' . $data['filter_sku'];
        }

        if (!empty($data['filter_status'])) {
            $filtro[] = 'filters[status]=' . $data['filter_status'];
        }

        if (!empty($data['filter_stock_to'])) {
            $filtro[] = 'filters[qty_to]=' . $data['filter_stock_to'];
        }

        if (!empty($data['filter_stock_from'])) {
            $filtro[] = 'filters[qty_from]=' . $data['filter_stock_from'];
        }

        if (!empty($data['page'])) {
            $filtro[] = 'page=' . $data['page'];
        }

        if (!empty($data['limit'])) {
            $filtro[] = 'per_page=' . $data['limit'];
        }

        $filtro = ($filtro) ? '?' . implode('&', $filtro) : '';

        $retorno = $this->callAPI($this->API_DOMAIN . '/products/' . $filtro, 'GET', null, $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }


    public function getMktUrl($marketId)
    {
        $httpCode = false;
        $retorno = $this->callAPI($this->API_DOMAIN . '/urls/products/' . $marketId, 'GET', false, $this->header, false, $httpCode, Type_DadosSend::TpDados_Json);

        if (($retorno)) {
            return $retorno;
        } else {
            $retorno['erro'] = $this->error;
            return $retorno;
        }
    }


    public function getMktQuestions($data = array())
    {
        $filtro = array();

        if (!empty($data['filter_name'])) {
            $filtro[] = 'filters[status]=' . $data['filter_status'];
        }

        $filtro = ($filtro) ? '?' . implode('&', $filtro) : '';

        $retorno = $this->callAPI($this->API_DOMAIN . '/questions' . $filtro, 'GET', null, $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            $retorno['erro'] = $this->error;
            return $retorno;
        }
    }


    public function addPlp($orderID)
    {
        $jsonSend = '{"order_remote_codes": ["' . $orderID . '"]}';

        $retorno = $this->callAPI($this->API_DOMAIN . '/shipments/b2w', 'POST', $jsonSend, $this->header);

        if (($retorno)) {
            // o skyhub retorna o id da PLP inserida no meio de uma mensagem...
            return filter_var($retorno->message, FILTER_SANITIZE_NUMBER_INT);
        } else {
            return false;
        }
    }

    public function getPlpByOrder($orderID)
    {
        $retorno = $this->callAPI($this->API_DOMAIN . '/shipments/b2w?delivery_id=' . $orderID, 'GET', '', $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function getPlpPDF($plpID)
    {
        $header = array(
            'X-User-Email: ' . $this->config->get('skyhub_email'),
            'x-Api-Key: ' . $this->config->get('skyhub_api_key'),
            'x-accountmanager-key: ' . $this->config->get('skyhub_account_manager_key'),
            'Accept: application/pdf'
        );

        $retorno = $this->callAPI($this->API_DOMAIN . '/shipments/b2w/view?plp_id=' . $plpID, 'GET', '', $header,false,$httpcode,Type_DadosSend::TpDados_Identificar, true);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function getOrderAvaliableToPlp()
    {
        $retorno = $this->callAPI($this->API_DOMAIN . '/shipments/b2w/to_group', 'GET', '', $this->header);

        if (($retorno)) {
            return $retorno;
        } else {
            return false;
        }
    }

    public function getEtiquetaPlpID($orderID)
    {
        $plp = $this->getPlpByOrder($orderID);

        if (empty($plp->plp[0])){
            $plpID = $this->addPlp($orderID);
        } else {
            $plpID = $plp->plp[0]->id;
        }

        return $plpID;
    }

    public function splitEtiqueta($mktOrderId){

      $mktOrderId = substr($mktOrderId, strpos($mktOrderId, '-')+1, strlen($mktOrderId));

      $plpEtiqueta = $this->getEtiquetaPlpID($mktOrderId);

      if(!$plpEtiqueta){
        throw new exception("Etiqueta indisponível");
      }

      $dataEtiqueta = $this->getPlpPDF($plpEtiqueta);

      if(!$dataEtiqueta){
        throw new exception("Erro ao gerar etiqueta indisponível");
      }

      $pathEtiqueta = $this->pathEtiqueta.$mktOrderId.'.pdf';
      $this->ftrgeralregistry->setEtiquetaPdf($pathEtiqueta, $dataEtiqueta);

      if(file_exists($pathEtiqueta)) {

        $this->load->dmodel('tool/etiqueta');
        $link = $this->dmodel_tool_etiqueta->split($pathEtiqueta);

        if(!$link){
          throw new exception("Link's das etiquetas indisponíveis");
        }

        return $link;

      }else{
        throw new exception('Erro ao salvar etiqueta no servidor');
      }

    }

    public function createAccountB2w($dataAccount){

      //dados especificos para criar conta
      $dataToken = array(
        "client_id" => "futura-sistemas",
        "client_secret" => "435585af8f200cf6927a22c8edee51ab",
        "grant_type" =>  "password",
        "provision_key" => "lV2DPH5GTElM0zZBZn2ohEMEmsqc4oXR",
        "authenticated_userid" => "futura-sistemas",
        "scope" => "account"
      );

      $header = array(
        'Content-Type: application/json'
      );

      $token = $this->callAPI($this->API_DOMAIN.'/b2w_partner/authorizer/oauth2/token', 'POST', $dataToken, $header, false, $httpcode, Type_DadosSend::TpDados_Json);

      if($token){
        $created = $this->callAPI($this->API_DOMAIN.'/b2w/signup?access_token='.$token->access_token, 'POST', $dataAccount, $header, false, $httpcode, Type_DadosSend::TpDados_Json);
        if($created){
          return true;
        }else{
          return false;
        }
      }else{
        return false;
      }

    }

    public function productActions($data){

      $jwt = $this->getJwt();
      $header = array(
        'Content-Type: application/json',
        'Authorization: Bearer '.$jwt->token
      );

      $retorno = $this->callAPI($this->API_DOMAIN.'/rehub/product_actions', 'POST', $data, $header, false, $httpcode, Type_DadosSend::TpDados_Json);

      if ($retorno) {
        return $retorno;
      } else {
        return false;
      }

    }

    public function getJwt(){

      $data = array(
        'user_email' => $this->config->get('skyhub_email'),
        'api_key' => $this->config->get('skyhub_api_key')
      );

      $retorno = $this->callAPI($this->API_DOMAIN.'/auth', 'POST', $data , $this->header, false, $httpcode, Type_DadosSend::TpDados_Json);

      if ($retorno) {
        return $retorno;
      } else {
        return false;
      }

    }

    public function getEtiquetaPDF($orderID)
    {
        $header = array(
            'X-User-Email: ' . $this->config->get('skyhub_email'),
            'x-Api-Key: ' . $this->config->get('skyhub_api_key'),
            'x-accountmanager-key: ' . $this->config->get('skyhub_account_manager_key'),
            'Accept: application/pdf'
        );

        $retorno = $this->callAPI($this->API_DOMAIN . '/orders/' . $orderID . '/shipment_labels', 'GET', '', $header,false,$httpcode,Type_DadosSend::TpDados_Identificar, true);

        if (($retorno) && ($this->httpcode == 200)) {
            return $retorno;
        } else {
            return false;
        }
    }

}