<?php
$loader = $this->registry->get('load');
$loader->controller('product/productDefault');

class ControllerProductCategory extends ControllerProductDefault
{

  public function index($setting = null)
  {

    $this->language->load('product/category');

    $this->data['t_result'] = $this->language->get('t_result');
    $this->data['t_results'] = $this->language->get('t_results');
    $this->data['t_order_by'] = $this->language->get('t_order_by');
    $this->data['t_result_not_found'] = $this->language->get('t_result_not_found');

    parent::index();

    $this->loadscripts();
    $this->load->library('image_validate');
    $image_validate = new Image_validate();

    $filterData = parent::setFilterData();

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

    if ($filterData['path']) {
      $path = '';
      $parts = explode('_', (string)$filterData['path']);
      $category_id = (int)array_pop($parts);

      foreach ($parts as $path_id) {
        if (!$path) {
          $path = (int)$path_id;
        } else {
          $path .= '_' . (int)$path_id;
        }

        $category_info = $this->model_catalog_category->getCategory($path_id);

        if ($category_info) {
          $this->data['breadcrumbs'][] = array(
            'text' => $category_info['name'],
            'href' => $this->url->link('product/category', parent::getUrlParameters(['path' => $path])),
            'separator' => $this->language->get('text_separator')
          );
        }
      }
    } else {
      $category_id = 0;
    }

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

    $category_info = $this->model_catalog_category->getCategory($category_id);

    if ($category_info) {
      if ($this->config->get('wg24_seo_categoria_status') == 'enable') {

        if ($this->config->get('wg24_seo_categoria_tituloini')) {
          $titulo_cat_ini = $this->config->get('wg24_seo_categoria_tituloini');
        } else {
          $titulo_cat_ini = "";
        }

        if ($this->config->get('wg24_seo_categoria_titulofim')) {
          $titulo_cat_fim = $this->config->get('wg24_seo_categoria_titulofim');
        } else {
          $titulo_cat_fim = "";
        }

        $this->document->setTitle($titulo_cat_ini . " " . $category_info['name'] . " " . $titulo_cat_fim);
      } else {
        if (isset($category_info['page_title']) && (trim($category_info['page_title']) <> "")) {
          $this->document->setTitle($category_info['page_title']);
        } else {
          $this->document->setTitle($category_info['name']);
        }

      }

      $this->document->setDescription($category_info['meta_description']);
      $this->document->setKeywords($category_info['meta_keyword']);
      $this->document->addScript('catalog/view/javascript/jquery/jquery.total-storage.min.js');

      $this->data['heading_title'] = $category_info['name'];
      // Set the last category breadcrumb

      $this->data['breadcrumbs'][] = array(
        'text' => $category_info['name'],
        'href' => $this->url->link('product/category', 'path=' . $filterData['path']),
        'separator' => $this->language->get('text_separator')
      );

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

      if ($category_info['image'] && $image_validate->isValidate($category_info)) {
        $this->data['thumb'] = $this->dmodel_tool_image->resize($category_info['image'], $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
      } else {
        $this->data['thumb'] = false;
      } 

      $this->data['exibeThumb'] = $this->config->get('wg24_category_image_status');

      $this->data['description'] = html_entity_decode($category_info['description'], ENT_QUOTES, 'UTF-8');
      $this->data['categories'] = array();

      $results = $this->model_catalog_category->getCategories($category_id);

      $this->data['image'] = array();
      foreach ($results as $result) {
        $data = array(
          'filter_category_id' => $result['category_id'],
          'filter_sub_category' => true
        );

        if ($this->config->get('config_product_count')) {
          $product_total = $this->model_catalog_product->getTotalProducts($data);
        }

        $this->data['categories'][] = array(
          'name' => $result['name'] . ($this->config->get('config_product_count') ? ' (' . $product_total . ')' : ''),
          'href' => $this->url->link('product/category', parent::getUrlParameters(['path' => $filterData['path'] . '_' . $result['category_id']]))
        );
      }

      $total_products = $this->cache->get('totalproducts.'.md5(implode(parent::getFilterData())) . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id'). '.'. $filterData['path']);

      if(!$total_products){

        $total_products = $this->model_catalog_product->getTotalProducts(parent::getFilterData());

        $this->cache->set('totalproducts.'.md5(implode(parent::getFilterData())) . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id') . '.' . $filterData['path'], $total_products);
      }

      $dataPagination = array(
        'total' => $total_products,
        'page' => $filterData['page'],
        'limit' => $filterData['limit'],
        'text' => $this->language->get('text_pagination'),
      );

      //validação feita para funcionar com a configuração de paginação pelo botão
      $this->data['status_aviseme'] = $this->config->get('avise_me_status');
      if (($this->config->get('config_pagination_type') && ($this->config->get('config_pagination_type') == Type_Pagination::Tp_More)) || $this->ftrgeralregistry->isApp()) {
        $dataPagination['url'] = $this->url->link('product/productList/defaultList', parent::getUrlParameters(['path' => $filterData['path'], 'page' => '{page}']), 'NONSSL', 'true', false, false);
        $this->data['pagination'] = json_encode(parent::getPagination($dataPagination, true), JSON_HEX_APOS);
        $this->data['paginationajax'] = true;

        if ($this->ftrgeralregistry->isApp()) {
          $this->document->addScriptApp(array('catalog/view/theme/appmobile/js/page.pagination.js'));
        } else {
          $this->document->addscript('catalog/view/theme/vista/js/page.pagination.js');
        }

      } else {
        $dataPagination['url'] = $this->url->link('product/category', parent::getUrlParameters(['path' => $filterData['path'], 'page' => '{page}']));
        $this->data['pagination'] = parent::getPagination($dataPagination);
        $this->data['paginationajax'] = false;
      }

      $this->data['totalProduct'] = $dataPagination['total']; // Criado para o app
      $this->data['sorts'] = parent::getSortList('product/category', parent::getUrlParameters());
      $this->data['limits'] = parent::getLimits('product/category');
      $this->data['sort'] = parent::getSort();
      $this->data['order'] = parent::getOrder();
      $this->data['limit'] = $filterData['limit'];

      $this->data['url'] = 'route2=' . $this->request->get['route'] . '&path=' . $this->request->get['path'];

      $this->template = parent::getTemplate('product/category.tpl');

      $this->children = parent::getChildren('product/productList/defaultList');

      $this->response->setOutput($this->render('product/category'));
    } else {
      parent::getProductNotFound('product/category');
    }
  }

  public function loadscripts()
  {
    $this->document->addScript('catalog/view/theme/vista/js/filter.js');
  }
}
