<?php

class ModelShippingKangu extends Model{

    function getArrayProductsKangu($array_products)
    {
        $products = array();
        foreach ($array_products as $array_product){
            $product = array(
                    'peso'          => $array_product['weight'],
                    'altura'        => $array_product['height'],
                    'largura'       => $array_product['width'],
                    'comprimento'   => $array_product['length'],
                    'tipo'          => 'C',
                    'produto'       => $array_product['name'],
                    'valor'         => $array_product['price'],
                    'quantidade'    => $array_product['quantity']);
            array_push($products,$product);
        }

        return $products;
    }

    function addTrakingCode($trakingCode){
      if($trakingCode != ''){
        $sql = '';
      }
    }

    function postCollectionRequest($order_id,$referencia,$order_info,$array_products,$customerinfo){
      $this->load->type('tipofuturaserver');
      $this->load->model('setting/setting');

      $settings = $this->model_setting_setting->getSetting('kangu');
      $config   = $this->model_setting_setting->getSetting('config');

      if ($order_info['status_futuraserver'] == Type_PedidoStatus::TpPSt_Faturado) {
        $this->load->dmodel('notafiscal/notafiscal');
        $resultNfe = $this->dmodel_notafiscal_notafiscal->getOrderNfe($order_id);
        if ($resultNfe) {
          $chave = $resultNfe['chave_acesso'];
          $numero = $resultNfe['numero_nfe'];
          $serie   = $resultNfe['serie'];
        }
      }

        $pedido = [
          'tipo'      => 'D',
          'numeroCli' => $order_id,
        ];

      $pedido = isset($chave) ?  array_merge($pedido,['chave' => $chave])  : $pedido;
      $pedido = isset($numero) ? array_merge($pedido,['numero'=> $numero]) : $pedido;
      $pedido = isset($serie) ?  array_merge($pedido,['serie' => $serie])  : $pedido;


        $data = array(
            'pedido' => $pedido,

            'origem'        => 'Futura Sistemas',
            'remetente'     => array(
                'nome'      => $config['config_name'],
                'cnpjCpf'   => $config['config_cnpj'],
                'endereco'  => array(
                    'logradouro'    => $settings['kangu_address'],
                    'numero'        => $settings['kangu_number'],
                    'complemento'   => isset($settings['kangu_complement'])?  $settings['kangu_complement'] : '',
                    'bairro'        => $settings['kangu_district'],
                    'cep'           => $settings['kangu_postcode'],
                    'cidade'        => $settings['kangu_city'],
                    'uf'            => $settings['kangu_ufOrigem'],),
                'contato'   => $settings['kangu_contact'],
                'email'     => $settings['kangu_contactEmail'],
                'telefone'  => $settings['kangu_phone'],),
            'destinatario' => array(
                'nome' => $customerinfo['firstname'],
                'cnpjCpf' => $customerinfo['cpf'] == '' ? $customerinfo['cnpj'] : $customerinfo['cpf'],
                'endereco' => array(
                    'logradouro' => $order_info['shipping_address_1'],
                    'numero' => $order_info['shipping_numero'],
                    'complemento' => $order_info['shipping_complemento'],
                    'bairro' => $order_info['shipping_address_2'],
                    'cep' => $order_info['shipping_postcode'],
                    'cidade' => $order_info['shipping_city'],
                    'uf' => $order_info['shipping_zone_code'],),
                'contato' => $customerinfo['firstname'],
                'email' => $customerinfo['email'],
                'telefone' => $customerinfo['telephone'],
                'celular' => $customerinfo['celular'],),
            'produtos' => $this->getArrayProductsKangu($array_products),
            'servicos' => array('P','R'),
            'referencia' => $referencia
        );

        return $this->setTrakingCode($order_id,$this->kangu->postCollectionRequest(json_encode($data)));;
    }

    function setTrakingCode($order_id,$data){
      $this->load->dmodel('tracking/tracking');
      $this->load->type('tipocomum');

      if($data->error->codigo == ''){
          $trakingCode = $data->codigo;

          $sql ="UPDATE ". DB_PREFIX ."order_shipping SET tracking_code = '{$trakingCode}'
              WHERE order_id = {$order_id}";

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

          $dataTracking = array(
            'order_id' => $order_id,
            'shipping_code' => 'kangu',
            'tracking_code' => $trakingCode,
            'tracking_complete' => Type_Status::Tp_Desabilitado
          );
        $now = new DateTime($this->db->dataAtual(), new DateTimeZone('America/Sao_Paulo'));

        $this->dmodel_tracking_tracking->addTrackingEcommerce($dataTracking);

        $lastId = $this->db->getLastId();

        $tracking = [];
        array_push($tracking, array(
          'order_tracking_id' => $lastId,
          'order_id' => $order_id,
          'evento' => [
              array('tipo'      => 0,
              'status'    => 0,
              'data'      => $now->format("Y-m-d"),
              'hora'      => $now->format("H:i:s"),
              'descricao' => 'Aguardando Postagem',
              'history'   => '',
              'finally'	=> '')
          ],
        ));
        array_push($tracking,$now->format("Y-m-d H:i:s"));

        $this->dmodel_tracking_tracking->addTrackingEcommerceEvent($tracking, 0);
      }

      return $data;
    }

}
?>