<?php

class Pedido extends Email
{

  public $order_info = false;
  public $order_itens_info = false;
  public $lista = false;
  public $order_status;

  public function __construct($registry)
  {
    parent::__construct($registry);
  }

  public function getOrderInfo($order_id)
  {
    $this->load->type('tipocomum');
    $this->load->type('tipofuturaserver');
    $this->load->dmodel('checkout/order');

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

  public function getOrderItemInfo($order_id){
    $this->load->dmodel('checkout/order');
    $this->order_itens_info = $this->dmodel_checkout_order->getOrderItems($order_id);
  }

  public function getInfosTemplateOrder($order_id)
  {

    $this->getOrderInfo($order_id);

    if ($this->order_info) {

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

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

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

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

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

      // HTML Mail
      $this->template->data['title'] = sprintf($this->language->get('text_new_subject'), html_entity_decode($this->order_info['store_name'], ENT_QUOTES, 'UTF-8'), $order_id);
      $this->template->data['text_greeting'] = sprintf($this->language->get('text_new_greeting'), html_entity_decode($this->order_info['store_name'], ENT_QUOTES, 'UTF-8'));
      $this->template->data['text_link'] = $this->language->get('text_new_link');
      $this->template->data['text_download'] = $this->language->get('text_new_download');
      $this->template->data['text_order_detail'] = $this->language->get('text_new_order_detail');
      $this->template->data['text_instruction'] = $this->language->get('text_new_instruction');
      $this->template->data['text_thank_buy'] = $this->language->get('text_new_thank_buy');
      $this->template->data['text_order_id'] = $this->language->get('text_new_order_id');
      $this->template->data['text_date_added'] = $this->language->get('text_new_date_added');
      $this->template->data['text_payment_method'] = $this->language->get('text_new_payment_method');
      $this->template->data['text_shipping_method'] = $this->language->get('text_new_shipping_method');
      $this->template->data['text_email'] = $this->language->get('text_new_email');
      $this->template->data['text_telephone'] = $this->language->get('text_new_telephone');
      $this->template->data['text_celular'] = $this->language->get('text_new_celular');
      $this->template->data['text_ip'] = $this->language->get('text_new_ip');
      $this->template->data['text_payment_address'] = $this->language->get('text_new_payment_address');
      $this->template->data['text_shipping_address'] = $this->language->get('text_new_shipping_address');
      $this->template->data['text_pickup_address'] = $this->language->get('text_pickup_address');
      $this->template->data['text_product'] = $this->language->get('text_new_product');
      $this->template->data['text_model'] = $this->language->get('text_new_model');
      $this->template->data['text_quantity'] = $this->language->get('text_new_quantity');
      $this->template->data['text_price'] = $this->language->get('text_new_price');
      $this->template->data['text_total'] = $this->language->get('text_new_total');
      $this->template->data['text_footer'] = $this->language->get('text_new_footer');
      $this->template->data['text_gift'] = $this->language->get('text_gift');

      $this->template->data['logo'] = $this->url->link('', '', 'SSL', false) . 'image/' . $this->config->get('config_logo');
      $this->template->data['store_name'] = $this->order_info['store_name'];
      $this->template->data['store_url'] = $this->order_info['store_url'];
      $this->template->data['customer_id'] = $this->order_info['customer_id'];
      $this->template->data['link'] = $this->order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_id;
      $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($this->language->get('date_format_short'), strtotime($this->order_info['date_added']));
      $this->template->data['payment_method'] = $this->order_info['payment_method'];
      $this->template->data['shipping_method'] = $this->order_info['shipping_method'];
      $this->template->data['email'] = $this->order_info['email'];
      $this->template->data['telephone'] = $this->order_info['telephone'];
      $this->template->data['celular'] =  $this->order_info['celular'];
      $this->template->data['isfone'] = ($this->order_info['telephone'] != '') ? true : false;
      $this->template->data['iscelular'] = ($this->order_info['celular'] != '') ? true : false;
      $this->template->data['ip'] = $this->order_info['ip'];

      $this->load->dmodel('checkout/order');
      $statusPedido = $this->dmodel_checkout_order->getOrderStatus($this->order_info['order_status_id']);
      if ($statusPedido['tipo_status'] == 2) {//Status de notificação de tipo de pedido negativo
        $this->template->data['text_thank_buy'] = $this->language->get('text_new_thank_buy_negative');
      }

      $this->template->data['text_greeting'] = sprintf($this->language->get('text_new_order_status') . ' ' . $statusPedido['descricao'], html_entity_decode($this->order_info['store_name'], ENT_QUOTES, 'UTF-8'));

      if ($this->order_info['comment'] != '') {
        $this->template->data['comment'] = nl2br($this->order_info['comment']);
      } else {
        $this->template->data['comment'] = '';
      }

      if ($this->order_info['payment_address_format']) {
        $format = $this->order_info['payment_address_format'];
      } else {
        $format = '{apelido}' . "\n" . '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}, {numero}, {complemento}' . "\n" . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
      }

      $find = array(
        '{apelido}',
        '{numero}',
        '{complemento}',
        '{firstname}',
        '{lastname}',
        '{company}',
        '{address_1}',
        '{address_2}',
        '{city}',
        '{postcode}',
        '{zone}',
        '{zone_code}',
        '{country}'
      );

      $replace = array(
        'apelido' => $this->order_info['payment_apelido'],
        'numero' => $this->order_info['payment_numero'],
        'complemento' => $this->order_info['payment_complemento'],
        'firstname' => $this->order_info['payment_firstname'],
        'lastname' => $this->order_info['payment_lastname'],
        'company' => $this->order_info['payment_company'],
        'address_1' => $this->order_info['payment_address_1'],
        'address_2' => $this->order_info['payment_address_2'],
        'city' => $this->order_info['payment_city'],
        'postcode' => $this->order_info['payment_postcode'],
        'zone' => $this->order_info['payment_zone'],
        'zone_code' => $this->order_info['payment_zone_code'],
        'country' => $this->order_info['payment_country']
      );

      $this->template->data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

      if ($this->order_info['shipping_address_format']) {
        $format = $this->order_info['shipping_address_format'];
      } else {
        $format = '{apelido}' . "\n" . '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}, {numero}, {complemento}' . "\n" . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
      }

      $find = array(
        '{apelido}',
        '{numero}',
        '{complemento}',
        '{firstname}',
        '{lastname}',
        '{company}',
        '{address_1}',
        '{address_2}',
        '{city}',
        '{postcode}',
        '{zone}',
        '{zone_code}',
        '{country}'
      );

      $replace = array(
        'apelido' => $this->order_info['shipping_apelido'],
        'numero' => $this->order_info['shipping_numero'],
        'complemento' => $this->order_info['shipping_complemento'],
        'firstname' => $this->order_info['shipping_firstname'],
        'lastname' => $this->order_info['shipping_lastname'],
        'company' => $this->order_info['shipping_company'],
        'address_1' => $this->order_info['shipping_address_1'],
        'address_2' => $this->order_info['shipping_address_2'],
        'city' => $this->order_info['shipping_city'],
        'postcode' => $this->order_info['shipping_postcode'],
        'zone' => $this->order_info['shipping_zone'],
        'zone_code' => $this->order_info['shipping_zone_code'],
        'country' => $this->order_info['shipping_country']
      );

      $shipping_pickup = ftr_geral::removeString($this->order_info['shipping_code'], '.') == Type_ShippingCode::Tp_ShippingPickup;
      $kangu_pickip = ftr_geral::removeString($this->order_info['shipping_code'], '.') == Type_ShippingCode::Tp_ShippingKanguPickup;

      $this->template->data['shipping_pickup'] = $shipping_pickup;
      if ($shipping_pickup OR $kangu_pickip){
        $this->template->data['pickup_address'] = ftr_geral::getOrderAddressFormatted($this->order_info, Type_Address::Tp_Retirada);
      } else {
        $this->template->data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
      }

      // 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;}
        $option_data = array();

        $order_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$product['order_product_id'] . "'");

        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

        foreach ($order_option_query->rows as $option) {
          if ($option['type'] != 'file') {
            $value = $option['value'];
          } else {
            $value = utf8_substr($option['value'], 0, utf8_strrpos($option['value'], '.'));
          }

          $option_data[] = array(
            'name' => $option['name'],
            'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
          );
        }

        $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'],
            'option' => $option_data,
            '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_voucher_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_voucher WHERE order_id = '" . (int)$order_id . "'");
      $this->template->data['vouchers'] = array();

      foreach ($order_voucher_query->rows as $voucher) {
        $this->template->data['vouchers'][] = array(
          'description' => $voucher['description'],
          'amount' => $this->currency->format($voucher['amount'], $this->order_info['currency_code'], $this->order_info['currency_value']),
        );
      }

      $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->text = sprintf($this->language->get('text_new_greeting'), html_entity_decode($this->order_info['store_name'], ENT_QUOTES, 'UTF-8')) . "\n\n";
      $this->text .= $this->language->get('text_new_order_id') . ' ' . $order_id . "\n";
      $this->text .= $this->language->get('text_new_date_added') . ' ' . date($this->language->get('date_format_short'), strtotime($this->order_info['date_added'])) . "\n";
      $this->text .= $this->language->get('text_new_order_status') . ' ' . $this->order_status . "\n\n";

      if ($this->order_info['comment'] != '') {
        $this->text .= $this->language->get('text_new_instruction') . "\n\n";
        $this->text .= $this->order_info['comment'] . "\n\n";
      }

      // Products
      $this->text .= $this->language->get('text_new_products') . "\n";

      foreach ($order_product_query as $product) {
        $this->text .= $product['quantity'] . 'x ' . $product['name'] . ' (' . $product['model'] . ') ' . html_entity_decode($this->currency->format($product['total'], $this->order_info['currency_code'], $this->order_info['currency_value']), ENT_NOQUOTES, 'UTF-8') . "\n";

        $order_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . $product['order_product_id'] . "'");

        foreach ($order_option_query->rows as $option) {
          $this->text .= chr(9) . '-' . $option['name'] . ' ' . (utf8_strlen($option['value']) > 20 ? utf8_substr($option['value'], 0, 20) . '..' : $option['value']) . "\n";
        }
      }

      foreach ($order_voucher_query->rows as $voucher) {
        $this->text .= '1x ' . $voucher['description'] . ' ' . $this->currency->format($voucher['amount'], $this->order_info['currency_code'], $this->order_info['currency_value']);
      }

      $this->text .= "\n";

      $this->text .= $this->language->get('text_new_order_total') . "\n";

      foreach ($order_total_query->rows as $total) {
        $this->text .= $total['title'] . ': ' . html_entity_decode($total['text'], ENT_NOQUOTES, 'UTF-8') . "\n";
      }

      $this->text .= "\n";

      if ($this->order_info['customer_id']) {
        $this->text .= $this->language->get('text_new_link') . "\n";
        $this->text .= $this->order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_id . "\n\n";
      }

      // Comment
      if ($this->order_info['comment'] != '') {
        $this->text .= $this->language->get('text_new_comment') . "\n\n";
        $this->text .= $this->order_info['comment'] . "\n\n";
      }

      $this->text .= $this->language->get('text_new_footer') . "\n\n";

    }

  }

}