<?php
final class DModelTrackingTracking extends Model {

  public function addTrackingOrderShipping($data=array()){

    $sql = "INSERT INTO ".DB_PREFIX."order_shipping SET order_id = '".$this->db->escape($data['order_id'])."', tracking_code = '".$this->db->escape($data['tracking_code'])."' ";
    $this->db->query($sql);

  }

  public function addTrackingEcommerce($data=array()){

    $sql = "INSERT INTO ".DB_PREFIX."order_tracking SET order_id = '".$this->db->escape($data['order_id'])."', shipping_code = '".$this->db->escape($data['shipping_code'])."', tracking_code = '".$this->db->escape($data['tracking_code'])."', tracking_complete = '".$this->db->escape($data['tracking_complete'])."'";
    $this->db->query($sql);

  }

  public function addTrackingEcommerceEvent(array $data, int $shipping){

    $this->load->helper('ftr_geral');

    $tracking_date_att = array_pop($data);
    $insert = array();
    foreach($data as $key => $value){

      if($value == false)
        continue;

      $order = array(
        'order_tracking_id' => $value['order_tracking_id'],
        'order_id' 			    => $value['order_id'],
      );
      if(count(array_filter($order))==2){
        $insert[$order['order_tracking_id']] = array_map(function($event) use(&$order){
          $data  = ftr_geral::formatDate($event['data'], 'en').' '.$event['hora'];
          $sql = "INSERT INTO ".DB_PREFIX."order_tracking_event SET order_tracking_id = '".$this->db->escape($order['order_tracking_id'])."', order_tracking_event_code = '".$this->db->escape($event['tipo'])."', order_tracking_event_status = '".$this->db->escape($event['status'])."', order_tracking_event_date = '".$this->db->escape($data)."', order_tracking_event_desciption='".$this->db->escape($event['descricao'])."'; ";
          $array = array(
            'history'   => $event['history'],
            'descricao' => $event['descricao']
          );
          return ['sql' => $sql, 'order_id' => $order['order_id'], 'notify'=> $array, 'finally' =>$event['finally']];
        }, $value['evento']);

        $query = $this->db->query("SELECT count(order_tracking_event_id) as total from ".DB_PREFIX."order_tracking_event WHERE order_tracking_id = ".$order['order_tracking_id']);

        if($query->row['total'] > 0){
          $insert[$order['order_tracking_id']] = array_slice(array_reverse($insert[$order['order_tracking_id']]), $query->row['total']);
        }
      }
    }

    if($insert){
      foreach($insert as $key => $value){
        if(count($value)>0){
          foreach ($value as $keys => $val ) {
            $this->db->query($val['sql']);
            if(($val['finally']) && (count(array_filter($val['finally'])) > 0)) {
              $this->db->query("UPDATE ".DB_PREFIX."order_tracking SET tracking_complete = '1' WHERE order_tracking_id = ".$key);
            }
          }
          $this->db->query("UPDATE ".DB_PREFIX."order_tracking SET tracking_date_att = '".$this->db->escape($tracking_date_att)."' WHERE order_tracking_id = ".$key);
        }
      }
    }
  }

  public function getTrackingsEcommerce($data = array()){

    $this->load->helper('ftr_geral');

		$sql  = "SELECT ot.* FROM ".DB_PREFIX."order o ";
    $sql .= "INNER JOIN ".DB_PREFIX."order_tracking ot ON (o.order_id = ot.order_id) ";
    $sql .= "LEFT JOIN ".DB_PREFIX."order_tracking_event ote ON (ot.order_tracking_id = ote.order_tracking_id) ";
    $sql .= "WHERE ot.tracking_date_att is not null";

    if(isset($data['order_id']) && ($data['order_id'])){
      $sql .= ' AND ot.order_id = '.$this->db->escape($data['order_id']);
    }

    if(isset($data['shipping_code']) && ($data['shipping_code'])){
      $sql .= ' AND ot.shipping_code in ('.$data['shipping_code'].')';
    }

    if(isset($data['origem_pedido'])){
      $sql .= ' AND o.origem_pedido = '.$this->db->escape($data['origem_pedido']);
    }

    if(isset($data['date_added_betwenn'])){
      $sql .= ' AND '.$this->db->escape($data['date_added_betwenn']);
    }

    if(isset($data['tracking_complete'])){
      $sql .= ' AND ot.tracking_complete = '.$this->db->escape($data['tracking_complete']);
    }

    $sql .= ' GROUP BY ot.tracking_code ';

    $sort_data = array(
      'ot.tracking_date_att'
    );

    if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
       $sql .= ftr_geral::sqlOrderByAdd('', $data['sort']);
    }


		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
    }

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}

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

    if($results){
      $tracking_data = array();

      foreach ($results->rows as $key => $result) {
        $tracking_data[$result['order_tracking_id']] = $this->getTrackingEcommerce($result['order_tracking_id']);
      }

      return $tracking_data;
    }else{
      return false;
    }

  }

  public function getTrackingEcommerce($tracking_id){

    $sql = "SELECT * FROM ".DB_PREFIX."order_tracking ot WHERE ot.order_tracking_id = ".$tracking_id;

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

    if($results){
      return array(
        'order_tracking_id' => $results->row['order_tracking_id'],
        'order_id'          => $results->row['order_id'],
        'shipping_code'     => $results->row['shipping_code'],
        'tracking_code'     => $results->row['tracking_code'],
        'tracking_complete' => $results->row['tracking_complete'],
        'tracking_date_att' => $results->row['tracking_date_att']
      );
    }else{
      return false;
    }

  }


  public function getTrackingEventsSistema($trackingCode){

    $sql = "select fel.DATA as data, fel.HORA as hora, fel.DESCRICAO as descricao from FRETE_ETIQUETA fe
            inner join FRETE_ETIQUETA_LOG fel on (fe.ID = fel.FK_ETIQUETA)
            where fe.ETIQUETA = '".$trackingCode."'";

    return $this->wsceo->getConsultaFromSqlCache($sql);

  }

  public function verifyStatus($trackingCode){

    $this->load->helper('ftr_geral');

    $trackingCode = ftr_geral::removeString($trackingCode, '.');

     $status = array_filter(array(
      'module_status'   => $this->config->get($trackingCode.'_status'),
      'tracking_status' => $this->config->get($trackingCode.'_tracking_status'),
    ));

    if(count($status)==2){
			return true;
    }else{
      return false;
    }

  }

  public function getConfigTracking($trackingCode){

    $this->load->helper('ftr_geral');

    $trackingCode = ftr_geral::removeString($trackingCode, '.');

    return array(
      'usuario'             => $this->config->get($trackingCode.'_tracking_usuario'),
      'senha'               => $this->config->get($trackingCode.'_tracking_senha'),
      'status_postado'      => $this->config->get($trackingCode.'_tracking_status_postado'),
      'status_saiu_entrega' => $this->config->get($trackingCode.'_tracking_status_saiu_entrega'),
      'status_entregue'     => $this->config->get($trackingCode.'_tracking_status_entregue')
    );

  }

}