<?php
$loader = $this->registry->get('load');
$loader->dmodel('marketplace/mktpedido');

final class DModelskyhubskypedido extends DModelmarketplacemktpedido
{

    public function getNfesSky()
    {
        $this->load->type('tipofuturaserver');
        $this->load->type('tipomarketplace');


        $sql = "SELECT nfe.chave_acesso, mp.mktOrderId, o.order_id FROM oc_order o"
            . " inner join oc_order_nfe nfe on (o.order_id = nfe.order_id)"
            . " inner join oc_marketplace_order mp on (mp.order_id = o.order_id)"
            . " WHERE o.status_futuraserver = '" . Type_PedidoStatus::TpPSt_Faturado . "'"
            . " and (o.id_futura is not null)"
            . " and (o.mkt_integracao_tipo = " . Type_MarketPlace::Tp_SkyHub . ")"
            . " and (date(o.date_added) BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE())"
            . " and (nfe.sky_nf_enviado = " . Type_Enviado::Tp_NaoEnviado . ")"
            . " and (o.mkt_order_status = " . TypeSkyHubOrder_Status::Tp_payment_received . ")";

        if (!empty($data['order_id'])) {
            $sql .= ' and o.order_id = ' . $data['order_id'];
        }

        $result = $this->db->query($sql);

        if ($result->rows) {
            return $result->rows;
        } else {
            return false;
        }
    }

    public function sendStatus($order_id, $order_status_id, $order_history_id, $reenvio = false)
    {
        $this->load->dmodel('skyhub/skysetting');
        $this->load->dmodel('checkout/order');
        $this->load->dmodel('notafiscal/notafiscal');
        $this->load->dmodel('wsceo/pedido/wsnotafiscal');

        $key = $this->dmodel_skyhub_skysetting->getKeyFromOrderStatus($order_status_id);

        if (!$key) {
            return true;//Se não tiver configuração para esse status no skyhub, então sai fora, não tem nada a ser feito...
        }

        $key = substr($key['key'], 20, strlen($key['key']) + 20);
        $order = $this->dmodel_checkout_order->getOrder($order_id);
        $order_item = $this->dmodel_checkout_order->getOrderItems($order_id);

        switch ($key) {
            case 'delivered':
                $retorno = $this->setPedidoEntregue($order['mktOrderId']);
                $status_type = TypeSkyHubOrder_Type::Tp_delivered;
                break;

            case 'nfe':

                /*
                 * quando a b2w liberar a entrega direct para produção ativar esse parametro na base para que ele
                 * começe a funcionar sem a necessidade de atualizar os clientes
                 */
                if ($order['chave_acesso'] == null || trim($order['chave_acesso']) == '') {
                    return false;
                }

                $retorno = $this->setEnvioNFEDirect(
                    $order_id,
                    $order['mktOrderId'],
                    $order['xml'],
                    $order['quantidade_volumes'],
                    $order['data_hora_emissao']
                );

                $status_type = TypeSkyHubOrder_Type::Tp_invoiced;
                break;

            case 'shipped':
                $retorno = $this->setOrderShipped($order_id, $order['mktOrderId'], $order, $order_item);
                $status_type = TypeSkyHubOrder_Type::Tp_shipped;
                break;

            case 'canceled':
                $retorno = $this->setCancelOrder($order['mktOrderId']);
                $status_type = TypeSkyHubOrder_Type::Tp_canceled;
                break;

            case 'shipment_exception':
                $retorno = $this->setOrderShipmentException($order_id, $order['mktOrderId']);
                $status_type = TypeSkyHubOrder_Type::Tp_shipment_exception;
                break;

            case 'confirmed_stock':
            case 'canceled_stock':
                $confirmed = ($key == 'confirmed_stock') ? true : false;
                $retorno = $this->setOrderConfirmedStock($order['mktOrderId'], $confirmed);
                $status_type = TypeSkyHubOrder_Type::getConstFromNickValue($key);
                break;

            case 'processing_store':
                $retorno = $this->setOrderProcessingStore($order['mktOrderId']);
                $status_type = TypeSkyHubOrder_Type::Tp_processing_store;
                break;

            default :
                return true; //Para não tentar enviar status que são apensa recebidos ou status que não são do skyhub
        }

        $this->saveMarketplaceLog();

        if (isset($retorno['erro'])) {
            $mensagemErro = $retorno['erro'];
            $tipoSituacao = TypeSkyHub_Situacao::Tp_SituacaoErro;
        } else {
            $tipoSituacao = TypeSkyHub_Situacao::Tp_SituacaoNotificado;
            $mensagemErro = '';
        }

        $dataStatus = array(
            "order_id" => $order_id,
            "order_history_id" => $order_history_id,
            "mktStatus" => $status_type,
            "tipo_origem" => TypeSkyHub_Origem::Tp_Envio,
            "tipo_situacao" => $tipoSituacao,
            "msg_erro" => $mensagemErro
        );

        if ($reenvio) {
            $this->updateMktOrderStatus($dataStatus);
        } else if (!$this->dmodel_marketplace_mktpedido->isVinculedMktOrderStatus($order_history_id)) {
            $this->addMktOrderStatus($dataStatus);
        }

        return true;

    }

    private function setOrderProcessingStore($mktOrderId)
    {
        $skyhub = new Skyhub($this->registry);
        return $skyhub->setOrderProcessingStore($mktOrderId);
    }


    private function setOrderConfirmedStock($mktOrderId, $confirmed)
    {
        $skyhub = new Skyhub($this->registry);
        return $skyhub->setOrderConfirmedStock($mktOrderId, $confirmed);
    }

    public function setCancelOrder($mktOrderId)
    {
        return $this->marketplace->setCancelOrder(Type_MarketPlace::Tp_SkyHub, $mktOrderId);
    }

    public function setPedidoEntregue($mktOrderId)
    {
        return $this->marketplace->setPedidoEntregue(Type_MarketPlace::Tp_SkyHub, $mktOrderId);
    }

    public function setEnvioNFEDirect($order_id, $mktOrderId, $xml_arquivo, $qtd_volumes, $data_hora_emissao)
    {
        $this->load->type('tipocomum');
        $retorno = $this->marketplace->setEnviarNFEDirect(Type_MarketPlace::Tp_SkyHub, $mktOrderId, $xml_arquivo, $qtd_volumes, $data_hora_emissao);

        if (!isset($retorno['erro'])) {
            $sql = ' update oc_order_nfe set sky_nf_enviado = ' . Type_Enviado::Tp_Enviado
                . ' where order_id = ?';
            $this->db->executeSql($sql, [$order_id]);
        }
        return $retorno;
    }

    private function setOrderShipmentException($order_id, $mktOrderId)
    {
        $this->load->dmodel('localisation/order_status');

        $status_msg = $this->dmodel_localisation_order_status->getOrderStatusMessage($this->config->get('skyhub_order_status_shipment_exception'));

        if (count($status_msg) == 1 && isset($status_msg['message'])) {
            $status_msg = $status_msg['message'];
        } else {
            $status_msg = 'Problema com o envio';
        }

        $ship_exc = array();
        $ship_exc['shipment_exception'] = array(
            'occurrence_date' => date(DATE_ATOM),
            'observation' => $status_msg
        );

        return $this->marketplace->setOrderShipmentException(Type_MarketPlace::Tp_SkyHub, $mktOrderId, $ship_exc);
    }

    private function setOrderShipped($order_id, $mktOrderId, $order, $order_item)
    {
        $jsonSend = array();
        $jsonShipment = array();
        $jsonSend['status'] = "order_shipped";

        $jsonShipment['code'] = $order_id;

        $jsonItems = array();

        foreach ($order_item as $items) {
            $jsonItems[] = array(
                'sku' => ($items['mkt_variation_id'] !== null && trim($items['mkt_variation_id']) !== '') ? $items['mkt_variation_id'] : $items['marketId'],
                'qty' => $items['quantity']
            );
        }
        $trakings = '';
        if ($order['tracking_code']) {
            foreach ($order['tracking_code'] as $traking_code) {
                $trakings .= $traking_code['tracking_code'] . ',';
            }
            $trakings = rtrim($trakings, ',');
        }

        $jsonTrack = array(
            'code' => $trakings,
            'carrier' => $order['shipping_code'],
            'method' => $order['shipping_method'],
        );

        $jsonShipment['items'] = $jsonItems;
        $jsonShipment['track'] = $jsonTrack;
        $jsonSend['shipment'] = $jsonShipment;


        return $this->marketplace->setPedidoEnvio(Type_MarketPlace::Tp_SkyHub, $mktOrderId, $jsonSend);
    }

    public function addOrderSkyHub($pedido, $data = array(), $syncManual = false)
    {
        $status = $data['status'] ?? $pedido->getParam('status');
        $status_type = $data['status_type'] ?? $pedido->getParam('status_type');

        try {

            if (($pedido->getTotal() <= 0) || ($pedido->getSubTotal() <= 0)) {
                throw new exception('Há pedido(s) com valores zerados');
            }

            $this->load->dmodel('marketplace/mktproduto');
            $this->load->dmodel('marketplace/mktprodutoskyhub');
            $this->load->dmodel('catalog/product');
            $this->load->dmodel('checkout/order');

            $adFieldsOrder = array();
            $adFieldsOrderValue = array();
            $adFieldsOrder[] = 'mkt_order_status';
            $adFieldsOrderValue[] = $this->db->escape(TypeSkyHubOrder_Status::getConstFromNickValue($status));
            $adjustmentKit = false;
            $mktCommisions = array();


            $dadosProd = array();
            $mkt_comission_total = 0;
            foreach ($pedido->getItens() as $product) {
                $mkt_comission = 0;
                $oc_mktproduct = $this->dmodel_marketplace_mktproduto->getMarketPlaceFromMarketId($product->getMktId(), Type_MarketPlace::Tp_SkyHub);

                $product_id = 0;
                $variation_id = '';
                $productDB = null;

                if (($product->getMktVariationId()) && ($oc_mktproduct['tipo_produto'] == Type_ProdutoMkt::Tp_MktProd_Grade)) {
                    //é vinculado com produto grade!! verificando então qual é a variação correta que está ligada ao produto...
                    $variation_id = $product->getMktVariationId();
                    $productItemGrid = $this->dmodel_marketplace_mktproduto->getProductFromVariation($variation_id, Type_MarketPlace::Tp_SkyHub);

                    if (isset($productItemGrid['product_id'])) {
                        $product_id = $productItemGrid['product_id'];
                    }

                } elseif ((!$product->getMktVariationId()) && ($oc_mktproduct) && ($oc_mktproduct['tipo_produto'] == Type_ProdutoMkt::Tp_MktProd_Normal)) {
                    $productDB = $this->dmodel_marketplace_mktprodutoskyhub->getProduct($oc_mktproduct['product_key_id']);
                    if ($productDB) {
                        $product_id = $productDB['product_id'];
                    }

                }
                if ((is_null($productDB)) && ($product_id != 0)) {
                    $productDB = $this->dmodel_marketplace_mktprodutoskyhub->getProduct($product_id);
                }

                if ($this->config->get('skyhub_comission_status')) {
                    $skyhub_comission = $this->config->get('skyhub_comission');
                    if (isset($skyhub_comission[$pedido->getMkTipo()])) {
                        $mkt_comission = (( (float)$skyhub_comission[$pedido->getMkTipo()] * (float)$pedido->getTotal()) / 100);
                        $mkt_comission_total += $mkt_comission;
                    }
                }

                if (!$productDB) {
                    $dadosProd[] = array(
                        'product_id' => $product_id,
                        'name' => $product->getProductName(),
                        'model' => '',
                        'quantity' => $product->getQuantity(),
                        'price' => $product->getPrice(),
                        'total' => $product->getQuantity() * $product->getPrice(),
                        'marketId' => $product->getMktId(),
                        'mkt_comission' => $mkt_comission,
                        'mkt_variation_id' => $variation_id
                    );
                } else {

                    $brinde = $this->getMktBrinde($product_id);
                    if ($brinde) {
                        if ($productDB['product_kit_id']) {
                            $brinde['product_kit_id'] = $productDB['product_kit_id'];
                            $brinde['product_kit_qtd'] = $product->getQuantity();
                        }
                        $dadosProd[] = $brinde;
                        $product->setPrice($product->getPrice() - 0.01);
                    }

                    if ($productDB['product_kit_id']) {
                        $adjustmentKit = true;
                        $itens_kit = $this->dmodel_catalog_product->getProductKitItens($productDB['product_kit_id'], $product->getPrice());

                        $mktCommisions[] = array( /* Para que seja rateado posteriormente, pois para isso preciso do pedido/pedido item */
                            "product_kit_id" => $productDB['product_kit_id'],
                            "mkt_comission" => $mkt_comission
                        );

                        foreach ($itens_kit as $item_kit) {
                            $dadosProd[] = array(
                                'product_id' => $item_kit['product_id'],
                                'name' => $item_kit['descricao'],
                                'model' => $item_kit['model'],
                                'quantity' => $item_kit['quantidade'] * $product->getQuantity(),
                                'price' => $item_kit['price'],
                                'total' => ($item_kit['price'] * $item_kit['quantidade']) * $product->getQuantity(),
                                'marketId' => "",
                                'mkt_comission' => 0,
                                'mkt_variation_id' => "",
                                'product_kit_id' => $productDB['product_kit_id'],
                                'product_kit_qtd' => $product->getQuantity(),
                                'id_futura' => $item_kit['product_id_futura'],
                                'discount' => ($item_kit['acerto']) < 0 ? ($item_kit['acerto'] * -1) * $product->getQuantity() : 0,
                                'increase' => ($item_kit['acerto']) > 0 ? $item_kit['acerto'] * $product->getQuantity() : 0
                            );
                        }
                    } else {
                        $dadosProd[] = array(
                            'product_id' => $product_id,
                            'name' => $productDB['name'],
                            'model' => $productDB['model'],
                            'quantity' => $product->getQuantity(),
                            'price' => $product->getPrice(),
                            'total' => $product->getQuantity() * $product->getPrice(),
                            'marketId' => $product->getMktId(),
                            'mkt_comission' => $mkt_comission,
                            'mkt_variation_id' => $variation_id
                        );
                    }
                }

            }
            $total_data = array();

            if ($adjustmentKit) {
                //Ajuste dos descontos e totais dos produtos caso possua KIT
                $this->language->load('total/descontoacrescimokit');
                $fullSubTotal = array_sum(array_column($dadosProd, 'total'));
                $adjustmentKitValue = $pedido->getSubTotal() - $fullSubTotal;
                $pedido->setSubTotal($fullSubTotal);
                if ($adjustmentKitValue >= 0) {
                    $text_kit = $this->language->get('acrescimo_kit');
                    $pedido->setAcresKit($adjustmentKitValue);
                } else {
                    $text_kit = $this->language->get('desconto_kit');
                    $pedido->setDiscountKit($adjustmentKitValue * -1);
                }

                $text_kit = ($adjustmentKitValue > 0) ? $this->language->get('acrescimo_kit') : $this->language->get('desconto_kit');
                $total_data[] = array(
                    'code' => 'descontoacrescimokit',
                    'title' => $text_kit,
                    'text' => $this->currency->format($adjustmentKitValue, $this->currency->getCode()),
                    'value' => (float)$adjustmentKitValue,
                    'sort_order' => $this->config->get('sub_total_sort_order') + 1//Exibir o desconto do Kit logo em seguida do subtotal
                );
            }

            $order_id = $this->addOrder($pedido, $mkt_comission_total, TypeSkyhub_Module::Tp_Payment, TypeSkyhub_Module::Tp_Shipping, $adFieldsOrder, $adFieldsOrderValue);

            foreach ($dadosProd as $prod) {
                if (isset($prod['product_kit_id']) && !isset($prod['brinde_product_id'])) {
                    $extraFields = array("product_kit_id", "product_kit_qtd", "desconto_valor", "acrescimo_valor");
                    $extraValues = array($prod["product_kit_id"], $prod["product_kit_qtd"], $prod["discount"], $prod["increase"]);
                    $this->addOrderProduct($order_id, $prod, $extraFields, $extraValues);
                } elseif (isset($prod['brinde_product_id'])) {
                    $extraFields = array("brinde_product_id", "brinde_tipo");
                    $extraValues = array($prod["brinde_product_id"], $prod["brinde_tipo"]);
                    if (isset($prod['product_kit_id'])) {
                        $extraFields = array_merge($extraFields, ["product_kit_id", "product_kit_qtd"]);
                        $extraValues = array_merge($extraValues, [$prod["product_kit_id"], $prod["product_kit_qtd"]]);
                    }
                    $this->addOrderProduct($order_id, $prod, $extraFields, $extraValues);
                } else {
                    $this->addOrderProduct($order_id, $prod);
                }
            }

            if ($mktCommisions) {
                $orderItens = $this->dmodel_checkout_order->getOrderItems($order_id);
                foreach ($mktCommisions as $comission) {
                    $this->dmodel_checkout_order->updateApportionment($order_id, $comission['mkt_comission'], Type_Apportionment::MktCommission, true, $comission['product_kit_id'], $orderItens);
                }
            }

            $this->addMktOrder(array(
                'order_id' => (int)$order_id,
                'mktOrderId' => $pedido->getMktId(),
                'order_product_id' => null,
                'tipo_integracao' => Type_MarketPlace::Tp_SkyHub,
                'shipping_code' => null,
                'origem_captura' => $syncManual ? Type_MktOrigemCaptura::Manual : Type_MktOrigemCaptura::Automatica
            ));

            $this->language->load('total/sub_total');
            $total_data[] = array(
                'code' => 'sub_total',
                'title' => $this->language->get('heading_title'),
                'text' => $this->currency->format($pedido->getSubTotal(), $this->currency->getCode()),
                'value' => (float)$pedido->getSubTotal(),
                'sort_order' => $this->config->get('sub_total_sort_order')
            );

            $shipping_cost = $pedido->getShippingCost();

            $method_title = $pedido->getShippingName();

            if ($shipping_cost <= 0) {
                $method_title .= ' (Envio Grátis)';
            }

            $total_data[] = array(
                'code' => 'shipping',
                'title' => $method_title,
                'text' => $this->currency->format((float)$shipping_cost, $this->currency->getCode()),
                'value' => (float)$shipping_cost,
                'sort_order' => $this->config->get('shipping_sort_order')
            );

            $this->language->load('total/total');
            $total_data[] = array(
                'code' => 'total',
                'title' => $this->language->get('heading_title'),
                'text' => $this->currency->format((float)$pedido->getTotal(), $this->currency->getCode()),
                'value' => (float)$pedido->getTotal(),
                'sort_order' => $this->config->get('total_sort_order')
            );

            $orderModule = 0;
            if ($pedido->getDiscount() > 0) {
                $total_data[] = array(
                    'code' => 'descontoskyhub',
                    'title' => 'Descontos',
                    'text' => $this->currency->format($pedido->getDiscount() * -1),
                    'value' => $pedido->getDiscount() * -1,
                    'sort_order' => $this->config->get('sub_total_sort_order') + 1
                );
                $orderModule = $this->config->get('sub_total_sort_order') + 1;
            }

            if ($pedido->getAcres() > 0) {
                $total_data[] = array(
                    'code' => 'acrescimoskyhub',
                    'title' => 'Acrescimos',
                    'text' => $this->currency->format($pedido->getAcres()),
                    'value' => $pedido->getAcres(),
                    'sort_order' => $orderModule + 1
                );
            }

            $this->dmodel_checkout_order->updateApportionmentAll($order_id,
                array(
                    Type_Apportionment::Shipping => $shipping_cost,
                    Type_Apportionment::Discount => $pedido->getDiscount(),
                    Type_Apportionment::Increase => $pedido->getAcres()
                )
            );
            $this->addOrderTotal($order_id, $total_data);

            $commentHistory = 'SkyHub (Venda #' . $pedido->getMktId() . ')';
            $order_status_id = $this->getSkyStatus($status);

            $order_history_id = $this->updateOrderHistory($order_id, $order_status_id, $commentHistory);
            $dataStatus = array(
                "order_id" => $order_id,
                "order_history_id" => $order_history_id,
                "mktStatus" => $status_type,
                "tipo_origem" => TypeSkyHub_Origem::Tp_Recebimento,
                "tipo_situacao" => TypeSkyHub_Situacao::Tp_SituacaoRecebido,
                "msg_erro" => ''
            );
            $this->addMktOrderStatus($dataStatus);

            return $order_id;

        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    public function getAddressNotConfirmed($customer_id, $billing_id, $billing_address)
    {
        $sql = "select address_id from " . DB_PREFIX . "address
            where customer_id = " . $this->db->escape($customer_id) . "
            and lower(firstname) = 'não'
            and postcode = '00000000'
            ";

        $billing_address ? $sql .= " and address_id = " . $billing_id : $sql .= " and address_id != " . $billing_id;

        $retorno = $this->db->query($sql);

        if ($retorno->num_rows > 0) {
            return $retorno->row['address_id'];
        } else {
            return false;
        }
    }

    public function updateOrderSkyHub($orderData, $mktOrderData)
    {
        try {
            if ($orderData['nao_confirmado']) {
                if ((mb_strtolower($mktOrderData->getBuyer()->getFirstName(), 'UTF-8') != 'não') &&
                    (($mktOrderData->getBuyer()->getSendAddress()->getPostCode() != '00000000') &&
                     (mb_strtolower($mktOrderData->getBuyer()->getSendAddress()->getLogradouro(), 'UTF-8') != 'não informado'))) {

                    $this->load->dmodel('account/customer');

                    $orderAddress = $this->getOrderAddress($mktOrderData);
                    $customerInfo = $this->getOrderCustomer($mktOrderData, $orderAddress);
                    $customerData = $this->getOrderCustomerData($mktOrderData, $orderAddress);

                    // Atualizado dados do cliente
                    if (mb_strtolower($customerInfo['firstname']) == 'não') {
                        $this->dmodel_account_customer->updateOCCustomerMktPlace($customerInfo['customer_id'], $customerData);
                    }

                    // Atualiza o endereço de faturamento
                    $billing_address_id = $this->getAddressNotConfirmed($customerInfo['customer_id'], $customerInfo['address_id'], true);
                    if ($billing_address_id) {
                        $this->dmodel_account_customer->updateOCCustomerAddressMktPlace($billing_address_id, $customerData['adresses']['billing'], $customerData);
                    }

                    // Atualiza o endereço de entrega
                    $shipping_address_id = $this->getAddressNotConfirmed($customerInfo['customer_id'], $customerInfo['address_id'], false);
                    if ($shipping_address_id) {
                        $this->dmodel_account_customer->updateOCCustomerAddressMktPlace($shipping_address_id, $customerData['adresses']['shipping'], $customerData);
                    }

                    // Atualiza pedido
                    $this->updateOrder($orderData, $mktOrderData);
                }
            }

            $this->updateOrderStatusSkyHub($orderData['order_id'], $mktOrderData->getParam('status'), $mktOrderData->getParam('status_type'));
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    public function updateOrderStatusSkyHub($order_id, $mktStatus, $mktStatusType)
    {
        try {
            // Status
            $status_id = $this->getSkyStatus($mktStatus);
            $order_history_id = $this->updateOrderHistory($order_id, $status_id, '');
            // Atualizar no tipo também...
            $this->updateTipoStatusPedido($order_id, TypeSkyHubOrder_Status::getConstFromNickValue($mktStatus));
            $dataStatus = array(
                "order_id" => $order_id,
                "order_history_id" => $order_history_id,
                "mktStatus" => $mktStatusType,
                "tipo_origem" => TypeSkyHub_Origem::Tp_Recebimento,
                "tipo_situacao" => TypeSkyHub_Situacao::Tp_SituacaoRecebido,
                "msg_erro" => ''
            );
            $this->addMktOrderStatus($dataStatus);

        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    public function getSkyStatus($order_status)
    {
        switch (strtolower($order_status)) {
            case 'waiting_payment';/* Assumimos que o status waiting_payment é o mesmo do novo pedido, para não gerar status desnecessários*/
            case 'book_product' :
                return $this->config->get('skyhub_order_status_new');
                break;

            case 'payment_received':
                return $this->config->get('skyhub_order_status_aproved');
                break;

            case 'order_canceled':
                return $this->config->get('skyhub_order_status_canceled');
                break;

            case 'order_shipped':
                return $this->config->get('skyhub_order_status_shipped');
                break;

            case 'order_invoiced':
                return $this->config->get('skyhub_order_status_nfe');
                break;

            case 'complete':
                return $this->config->get('skyhub_order_status_delivered');
                break;

            case 'shipment_exception':
                return $this->config->get('skyhub_order_status_shipment_exception');
                break;

            case 'payment_overdue':
                return $this->config->get('skyhub_order_status_canceled');
                break;

            case 'confirm_stock':
                return $this->config->get('skyhub_order_status_confirm_stock');
                break;

            case 'confirmed_stock':
                return $this->config->get('skyhub_order_status_confirmed_stock');
                break;

            case 'canceled_stock':
                return $this->config->get('skyhub_order_status_canceled_stock');
                break;

            case 'processing_store':
                return $this->config->get('skyhub_order_status_processing_store');
                break;
        }
    }

    public function proccessOrder($tempoLimite = false)
    {
        $this->load->dmodel('marketplace/mktpedido');
        $this->load->dmodel('marketplace/marketplace');
        $skyhub = new SkyHubUtils($this->registry);

        $retorno = array("fail_order" => 0);

        // Processa a fila interna
        $this->db->query("DELETE FROM `" . DB_PREFIX . "marketplace_api_call` WHERE tipo_integracao = " . Type_MarketPlace::Tp_SkyHub . " AND done = 1");
        $skyhubOrdersQueue = $this->db->query("SELECT * FROM `" . DB_PREFIX . "marketplace_api_call` WHERE tipo_integracao = " . Type_MarketPlace::Tp_SkyHub . " AND callType='order' and `done` = '0' limit 100 ")->rows;

        if ($skyhubOrdersQueue) {
            $skyhubOrdersQueueGroup = array_chunk($skyhubOrdersQueue, 50);
            foreach ($skyhubOrdersQueueGroup as $key => $skyhubOrdersQueue) {
                foreach ($skyhubOrdersQueue as $skyhubOrder) {

                    $orderId = $skyhubOrder['callId'];

                    $orderJson = $skyhub->getOrderWs($orderId);
                    if (!$orderJson) {
                        continue;
                    }
                    $order = $skyhub->orderJsonToObject($orderJson);

                    //processa pedido
                    $this->saveSkyhubOrder($order, $retorno);
                }
                if (($tempoLimite) && (new DateTime($this->db->dataAtual()) > $tempoLimite)) {
                    break;
                }
            }
        }

        // Processa a fila do skyhub
        do {
            $order = $this->marketplace->getOrder(Type_MarketPlace::Tp_SkyHub, '');

            if (!$order) {
                break; //Não tem nenhuma venda na fila...
            } else {
                $this->saveMarketplaceLog();
                $this->dmodel_marketplace_marketplace->addAPICall(Type_MarketPlace::Tp_SkyHub, $order->getMktId(), Type_CallApi::Tp_Order);
                $this->marketplace->deleteOrderQueue(Type_MarketPlace::Tp_SkyHub, $order->getMktId());

                $this->saveSkyhubOrder($order, $retorno);
            }

            if (($tempoLimite) && (new DateTime($this->db->dataAtual()) > $tempoLimite)) {
                break;
            }

        } while ($order);

        return $retorno;

    }

    public function saveSkyhubOrder($order, &$retorno)
    {
        try {
            $this->saveMarketplaceLog();
            $this->db->startTransaction();

            $order_info = $this->getMktOrder($order->getMktId(), Type_MarketPlace::Tp_SkyHub);

            if ($order_info) {
                $lastStatus = $this->dmodel_marketplace_mktpedido->getLastMktOrderStatus($order_info['order_id']);
                switch ($order->getParam('status')) {
                    /*Alguns status pelo que vimos, serve exatamente para a mesma coisa, vi com Matheus e trataremos conforme identificarmos, já deixei assim
                    para os proximos, caso necessario.*/
                    case 'waiting_payment':
                        $order->setParam('status', TypeSkyHubOrder_Status::getNickFromConstValue(TypeSkyHubOrder_Status::Tp_book_product));
                        $order->setParam('status_type', TypeSkyHubOrder_Type::Tp_new);
                        break;
                    case 'order_shipped':
                        $order->setParam('status', TypeSkyHubOrder_Status::getNickFromConstValue(TypeSkyHubOrder_Status::Tp_order_shipped));
                        $order->setParam('status_type', TypeSkyHubOrder_Type::Tp_shipped);
                        if ($lastStatus['mktStatus'] != $order->getParam('status_type')) {
                            $this->load->dmodel('tracking/tracking');
                            if (strtolower($order->getParam('shipments_carrier')) == Type_Tracking::Tp_Correios) {
                                $dataTracking = array(
                                    'order_id' => $order_info['order_id'],
                                    'shipping_code' => $order->getShippingName(),
                                    'tracking_code' => $order->getParam('shipments_code'),
                                    'tracking_complete' => Type_Status::Tp_Desabilitado
                                );

                                $this->dmodel_tracking_tracking->addTrackingEcommerce($dataTracking);
                            }
                            $dataOrder = array(
                                'order_id' => $order_info['order_id'],
                                'tracking_code' => $order->getParam('shipments_code'),
                            );

                            $this->dmodel_tracking_tracking->addTrackingOrderShipping($dataOrder);
                        }
                        break;
                }

                if ($lastStatus['mktStatus'] != $order->getParam('status_type')) {
                    $this->updateOrderSkyHub($order_info, $order);
                }
            } else {
                if ($order->getParam('status_type') <> TypeSkyHubOrder_Type::Tp_new) {
                    /* Quando o pedido já teve o status alterado de inicio, por exemplo, cliente pagou com cartão e já foi aprovado no momento da sincronia
                    o status que vêm do skyhub já é o status final, não lançando os status corretamente, por isso eu forço aqui na inserção à vir com o status novo
                    assim quando ele entrar na atualização, ira lançar os demais status.
                    Ps. nessa situação haverá dois registros na queue com o mesmo status(tanto o novo quanto o pago, estarao como pago),
                    logo, o segundo registro ira descer lançando o status correto
                    Ficando o primeido do add como NEW, e o segundo como Pago */
                    $data = array(
                        'status' => TypeSkyHubOrder_Status::getNickFromConstValue(TypeSkyHubOrder_Status::Tp_book_product),
                        'status_type' => TypeSkyHubOrder_Type::Tp_new
                    );
                    $order_id = $this->addOrderSkyHub($order, $data);
                    $this->updateOrderStatusSkyHub($order_id, $order->getParam('status'), $order->getParam('status_type'));
                } else {
                    $this->addOrderSkyHub($order);
                }
            }

            $this->db->query("UPDATE `" . DB_PREFIX . "marketplace_api_call` SET done = '1' WHERE tipo_integracao = " . Type_MarketPlace::Tp_SkyHub . " AND callId = '" . $order->getMktId() . "' and callType='" . Type_CallApi::Tp_Order . "';");
            $this->db->commit();

        } catch (Exception $e) {
            $retorno['fail_order']++;
            $this->db->rollback();
        }
    }

    public function inStatusSkyhub($order_history_id)
    {
        $retorno = $this->db->query(
            "SELECT * FROM oc_order_history oh WHERE oh.order_status_id IN(
        SELECT `value` FROM oc_setting
        WHERE `group` = 'skyhub' AND `key` like 'skyhub_order_status%')
        AND  oh.order_history_id = $order_history_id")->rows;

        if (count($retorno) > 0) {
            return true;
        } else {
            return false;
        }

    }

}