<?php

class ControllerProductDefault extends Controller
{
  
  public function index($setting = null)
  {
    $this->loadLanguage();
    $this->language->load('product/avise_me');
    
    //-------------------------- loadings -------------------------------------//
    $this->load->model('catalog/category');
    $this->load->model('catalog/product');
    $this->load->dmodel('tool/image');
    $this->load->type('tipocomum');
    $this->load->helper('ftr_geral');
    
    //--------------------------- GETS DE CONFIGS -----------------------------//
    $this->data['display_product_grid'] = $this->config->get('futuragrade_opcao_cor');
    $this->data['pagseguro_parcela'] = $this->config->get('pagseguro_parcela');
    $this->data['productBoxButton'] = $this->config->get('futuraquantidadeatacado_status');
    $this->data['typeProductBoxButton'] = $this->load->typeForTwig('Type_ProductBoxButton');
    $this->data['efeitoimg'] = $this->config->get('wg24_prod_efec_img');

    $this->data['futura_habilita_lista_desejos'] = ($this->config->get('wg24_futura_status_lista_desejos') == '') || ($this->config->get('wg24_futura_status_lista_desejos') == Type_Status::Tp_Habilitado);
    $this->data['futura_habilita_lista_comparacao'] = ($this->config->get('wg24_futura_status_lista_comparacao') == '') || ($this->config->get('wg24_futura_status_lista_comparacao') == Type_Status::Tp_Habilitado);
    $this->data['wg24_futura_prod_exibe_selo'] = $this->config->get('wg24_futura_prod_exibe_selo');
    $this->data['wg24_futura_prod_qtd_dias_novo'] = $this->config->get('wg24_futura_prod_qtd_dias_novo');
    $this->data['configefeito'] = $this->config->get('wg24_prod_efec_img');
    $this->data['continue'] = $this->url->link('common/home', '', 'NONSSL', 'false');
    $this->data['compare'] = $this->url->link('product/compare');
    $this->data['wg24_quick'] = ($this->config->get('wg24_quick') == Type_StatusEn::Tp_Enable) ? true : false;
    $this->data['config_product_list_rating_status'] = ($this->config->get('config_product_list_rating_status') == Type_Status::Tp_Habilitado) ? true : false;
    $this->data['exibe_futura_preco_dinamico'] = (($this->config->get('preco_dinamico_status')) && ($this->config->get('futura_preco_dinamico_produto'))) ? true : false;
    $this->data['box_large'] = $this->config->get('wg24_productbox_size') == Type_Tamanho::Tp_Grande;
    $this->data['class_actions_one_line'] = (!$this->data['productBoxButton'] || (!$this->data['futura_habilita_lista_desejos'] && !$this->data['futura_habilita_lista_comparacao'])) ? 'actions-one-line' : '';
    $this->data['layout_id_product'] = Type_IdLayout::Tp_Idcategory;
    $this->data['icon_cart'] = $this->config->get('icon_cart');
    $this->data['mostra_preco_sem_estoque'] = $this->config->get('mostra_preco_sem_estoque');

    if ($this->config->get('wg24_l_sale_icon_style') == 'circle') {
      $this->data['itembox_sale_label'] = 'itembox-sale-label-circle';
    } elseif ($this->config->get('wg24_l_sale_icon_style') == 'square') {
      $this->data['itembox_sale_label'] = 'itembox-sale-label-square';
    } else {
      $this->data['itembox_sale_label'] = '';
    }

    if($this->config->get('config_show_cronometer') == Type_Status::Tp_Habilitado){
      $this->data['config_show_cronometer'] = Type_Status::Tp_Habilitado ;
    }else{
      $this->data['config_show_cronometer'] = Type_Status::Tp_Desabilitado ;
    }

    $this->data['text_refine'] = $this->language->get('text_refine');
    $this->data['text_empty'] = $this->language->get('text_empty');
    $this->data['text_quantity'] = $this->language->get('text_quantity');
    $this->data['text_manufacturer'] = $this->language->get('text_manufacturer');
    $this->data['text_model'] = $this->language->get('text_model');
    $this->data['text_price'] = $this->language->get('text_price');
    $this->data['text_tax'] = $this->language->get('text_tax');
    $this->data['text_points'] = $this->language->get('text_points');
    $this->data['text_compare'] = sprintf($this->language->get('text_compare'), (isset($this->session->data['compare']) ? count($this->session->data['compare']) : 0));
    $this->data['compare_list'] = (isset($this->session->data['compare'])) ? $this->session->data['compare'] : [];
    $this->data['text_display'] = $this->language->get('text_display');
    $this->data['text_list'] = $this->language->get('text_list');
    $this->data['text_grid'] = $this->language->get('text_grid');
    $this->data['text_sort'] = $this->language->get('text_sort');
    $this->data['text_limit'] = $this->language->get('text_limit');
    $this->data['button_cart'] = $this->language->get('button_cart');
    $this->data['button_wishlist'] = $this->language->get('button_wishlist');
    $this->data['button_compare'] = $this->language->get('button_compare');
    $this->data['button_continue'] = $this->language->get('button_continue');
    $this->data['heading_title'] = $this->language->get('heading_title');
    $this->data['novo_selo'] = $this->language->get('novo_selo');
    $this->data['lang_learn_more_icon'] = $this->language->get('lang_learn_more_icon');
    $this->data['text_de'] = $this->language->get('text_de');
    $this->data['text_por'] = $this->language->get('text_por');


    /*variaveris de controle para setar grid e borda nas listagens dos produtos*/
    $this->data['itembox_border'] = Ftr_Geral::isType($this->config->get('wg24_itembox_border'), Type_DsimDnao::getEnumList(), Type_DsimDnao::Tp_Sim);
    if ($this->ftrgeralregistry->isApp()){
      $gridOrList = Type_gridOrListView::Tp_Grid;
    } else {
      $gridOrList = $this->config->get('wg24_cate_list_grid');
    }
    $this->data['gridOrList'] = (isset($gridOrList) && $gridOrList) ? substr($gridOrList, 0, strpos($gridOrList, '_')) : 'grid';

  }

  public function getFilter()
  {
    if (isset($this->request->get['filter'])) {
      return $this->request->get['filter'];
    } else {
      return '';
    }
  }

  public function getOrder()
  {
    if (isset($this->request->get['order'])) {
      return $this->request->get['order'];
    } elseif ((isset($this->request->get['route']) && $this->request->get['route'] == 'product/search') && ((!isset($this->request->get['sort'])) || ($this->request->get['sort'] == '') || ($this->request->get['sort'] == 'score'))) {
      return 'DESC';
    } else {
      if ($this->config->get('config_produto_ordenacao_padrao') == Type_OrdemProdutos::Tp_CadastroDec) {
        return 'DESC';
      } elseif (!isset($this->request->get['order']) && (isset($this->request->get['name'])) && $this->request->get['name'] == Type_ModuleListProduct::Tp_ProductViewedAll) {
        return 'DESC';
      } else {
        return 'ASC';
      }
    }
  }

  public function getSort()
  {
    if (isset($this->request->get['sort'])) {
      return $this->request->get['sort'];
    } else if (isset($this->request->get['route']) && (($this->request->get['route'] == 'fidelity/category') || ($this->request->get['route'] == 'fidelity/category/fidelitygrid'))) {
      return 'fp.pontos';
    } else if (isset($this->request->get['route']) && ($this->request->get['route'] == 'product/search')) {
      return 'score';
    } else if ($this->config->get('config_produto_ordenacao_padrao') == Type_OrdemProdutos::Tp_CadastroDec) {
      return 'p.data_replicacao_ecommerce';
    } else if (!isset($this->request->get['sort']) && (isset($this->request->get['name'])) && $this->request->get['name'] == Type_ModuleListProduct::Tp_ProductViewedAll) {
      return 'p.viewed';
    } else {
      return 'pd.name';
    }
  }

  public function getSortList($url, $urlParam = null)
  {

    $result[] = array(
      'text' => $this->language->get('text_name_asc'),
      'value' => 'pd.name-ASC',
      'href' => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'pd.name', 'order' => 'ASC']))
    );

    $result[] = array(
      'text' => $this->language->get('text_name_desc'),
      'value' => 'pd.name-DESC',
      'href' => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'pd.name', 'order' => 'DESC']))
    );

    $result[] = array(
      'text' => $this->language->get('text_price_asc'),
      'value' => 'p.price-ASC',
      'href' => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'p.price', 'order' => 'ASC']))
    );

    $result[] = array(
      'text' => $this->language->get('text_price_desc'),
      'value' => 'p.price-DESC',
      'href' => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'p.price', 'order' => 'DESC']))
    );

    if ($this->config->get('config_review_status')) {
      $result[] = array(
        'text' => $this->language->get('text_rating_desc'),
        'value' => 'rating-DESC',
        'href' => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'rating', 'order' => 'DESC']))
      );

      $result[] = array(
        'text' => $this->language->get('text_rating_asc'),
        'value' => 'rating-ASC',
        'href' => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'rating', 'order' => 'ASC']))
      );
    }

    $result[] = array(
      'text' => $this->language->get('text_model_asc'),
      'value' => 'p.model-ASC',
      'href' => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'p.model', 'order' => 'ASC']))
    );

    $result[] = array(
      'text' => $this->language->get('text_model_desc'),
      'value' => 'p.model-DESC',
      'href' => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'p.model', 'order' => 'DESC']))
    );

    $result[] = array(
      'text' => $this->language->get('text_visitado_desc'),
      'value' => 'p.viewed-DESC',
      'href' => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'p.viewed', 'order' => 'DESC']))
    );

    $result[] = array(
      'text' => $this->language->get('text_novos_produtos_desc'),
      'value' => 'p.data_replicacao_ecommerce-DESC',
      'href' => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'p.data_replicacao_ecommerce', 'order' => 'DESC']))
    );

    return $result;
  }

  /*recupera todos os GET que estiveremna url, caso não queria algum valor especifica-lo no segundo parametro*/
  public function getUrlParameters($pDefaults = null, $pIgnore = null)
  {

    $request = $this->request->get;

    if ($pIgnore !== null) {
      foreach ($pIgnore as $key => $value) {
        if (array_key_exists($value, $request)) {
          unset($request[$value]);
        }
      }
    }

    if ($pDefaults !== null) {
      foreach ($pDefaults as $key => $value) {
        if (array_key_exists($key, $request)) {
          $request[$key] = $pDefaults[$key];
        } else {
          $request = array_merge($request, [$key => $pDefaults[$key]]);
        }
      }
    }

    $url = '';

    if (isset($request['filter']) && (!in_array($request['filter'], $pIgnore))) {
      $url .= '&filter=' . $request['filter'];
    }

    if (isset($request['path'])) {
      $url .= '&path=' . $request['path'];
    }

    if (isset($request['name'])) {
      $url .= '&name=' . $request['name'];
    }

    if (isset($request['index'])) {
      $url .= '&index=' . $request['index'];
    }

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

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

    if ($this->config->get('futuragrade_status')) {
      if (isset($request['filcolor'])) {
        $url .= '&filcolor=' . $request['filcolor'];
      }
      if (isset($request['filsize'])) {
        $url .= '&filsize=' . $request['filsize'];
      }
      if (isset($request['filspecification'])) {
        $url .= '&filspecification=' . $request['filspecification'];
      }
    }

    if (isset($request['sort'])) {
      $url .= '&sort=' . $request['sort'];
    }

    if (isset($request['order'])) {
      $url .= '&order=' . $request['order'];
    }

    if (isset($request['page'])) {
      $url .= '&page=' . $request['page'];
    }

    if (isset($request['limit'])) {
      $url .= '&limit=' . $request['limit'];
    }

    if (isset($request['product_id'])) {
      $url .= '&product_id=' . $request['product_id'];
    }

    if (isset($request['manufacturer_id'])) {
      $url .= '&manufacturer_id=' . $request['manufacturer_id'];
    }

    if (isset($request['search'])) {
      $url .= '&search=' . rawurlencode(html_entity_decode($request['search'], ENT_QUOTES, 'UTF-8'));
    }

    if (isset($request['tag'])) {
      $url .= '&tag=' . rawurlencode(html_entity_decode($request['tag'], ENT_QUOTES, 'UTF-8'));
    }

    if (isset($request['category_id'])) {
      $url .= '&category_id=' . $request['category_id'];
    }

    if (isset($request['order_promotion_id'])) {
      $url .= '&order_promotion_id=' . $request['order_promotion_id'];
    }

    return $url;
  }

  /*Exibi a tpl da pagina não encontrada mudando os parametros de acordo com a opção*/
  public function getProductNotFound($url)
  {
    $this->data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_error'),
      'href' => $this->url->link($url, $this->getUrlParameters()),
      'separator' => $this->language->get('text_separator')
    );

    $this->breadcrumbs->setbreadcumbs($this->data['breadcrumbs']);
    $this->document->setTitle($this->language->get('text_error'));
    $this->response->addHeader($this->request->server['SERVER_PROTOCOL'] . '/1.1 404 Not Found');

    $this->data['heading_title'] = $this->language->get('text_error');
    $this->data['text_error'] = $this->language->get('text_error');
    $this->data['button_continue'] = $this->language->get('button_continue');
    $this->data['continue'] = $this->url->link('common/home', '', 'NONSSL', 'false');

    $this->template = $this->getTemplate('error/not_found.tpl');

    $this->children = $this->getChildren();

    $this->response->setOutput($this->render('error/not_found'));
  }

  /*Verifica se o template passado existe*/
  public function getTemplate($template)
  {

    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/' . $template)) {
      $pagetpl = $this->config->get('config_template') . '/template/' . $template;
    } else {
      $pagetpl = 'default/template/' . $template;
    }

    return $pagetpl;
  }

  /*Cria a paginação das paginas de listagens */
  public function getPagination($data = array(), $json = false)
  {
    $pagination = new Pagination();
    $pagination->total = $data['total'];
    $pagination->page = $data['page'];
    $pagination->limit = $data['limit'];
    $pagination->text = $data['text'];
    $pagination->url = $data['url'];
    return $pagination->render($json);
  }

  /*Valida se o GET esta passando o parametro caso não esteja atribui o valor Default, caso tenha um subparmetro verifica se deve atribui-lo*/
  public function getRequest($param, $default, $subparam = false)
  {
    if (isset($this->request->get[$param])) {
      if ($subparam) {
        if (isset($this->request->get[$subparam]) && (!empty($this->request->get[$subparam]))) {
          return $this->request->get[$subparam];
        }
      }
      return $this->request->get[$param];
    }
    return $default;
  }

  /*Cria os links de quantos produtos serão listados em cada pagina*/
  public function getLimits($href, $param = null, $page = null)
  {
    $arrayLimits = array();
    if ($page == Type_ModuleListProduct::Tp_ProductVisualized) {
      $limits = array_unique(array($this->config->get('product_visualized_limit')));
    } else {
      $limits = array_unique(array($this->config->get('config_catalog_limit'), 24, 48, 72, 96));
    }
    sort($limits);
    foreach ($limits as $value) {
      $arrayLimits[] = array(
        'text' => $value,
        'value' => $value,
        'href' => $this->url->link($href, $this->getUrlParameters([$param, 'limit' => $value], ['page']))
      );
    }
    return $arrayLimits;
  }

  /*Especifica os arquivos filhos podendo adicionar mais um caso necessario*/
  public function getChildren($data = null)
  {
    $children = array(
      'common/breadcrumbs',
      'common/column_left',
      'common/column_right',
      'common/column_refinar',
      'common/content_top',
      'common/content_bottom',
      'common/footer',
      'common/header'
    );
    if ($data !== null) {
      array_push($children, $data);
    }
    return $children;
  }

  /*Pega as variaveis que estão sendo passadas por GET e monta um array para que possamos chama-las em outros lugares*/
  public function setFilterData()
  {
    $result = array();

    $result['path'] = $this->getRequest('path', false);
    $result['search'] = $this->getRequest('search', '');
    $result['category_id'] = $this->getRequest('category_id', 0);
    $result['page'] = $this->getRequest('page', 1);
    $result['tag'] = html_entity_decode($this->getRequest('tag', '', 'search'), ENT_COMPAT, 'UTF-8');
    $result['description'] = $this->getRequest('description', '');
    $result['sub_category'] = $this->getRequest('sub_category', '');
    $result['name'] = $this->getRequest('name', '');
    $result['manufacturer_id'] = $this->getRequest('manufacturer_id', 0);
    $result['order_promotion_id'] = $this->getRequest('order_promotion_id', '');

    if ($this->config->get('futurafiltromarca_status')) {
      $result['filbrand'] = $this->getRequest('filbrand', false);
    }

    if ($this->config->get('futurafiltrovalor_status')) {
      $result['price_initial'] = str_replace(array('.', ','), array('', '.'), $this->getRequest('price_initial', false));
      $result['price_laste'] = str_replace(array('.', ','), array('', '.'), $this->getRequest('price_laste', false));
    }

    if ($this->config->get('futuragrade_status')) {
      //limpa a variavel de sessão que armazena a quantidade escolida quando o produto é grade
      $this->session->data['addQtd'] = array();
      $result['filcolor'] = $this->getRequest('filcolor', false);
      $result['filsize'] = $this->getRequest('filsize', false);
      $result['filspecification'] = $this->getRequest('filspecification', false);
    }

    if ($this->config->get('fidelity_status')) {
      //limpa a variavel de sessão que armazena a quantidade escolida quando o produto é grade
      $result['filrange'] = $this->getRequest('filrange', false);
    }

    $result['sort'] = $this->getSort();
    $result['order'] = $this->getOrder();
    $result['start'] = ($this->getRequest('page', 1) - 1) * $this->getRequest('limit', $this->config->get('config_catalog_limit'));
    $result['limit'] = $this->getRequest('limit', $this->config->get('config_catalog_limit'));

    return $result;
  }

  /*Utilzando o array que é montador na função 'setFilterData' montamos o array no padrão da pesquisa de produtos*/
  public function getFilterData()
  {
    $filterData = $this->setFilterData();
    if ($filterData['path'] != "") {
      $parts = explode('_', (string)$filterData['path']);
      $category_id = (int)array_pop($parts);
    } else {
      $category_id = $filterData['category_id'];
    }

    $data = array(
      'filter_manufacturer_id' => $filterData['manufacturer_id'],
      'filter_name' => $filterData['search'],
      'filter_tag' => $filterData['tag'],
      'filter_description' => $filterData['description'],
      'filter_order_promotion' => $filterData['order_promotion_id'],
      'filcolor' => ($this->config->get('futuragrade_status')) ? $filterData['filcolor'] : '',
      'filsize' => ($this->config->get('futuragrade_status')) ? $filterData['filsize'] : '',
      'filspecification' => ($this->config->get('futuragrade_status')) ? $filterData['filspecification'] : '',
      'filter_category_id' => $category_id,
      'price_initial' => ($this->config->get('futurafiltrovalor_status')) ? $filterData['price_initial'] : '',
      'price_laste' => ($this->config->get('futurafiltrovalor_status')) ? $filterData['price_laste'] : '',
      'filbrand' => ($this->config->get('futurafiltromarca_status')) ? $filterData['filbrand'] : '',
      'filter_sub_category' => $filterData['sub_category'],
      'filrange' => ($this->config->get('fidelity_status')) ? $filterData['filrange'] : '',
      'name' => $filterData['name'],
      'sort' => $filterData['sort'],
      'order' => $filterData['order'],
      'start' => $filterData['start'],
      'limit' => $filterData['limit']
    );
    return $data;
  }


  //Função que calcula a diferença quantodade de dias para mostrar ou nao o selo de produto novo - por Henrique R. Pohl
  public function validaSeloNovo($originalData, $qtdDiasNovo)
  {
    $dataAddProduto = new DateTime($originalData);
    $dataAtual = new DateTime(date("Y-m-d"));
    $diferenca = $dataAddProduto->diff($dataAtual);
    $dataDias = $diferenca->days;

    if ($dataDias < $qtdDiasNovo) {
      return true;
    } else {
      return false;
    }
  }

  public function loadLanguage()
  {

    if (isset($this->request->get['route'])) {
      switch ($this->request->get['route']) {
        case 'product/search':
          $this->language->load('product/search');
          break;
        case 'product/category':
          $this->language->load('product/category');
          break;
        case 'product/manufacturer':
          $this->language->load('product/manufacturer');
          break;
        case 'product/manufacturer/info':
          $this->language->load('product/manufacturer');
          break;
        case 'product/special':
          $this->language->load('product/special');
          break;
      }
    }

  }

  public function modulesInPage()
  {

    if (isset($this->request->get['route'])) {
      if ($this->request->get['route'] == 'product/modules_in_page') {
        return true;
      } else {
        return false;
      }
    }

  }

  public function getTotalPaginationModulesInPage()
  {

    switch ($this->request->get['name']) {
      case Type_ModuleListProduct::Tp_ProductVisualized:
        $result = $this->productvisualized->getTotalProducts();
        return $result;
        break;
      case Type_ModuleListProduct::Tp_Featured:
        $productsId = $this->config->get('featured_product');

        if (isset($this->request->get['index']) && !isset($productsId)) {
          $index = $this->request->get['index'];
          $featuredModule = $this->config->get('featured_module');

          if (isset($featuredModule) && isset($featuredModule[$index])) {
            $productsId = $featuredModule[$index]['featured_product'];
          }
        }

        if (gettype($productsId) == 'array') {
          $productsId = implode(',', $productsId);
        }

        $data = $this->getFilterData();
        $data['productsId'] = $productsId;
        return $this->model_catalog_product->getTotalProducts($data);
        break;
      case Type_ModuleListProduct::Tp_Special:
        $data = $this->getFilterData();
        return $this->model_catalog_product->getProductTotalSpecials($data);
        break;
      default:
        $this->load->model('catalog/product');
        return $this->model_catalog_product->getTotalProducts($this->getFilterData());
        break;
    }

  }

  public function getTitleModulesInPage($title)
  {
    return (ftr_geral::isIsset($this->config->get($this->request->get['name'] . '_title')) && ($this->config->get($this->request->get['name'] . '_title') != "")) ? $this->config->get($this->request->get['name'] . '_title') : $title;
  }

}
