<?php
class ControllerModuleSkyhubError extends Controller {

  private $error = array();

  public function index(){
    $this->load->helper('ftr_geral');

    $language = $this->load->language('module/skyhub');;
    $this->data = array_merge($this->data, $language);

    $this->document->setTitle($language['heading_title_error']);

    $this->document->addScript(array(
      'view/javascript/skyhub-error.js'
    ));

    $this->data['token'] = $this->session->data['token'];
    $this->data['type'] = $this->request->get['type'];

    $this->data['breadcrumbs'] = array();

    $this->data['breadcrumbs'][] = array(
      'text'      => $language['text_home'],
      'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      'separator' => false
    );

    $this->data['breadcrumbs'][] = array(
      'text'      => $language['heading_title'],
      'href'      => $this->url->link('module/skyhub/error', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
      'separator' => ' :: '
    );

    $this->data['breadcrumbs'][] = array(
      'text'      => $language['heading_title_error'],
      'href'      => $this->url->link('module/skyhub/error', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
      'separator' => ' :: '
    );

    $this->data['type_marketplace'] = Type_MarketPlace::Tp_SkyHub;

    $this->data['skyhub_error_type'] = TypeSkyHubError::getEnumList();

    if (isset($this->error['warning'])) {
      $this->data['error_warning'] = $this->error['warning'];
    } else {
      $this->data['error_warning'] = '';
    }

    $this->children = array(
      'common/header',
      'common/footer'
    );

    $this->response->setOutput($this->render('module/skyhub/error'));

  }


  public function getLinkUrl($remove=array()){
    $url = '';

    foreach ($remove as $key => $value) {
        unset($this->request->get[$value]);
    }

    if (isset($this->request->get['type'])) {
      $url .= '&type=' . $this->request->get['type'];
    }

    return $url;
  }

  public function getErrors(){
    $this->load->dmodel('marketplace/mktproduto');
    $this->load->dmodel('marketplace/mktpedido');
    $this->load->dmodel('marketplace/mktprodutoskyhub');

    $type_error = $this->request->get['type_error'];

    $skyhub = new SkyHubUtils($this->registry);
    $json = $skyhub->getErrors($type_error);

    $arrayJson = json_decode(json_encode($json), true);

    usort($arrayJson['data'],
      function ($a, $b) {
        // pega a data do primeiro erro apenas, porque os outros erros tem que ser mostrados juntos
        $dateA = new DateTime($a['categories'][0]['errors'][0]['last_occurrence']);
        $dateB = new DateTime($b['categories'][0]['errors'][0]['last_occurrence']);

        if ($dateB == $dateA) return 0 ;
        return ($dateB > $dateA) ? -1 : 1 ;

      }
    );

    // TESTE - Vou deixar esse código aqui pra ficar mais facil de testar e visualizar como vem os dados
//    $arrayJson = json_decode('{
//    "errors_qty": 50,
//    "data": [
//        {
//            "entity_id": "P157278",
//            "categories": [
//                {
//                    "errors": [
//                        {
//                            "message": "Erro TEste",
//                            "last_occurrence": "2020-03-07T13:09:56-03:00",
//                            "error_code": "unknown"
//                        }
//                    ],
//                    "error_category_code": "link_b2w_products"
//                }
//            ]
//        }
//    ]
//    }', true);

    foreach ($arrayJson['data'] as $key => $value){
      $entity_id = $value['entity_id'];
      switch ($type_error) {
        case TypeSkyHubError::Tp_Products:
          $product_info = $this->dmodel_marketplace_mktprodutoskyhub->getProduct(substr($entity_id, 1, strlen($entity_id)-1));
          if ($product_info) {
            $product_id = $product_info['product_id'];
            $link = $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&option=update&product_id=' . $product_id, 'SSL');
          }
          break;
        case TypeSkyHubError::Tp_Orders:
          $order_info = $this->dmodel_marketplace_mktpedido->getMktOrder($entity_id, Type_MarketPlace::Tp_SkyHub);
          if ($order_info) {
            $link = $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $order_info['order_id'], 'SSL');
          };
          break;
      }
      $arrayJson['data'][$key]['link'] = $link ?? false;
    }

    $this->response->setOutputJson($arrayJson);
  }
}