<?php

class EmailPedidoStatus extends Pedido
{

  private $registry;

  public function __construct($registry)
  {
    $this->registry = $registry;
    parent::__construct($registry);
    parent::getConfigMail();
  }

  public function sendTask($typeemail, $order_id, $attribute_value)
  {

    try {

      $this->getInfoOrderStatus($order_id, $attribute_value);
      $this->mail->setTo($this->to);//$order_info['email']
      $this->mail->setSender($this->sender);//$order_info['store_name']
      $this->mail->setSubject(html_entity_decode($this->subject, ENT_QUOTES, 'UTF-8'));
      $this->mail->setHtml(parent::getTemplate($typeemail));
      $this->mail->setText(html_entity_decode($this->text, ENT_QUOTES, 'UTF-8'));
      $this->mail->send(true);
    } catch (Exception $e) {
      throw $e;
    }

  }

  public function getInfoOrderStatus($order_id, $attribute_value)
  {
    parent::getOrderInfo($order_id);

    if ($this->order_info) {

      $attribute_value = json_decode($attribute_value);

      $this->to = $this->order_info['email'];
      $this->sender = $this->order_info['store_name'];

      if ($this->config->get('listapresente_status')) {
        $this->load->model('listapresente/listapresente');
        //Alterar o status dos itens quando o pedido for pago.
        if ($this->config->get('futuralistapresente_cod_status_completo') == $attribute_value->order_status_id) {
          $itens = $this->model_listapresente_listapresente->GetItensPedido($order_id);
          if ($itens) {
            $this->model_listapresente_listapresente->updateStatusItemPedido($itens, $attribute_value->order_status_id);
          }
        }
      }

      $language = new Language($this->order_info['language_directory']);
      $language->load($this->order_info['language_filename']);
      $language->load('mail/order');

      $this->subject = sprintf($language->get('text_subject'), $this->order_info['store_name'], $order_id);

      /* Linguagem */
      $this->template->data['text_order'] = $language->get('text_order');
      $this->template->data['text_date_added'] = $language->get('text_date_added');
      $this->template->data['text_order_status'] = $language->get('text_order_status');
      $this->template->data['text_link'] = $language->get('text_link');
      $this->template->data['text_store_rating'] = $language->get('text_store_rating');
      $this->template->data['text_comment'] = $language->get('text_comment');
      $this->template->data['text_footer'] = $language->get('text_footer');
      $this->template->data['text_product'] = $language->get('text_new_product');
      $this->template->data['text_model'] = $language->get('text_new_model');
      $this->template->data['text_quantity'] = $language->get('text_new_quantity');
      $this->template->data['text_price'] = $language->get('text_new_price');
      $this->template->data['text_total'] = $language->get('text_new_total');
      $this->template->data['text_gift'] = $language->get('text_gift');
      $this->template->data['logo'] = $this->urlloja->link('', '', 'SSL', false) . 'image/' . $this->config->get('config_logo');
      $this->template->data['link_website'] = $this->order_info['store_url'];
      $this->template->data['store_url_contact'] = $this->order_info['store_url'] . 'index.php?route=information/contact';
      $this->template->data['store_name'] = $this->order_info['store_name'];
      $this->template->data['header_background_color'] = $this->config->get('wg24_header_bg_color');
      $this->template->data['btn_background_color'] = $this->config->get('wg24_btn_1bg_col');
      $this->template->data['btn_text_color'] = $this->config->get('wg24_btn_text_col');
      $this->template->data['order_id'] = $order_id;
      $this->template->data['date_added'] = date($language->get('date_format_short'), strtotime($this->order_info['date_added']));

      $tracking = ftr_geral::removeString($this->order_info['shipping_code'], '.');
      $this->template->data['shipping_code'] = ucfirst($tracking);
      $this->template->data['shipping_code_link'] = Type_TrackingLinkEmail::getNickFromValue($tracking);


      $order_status_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_status WHERE order_status_id = '" . (int)$attribute_value->order_status_id . "' AND language_id = '" . (int)$this->order_info['language_id'] . "'");

      if ($order_status_query->num_rows) {
        $this->template->data['name'] = $order_status_query->row['name'];
      }

      if ($this->order_info['customer_id']) {
        $this->template->data['store_url'] = html_entity_decode($this->order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_id, ENT_QUOTES, 'UTF-8');
      }

      if(isset($attribute_value->order_history_id)){
        $order_history_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_history WHERE order_history_id = '" . (int)$attribute_value->order_history_id . "'");
        $comment_history = preg_replace('/<[^>]*>[^<]*<[^>]*>/', '', html_entity_decode($order_history_query->row['comment'], ENT_QUOTES, 'UTF-8'));
      }else{
        $comment_history = '';
      }

      if ($this->order_info['comment'] != '' || $comment_history != '') {
        $comment_order = strip_tags(html_entity_decode($this->order_info['comment'], ENT_QUOTES, 'UTF-8'));
        $this->template->data['comment'] = ($comment_order!='') ? $comment_order.PHP_EOL.$comment_history : $comment_history;
      } else {
        $this->template->data['comment'] = false;
      }

      $this->template->data['link_pagamento'] = $this->getLinkPagamento($order_id, $this->order_info['payment_code'], $attribute_value);

      // Products
      $this->load->dmodel('catalog/product');
      $this->load->dmodel('account/order');
      $this->template->data['productlist'] = array();

      $order_product_query = $this->dmodel_account_order->getOrderProducts($order_id);

      $controle_kit = array(); //Como id do kit está no item, controla para não gerar duplicidades;
      foreach ($order_product_query as $product) {
        if (in_array($product['product_kit_id'],$controle_kit)) {continue;}

        if(isset($product['lista_escolar_id']) && $product['lista_escolar_id']>0){
          $tipoLista = Type_ProductCart::Tp_ListaEscolar;
          $id_lista  = $product['lista_escolar_id'];
          $this->template->data['productlist'][$tipoLista][$id_lista]['isListaEscolar'] = true;
          $this->template->data['productlist'][$tipoLista][$id_lista]['descricao'] = $product['lista_escolar_descricao'];
        }else{
          $tipoLista = Type_ProductCart::Tp_Default;
          $id_lista  = 0;
          $this->template->data['productlist'][$tipoLista][$id_lista]['isListaEscolar'] = false;
        }

        //Brinde
        $produto_brinde = $this->dmodel_account_order->getProductOrderBrinde($product['product_id'],$order_id);
        if ($produto_brinde) {
          $produto_brinde['product_name'] = $produto_brinde['name'];
          $produto_brinde['href'] = $this->url->link('product/product', 'product_id=' . $produto_brinde['product_id']);
          $product['price'] += $produto_brinde['price_order'];
          $product['total'] += $produto_brinde['total_order'];
        }
        //Brinde

        //KIT
        $produto_kit = false;
        if ($product['product_kit_id']) { 
          $produto_kit = $this->dmodel_account_order->getOrdertKit($order_id,$product['product_kit_id']);
          $controle_kit[] = $product['product_kit_id'];
        }
        //KIT            

        $grades = array();
        if ($this->config->get('futuragrade_status')) {
          $results = $this->dmodel_catalog_product->getDadosGridProdutoId((int)$product['product_id']);

          foreach ($results as $result) {
            $grades[] = array(
              'color' => (isset($result['color'])) ? $result['color_template'] .' : '. $result['color'] : '',
              'size' => (isset($result['size'])) ? $result['size_template'] .' : '. $result['size'] : '',
              'specification' => (isset($result['specification'])) ? $result['specification_template'] .' : '. $result['specification'] : ''
            );
          }
        }

        if ($produto_kit){
          $this->template->data['productlist'][$tipoLista][$id_lista]['products'][] = $produto_kit;  
        }else{        
          $this->template->data['productlist'][$tipoLista][$id_lista]['products'][] = array(
            'name' => $product['name'],
            'model' => $product['model'],
            'quantity' => $product['quantity'],
            'price' => $this->currency->format($product['price'], $this->order_info['currency_code'], $this->order_info['currency_value']),
            'total' => $this->currency->format($product['total'], $this->order_info['currency_code'], $this->order_info['currency_value']),
            'grades' => $grades,
            'brinde' => $produto_brinde,
            'itens_kit' => false
          );
        }
      }

      // Order Totals
      $order_total_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_total` WHERE order_id = '" . (int)$order_id . "' ORDER BY sort_order ASC");
      $this->template->data['totals'] = $order_total_query->rows;

      $this->load->dmodel('localisation/order_status');
      $msg = $this->dmodel_localisation_order_status->getOrderStatusMessage((int)$attribute_value->order_status_id);

      if (isset($msg[0]['message']) && $msg[0]['message']) {
        $this->template->data['order_status_message'] = $msg[0]['message'];
      }

      if ($attribute_value->order_status_id == $this->config->get('config_complete_status_id')) {
        $this->template->data['url_store_rating'] = $this->urlloja->link('account/store_rating', '', 'SSL');
      }

      // Chama a função order_history e exibi apenas a informaçõe sem html
      $this->load->controller('account/order');
      $ctrAccountOrder = new ControllerAccountOrder($this->registry);
      $this->template->data['history_process'] = $ctrAccountOrder->historyProccess(['email' => true, 'order_id' => $order_id]);

      $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($attribute_value->order_status_id, $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);

        $process_status = $this->dmodel_proccess_order_to_situation->getOrderStatusByProcessType(Type_ContrlProcVenda::TpStContrlProcVenda_LiberacaoFaturamento, Type_StatusProcVenda::TpStProcVend_Finalizado);

        if (
          (count($lastProccessVenda) > 0) &&
          ($lastProccessVenda['status'] == Type_ContrlProcVenda::TpStContrlProcVenda_LiberacaoFaturamento) &&
          ($lastProccessVenda['proccess_status'] == Type_StatusProcVenda::TpStProcVend_Finalizado) &&
          in_array($attribute_value->order_status_id, $process_status)
        ) {

          $result = $this->dmodel_notafiscal_notafiscal->getOrderNfe($order_id);
          if (($result) && (!is_null($result['link_danfe'])) && (!is_null($result['link_xml']))) {
            $this->template->data['send_nfe_info'] = true;
            $this->template->data['chave_acesso'] = $result['chave_acesso'];
            $this->template->data['link_danfe'] = $result['link_danfe'];
            $this->template->data['link_xml'] = str_replace(' ', '%20', $result['link_xml']);
          } else {
            throw new Exception('Erro ao enviar email, nota fiscal não foi gerada para o pedido: ' . $order_id);
          }

        }

        $process_status_rastreio = $this->dmodel_proccess_order_to_situation->getOrderStatusByProcessType(Type_ContrlProcVenda::TpStContrlProcVenda_LiberacaoConferencia, Type_StatusProcVenda::TpStProcVend_Finalizado);

        if (
          (count($lastProccessVenda) > 0) &&
          (
            ($lastProccessVenda['status'] == Type_ContrlProcVenda::TpStContrlProcVenda_LiberacaoConferencia) ||
            (in_array($lastProccessVenda['status'],[Type_ContrlProcVenda::TpStContrlProcVenda_LiberacaoConferencia, Type_ContrlProcVenda::TpStContrlProcVenda_LiberacaoBaixa, Type_ContrlProcVenda::TpStContrlProcVenda_LiberacaoFaturamento,
              Type_ContrlProcVenda::TpStContrlProcVenda_LiberacaoControleEntrega, Type_ContrlProcVenda::TpStContrlProcVenda_PedidoCancelado, Type_ContrlProcVenda::TpStContrlProcVenda_ConferenciaEntrega]))
          ) &&
          ($lastProccessVenda['proccess_status'] == Type_StatusProcVenda::TpStProcVend_Finalizado) &&
          in_array($attribute_value->order_status_id, $process_status_rastreio)
        ) {

          if(isset($this->order_info['tracking_code']) && ($this->order_info['tracking_code'])){
            $this->template->data['tracking_codes'] = $this->order_info['tracking_code'];
          }

        }

      } 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') == $attribute_value->order_status_id) {
            $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']))) {
              $this->template->data['send_nfe_info'] = true;
              $this->template->data['chave_acesso'] = $result['chave_acesso'];
              $this->template->data['link_danfe'] = $result['link_danfe'];
              $this->template->data['link_xml'] = $result['link_xml'];
            } else {
              throw new Exception('Erro ao enviar email, nota fiscal não foi gerada para o pedido: ' . $order_id);
            }
          }
        }

        if(isset($this->order_info['tracking_code']) && ($this->order_info['tracking_code'])){
          $this->template->data['tracking_codes'] = $this->order_info['tracking_code'];
        }

      }
      $this->template->data['tracking_codes'] = $this->order_info['tracking_code'];
    }

  }

  public function getLinkPagamento($order_id, $payment_method, $attribute_value)
  {

    $arrayPosterior = array(
      'cielo_api_credito',
      'itaushopline'
    );


    if (in_array($payment_method, $arrayPosterior)) {

      if ($this->config->get('cielo_api_credito_status') && ($payment_method == 'cielo_api_credito') && ($attribute_value->order_status_id == $this->config->get('cielo_api_order_status_posteriorlink_id'))) {
        $tolken_id = ftr_geral::cripty($order_id, $this->config->get('config_encryption'));
        return $this->config->get('config_linkproducao_ssl') . 'index.php?route=payment/cielo_api_credito_pos&pedido_id=' . $order_id . '&tolken_id=' . $tolken_id;
      }

      if ($this->config->get('itaushopline_status') && ($payment_method == 'itaushopline') && ($attribute_value->order_status_id == $this->config->get('itaushopline_order_status_posteriorlink_id'))) {
        $tolken_id = ftr_geral::cripty($order_id, $this->config->get('config_encryption'));
        return $this->config->get('config_linkproducao_ssl') . 'index.php?route=payment/itaushopline_pos&pedido_id=' . $order_id . '&tolken_id=' . $tolken_id;
      }

    }

    return false;

  }


}