<?php
require_once('tracking.php');

class KanguTracking {

    private $tipo      = 'L'   ;
    private $resultado = 'T'   ;
    private $idioma    = '101' ;
    private $eventos   = [];

  public function autentication($data = array()){
    return true;
  }

	protected $statusKangu = array(
		'_tracking_status_entregue'     => array('E' => 1, 'I' => 1, 'R' => 1),
		'_tracking_status_saiu_entrega' => array('C' => 0)
	);

	protected $statusKanguFinal = array(
		'_tracking_status_entregue' => array('E' => [1,23], 'I' => [1,23], 'R' => [1,23])
	);

    public function __construct($obj){
      $this->kangu = $obj;
    }

    public function getObjectTracking($object){
      try{
        $results = [];
        $objeto = [];

        foreach ($object as $key => $value){
          $data = $this->kangu->buscaEventos($value);

          if( $data->error->mensagem != ''){
            array_push($objeto, (object) array(
              'numero'    => $value,
              'erro'     => $data->error->mensagem)
            );
          }else{

            $event = [];
            foreach ($data->historico as $hist){
              array_push($event, (object) array(
                'tipo'=> $hist->acao,
                'status' => $hist->acao == 'E'? 1 : 0,
                'data' => $hist->data,
                'hora' => substr($hist->dataHora,11),
                'descricao' => $hist->observacao,
                'local' => '',
                'codigo' => '',
                'cidade' => '',
                'uf' => ''
              ));
            }

            array_push($objeto, (object) array(
              'numero'    => $value,
              'sigla'     => '',
              'nome'      => '',
              'categoria' => '',
              'evento'    => $event,)
            );
          }

        }

        if(is_object($results) && isset($results->return->objeto->erro)){
          $error = $results->return->objeto->erro.': '.$results->return->objeto->numero;
          throw new Exception($error);
        }

        $this->eventos = (object) array_merge(array('versao'=> '2.0','qtd' => count($object), 'objeto'=> $objeto));

      }catch (Exception $e){
          throw $e;
      }

    }


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

        $eventData	= array();
        if(is_object($this->eventos) && property_exists($this->eventos,'objeto')){
          $eventData = array_map(function($array) use (&$data){
            if(!isset($array->erro)){
              return array(
                'order_tracking_id' => (in_array(trim($array->numero), $data['tracking_code'])) ? array_search(trim($array->numero), $data['tracking_code']) : false,
                'order_id' => (in_array(trim($array->numero), $data['order_id'])) ? array_search(trim($array->numero), $data['order_id']) : false,
                'evento' => array_map(function($event){
                  return array(
                    'tipo'      => $event->tipo,
                    'status'    => $event->status,
                    'data'      => $event->data,
                    'hora'      => $event->hora,
                    'descricao' => $event->descricao,
                    'history'   => $this->getHistory(['tipo' => $event->tipo, 'status'=> $event->status]),
                    'finally'	=> $this->getFinally(['tipo' => $event->tipo, 'status'=> $event->status])
                  );
                }, $array->evento)
              );
            }else{
              return false;
            }
          }, $this->eventos->objeto);
        }elseif(is_object($this->eventos) && property_exists($this->eventos,'evento')){
          $eventData[0] = array(
            'order_tracking_id' => (in_array(trim($this->eventos->numero), $data['tracking_code'])) ? array_search(trim($this->eventos->numero), $data['tracking_code']) : false,
            'order_id' => (in_array(trim($this->eventos->numero), $data['order_id'])) ? array_search(trim($this->eventos->numero), $data['order_id']) : false,
            'evento' => array_map(function($event){
              return array(
                'tipo'      => $event->tipo,
                'status'    => $event->status,
                'data'      => $event->data,
                'hora'      => $event->hora,
                'descricao' => $event->descricao,
                'history'    => $this->getHistory(['tipo' => $event->tipo, 'status'=> $event->status]),
                'finally'    => $this->getFinally(['tipo' => $event->tipo, 'status'=> $event->status])
              );
            }, $this->eventos->evento)
          );
        }
        return $eventData;

    }


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

		foreach($this->statusKangu as $key => $statusKangu){
			if(array_key_exists($data['tipo'], $statusKangu) && in_array($data['status'], $statusKangu)){
				return true;
			}
		}

		return false ;
	}

	public function getFinally($data = array()){
		$retorno = false;
		foreach($this->statusKanguFinal as $key => $statusFinal){
			if(array_key_exists($data['tipo'], $statusFinal)){
				$retorno = array_map(function ($array) use (&$data){
					return in_array($data['status'], $array) ? true : false;
				}, $statusFinal);
			}
		}

		return $retorno ;
	}

}