<?php

final class DModelMercadolivreMeliMensagem extends Model
{

  public function setMessageOrder($order_id, $orderStatusId)
  {

    if ($this->config->get('mercadolivre_automatic_message_status')) {
      $this->load->dmodel('mercadolivre/melipedido');
      $this->load->dmodel('notafiscal/notafiscal');
      $this->load->dmodel('checkout/order');

      $order_info = $this->dmodel_checkout_order->getOrder($order_id);

      if ($order_info) {

        $find    = array();
        $replace = array();
        $msgNota = false;

        if ($orderStatusId == $this->dmodel_mercadolivre_melipedido->getOCStatus(Type_MercadoLivreStatus::Tp_ProductReadyToShip)) {
          $melienvio = $this->mercadolivre->getShipments($order_info['meli_shipping_id']);
          if ($melienvio) {
              $find    = array_push($find, Type_MercadoLivreTags::Tp_TagCod);
              $replace = array_push($replace, $melienvio->tracking_number);
          }
        }

        $this->load->dmodel('notafiscal/notafiscal');
        $this->load->dmodel('wsceo/pedido/wsprocessosvenda');
        $processosVenda = $this->dmodel_wsceo_pedido_wsprocessosvenda->getProcessosVenda();
        if (($this->config->get('processo_venda_status') == Type_DsimDnao::Tp_Sim) && is_array($processosVenda) ) {

          $this->load->dmodel('proccess/order_to_situation');

          $maxProccess = $this->dmodel_proccess_order_to_situation->getProccessByStatus($orderStatusId, $this->config->get('processo_venda_id'));
          $ordem = false;
          if (sizeof($maxProccess) > 0) {
            $ordem = $maxProccess['ordem'];
          }
          $lastProccessVenda = $this->dmodel_proccess_order_to_situation->getLastOrderProcess($order_id, $this->config->get('processo_venda_id'), $ordem);

          if (
            (count($lastProccessVenda) > 0) &&
            ($lastProccessVenda['status'] == Type_ContrlProcVenda::TpStContrlProcVenda_LiberacaoFaturamento) &&
            ($lastProccessVenda['proccess_status'] == Type_StatusProcVenda::TpStProcVend_Finalizado)
          ) {

            $result = $this->dmodel_notafiscal_notafiscal->getOrderNfe($order_id);
            if (($result) && (!is_null($result['link_danfe'])) && (!is_null($result['link_xml']))) {
                $find    = array_merge($find, [Type_MercadoLivreTags::Tp_TagChaveAcesso, Type_MercadoLivreTags::Tp_TagLinkXml, Type_MercadoLivreTags::Tp_TagLinkDanfe]);
                $replace = array_merge($replace,['Chave Acesso: ' . $result['chave_acesso'], 'Link do XML: ' . $result['link_xml'], 'Link da danfe: ' . $result['link_danfe']] );
            } else {
              throw new Exception('Erro ao enviar email, nota fiscal não foi gerada para o pedido do mercado livre: ' . $order_id);
            }

          }

        } else {

          if (ftr_geral::isIsset($this->config->get('select_order_status_nota_fiscal_emitida_id')) && $this->config->get('select_order_status_nota_fiscal_emitida_id') != '') {
            if ($this->config->get('select_order_status_nota_fiscal_emitida_id') == $orderStatusId) {
              $result = $this->dmodel_notafiscal_notafiscal->getOrderNfe($order_id);
              if (($result) && ($result['status_futuraserver'] == Type_PedidoStatus::TpPSt_Faturado) && (!is_null($result['link_danfe'])) && (!is_null($result['link_xml']))) {
                  $find    = array_merge($find, [Type_MercadoLivreTags::Tp_TagChaveAcesso, Type_MercadoLivreTags::Tp_TagLinkXml, Type_MercadoLivreTags::Tp_TagLinkDanfe]);
                  $replace = array_merge($replace,['Chave Acesso: ' . $result['chave_acesso'], 'Link do XML: ' . $result['link_xml'], 'Link da danfe: ' . $result['link_danfe']] );
              } else {
                throw new Exception('Erro ao enviar email, nota fiscal não foi gerada para o pedido do mercado livre: ' . $order_id);
              }
            }
          }

        }


        $mensagemStatus = ftr_geral::isIsset($this->config->get('mercadolivre_automatic_message')) ? array_filter($this->config->get('mercadolivre_automatic_message')) : false;
        if ($mensagemStatus) {
          $mensagem = (isset($mensagemStatus[$orderStatusId])) ? $mensagemStatus[$orderStatusId] : false;
          if ($mensagem) {
            if ($msgNota) {
              $mensagem .= PHP_EOL . $msgNota;
            }

            $this->load->dmodel('account/customer');
            $customer_info = $this->dmodel_account_customer->getCustomer($order_info['customer_id']);

            $arrayMessage = array(
              'from' => ['user_id' => $this->mercadolivre->getAppUser(), 'email' => $order_info['email']],
              'to' => ['user_id' => $customer_info['mkt_buyer_id']],
              'text' => trim(str_replace($find, $replace, $mensagem))
            );

            $meli_pack_id = ($order_info['meli_pack_id']!='') ? $order_info['meli_pack_id'] : $order_info['mktOrderId'];

            try{
              $this->mercadolivre->sendMenssagePackId($arrayMessage, $meli_pack_id);
            }catch (Exception $e) {
              throw $e;
            }

          }
        }

      }

    }
  }

  public function sendMessageAccount($cliente_id, $order_id)
  {


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

    $customer_info = $this->dmodel_account_customer->getCustomer($cliente_id);
    $order_info = $this->dmodel_checkout_order->getOrder($order_id);

    if ($order_info) {

      $this->load->type('tipocomum');
      $this->load->helper('ftr_geral');
      $this->language->load('mail/mlcustomer');

      $sql = "SELECT * FROM " . DB_PREFIX . "design_layout_personalizado WHERE tipo_layout = " . Type_LayoutPersonalizado::Tp_LayoutEmailMercadoLivre;
      $query = $this->db->query($sql);
      $mail_info = $query->rows;

      $find = array();

      foreach (Type_LayoutPersonalizadoVarButton::getEnumList() as $key => $value) {
        $find[] = '{{ ' . $key . ' }}';
      }

      $token = ftr_geral::cripty($customer_info['customer_id'], $this->config->get('config_encryption'));

      $replace = array(
        'cli_nome' => $customer_info['firstname'],
        'cli_email' => $customer_info['email'],
        'loj_nome' => $this->config->get('config_name'),
        'loj_link' => $this->urlloja->link('common/home', '', 'SSL'),
        'loj_login_link' => $this->urlloja->link('account/register', '&cmltoken=' . $token . '&id=' . $customer_info['customer_id'], 'SSL'),
        'ped_id' => $order_id
      );

      $format = $mail_info[0]['conteudo_layout'];
      $mensagem = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', $format));
      $mensagem = trim(substr(str_replace($find, $replace, $mensagem), 0, 350)); //limita nos 350 pois o Mercado livre aceita no maximo essa quantidade

      $arrayMessage = array(
        'from' => ['user_id' => $this->mercadolivre->getAppUser(), 'email' => $customer_info['email']],
        'to' => ['user_id' => $customer_info['mkt_buyer_id']],
        'text' => $mensagem
      );

      $meli_pack_id = ($order_info['meli_pack_id']!='') ? $order_info['meli_pack_id'] : $order_info['mktOrderId'];

      try{
        $this->mercadolivre->sendMenssagePackId($arrayMessage, $meli_pack_id);
      }catch (Exception $e) {
        throw $e;
      }

    }

  }


  protected function getToMessage($data = array())
  {

    $to = array();
    $items = $this->mercadolivre->getShipmentsItems($data['shipmentsid']);

    foreach ($items as $key => $item) {
      $to[] = array(
        'user_id' => $data['user_id'],
        'resource' => 'orders',
        'resource_id' => $item->order_id,
        'site_id' => 'MLB'
      );
    }

    return $to;
  }

  protected function getPropery($dataobj, $dataname, $defaultvalue = '')
  {
    return (is_object($dataobj) && property_exists($dataobj, $dataname)) ? $dataobj->$dataname : $defaultvalue;
  }


}