<?php

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

class ControllerFidelityCategory extends ControllerProductDefault
{

  public function index($setting = null)
  {

    if (!$this->config->get('fidelity_status')) {
      return false;
    }

    parent::index();

    $this->loadscripts();

    $language = $this->load->language('fidelity/category');
    $this->data = array_merge($this->data, $language);

    $this->document->setTitle($this->language->get('heading_title'));

    $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
    );

    $this->data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_trade'),
      'href' => $this->url->link('fidelity/category', '', 'SSL'),
      'separator' => $this->language->get('text_separator')
    );

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

    $data = parent::getFilterData();
    $data['fidelity'] = true;

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


    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('fidelity/category/fidelitygrid', parent::getUrlParameters(['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',
          'catalog/view/theme/appmobile/js/template/fidelity/fidelity.js',
        ));
      } else {
        $this->document->addscript('catalog/view/theme/vista/js/page.pagination.js');
      }

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

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


    $this->load->dmodel('tool/image');
    $this->load->type('tipocomum');

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

    $products = $this->fidelitycart->getProducts();
    $this->data['total_points'] = $this->fidelitycart->getTotal();

    $this->data['go_to_fidelity_cart'] = $this->url->link('fidelity/cart');

    foreach ($products as $product) {
      if ($product['image']) {
          $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
          $image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $product['data_atualizacao_replicacao']) . $watermark_config_date_number;

          $image = $this->dmodel_tool_image->resizeWithWatermark($product['image'], Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height) . $image_version_number;
      } else {
        $image = $this->dmodel_tool_image->resize('data/sem-imagem.png', Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height);
      }

      $total = ($product['pontos'] * $product['quantity']);

      $this->data['cartlists'][Type_ProductCart::Tp_Default][0]['products'][] = array(
        'color_description' => ($this->config->get('futuragrade_status')) ? $product['color_description'] : '',
        'size_description' => ($this->config->get('futuragrade_status')) ? $product['size_description'] : '',
        'specification_description' => ($this->config->get('futuragrade_status')) ? $product['specification_description'] : '',
        'color_template_description' => ($this->config->get('futuragrade_status')) ? $product['color_template_description'] : '',
        'size_template_description' => ($this->config->get('futuragrade_status')) ? $product['size_template_description'] : '',
        'specification_template_description' => ($this->config->get('futuragrade_status')) ? $product['specification_template_description'] : '',
        'key' => $product['key'],
        'product_id' => $product['product_id'],
        'thumb' => $image,
        'name' => $product['name'],
        'model' => $product['model'],
        'quantity' => $product['quantity'],
        'stock' => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
        'pontos' => $product['pontos'],
        'total' => $total,
        'total_value' => str_replace(array('R$ ', ',', '.'), array('', '', ''), $total),
        'href' => $this->url->link('fidelity/product', 'product_id=' . $product['product_id']),
        'remove' => $this->url->link('fidelity/cart', 'remove=' . $product['key']),
        'id_futura' => $product['id_futura'],
      );

    }
    ksort($this->data['cartlists']);//ordenando por tipo e deixando a lista de produtos(que não em lista) na primeira posição

    $this->children = parent::getChildren('fidelity/category/fidelitygrid');

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

    $this->response->setOutput($this->render('fidelity/category'));

  }

  public function fidelitygrid()
  {
    $this->load->model('catalog/product');
    $this->load->dmodel('tool/image');

    $language = $this->load->language('fidelity/category');
    $this->data = array_merge($this->data, $language);

    $data = parent::getFilterData();
    $data['sorts'] = $this->getSortList('fidelity/category', parent::getUrlParameters());
    $data['sort'] = parent::getSort();
    $data['order'] = parent::getOrder();
    $data['fidelity'] = true;
    $results = $this->model_catalog_product->getProducts($data);

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

    $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
    if($results){
      foreach ($results as $product) {

        $gridhave = "";
        if ($this->config->get('futuragrade_status') && $this->config->get('futuragrade_opcao_cor')) {
          $gridid = $this->model_catalog_product->getIDProductGrid($product['product_id']);
          if ($gridid) {
            $prodcolors = $this->model_catalog_product->getGridColor($gridid, $product['product_id']);
            if (($prodcolors) && (count($prodcolors) > 1)) {
              $gridhave = $this->model_catalog_product->getGridHave($product['product_id']);
            }
          }
        }

        $mouse_hover = $this->db->query("SELECT pi.*, p.data_atualizacao_replicacao
                                            FROM `" . DB_PREFIX . "product_image` pi
                                            INNER JOIN " . DB_PREFIX . "product p on (pi.product_id = p.product_id)
                                            WHERE p.product_id = '" . (int)$product['product_id'] . "' order by product_image_id limit 1 ");
        foreach ($mouse_hover as $hover_image) {
          if ($hover_image) {
            if (isset($hover_image['image'])) {
              $image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $hover_image['data_atualizacao_replicacao']) . $watermark_config_date_number;

              $mouse_hover_image = $this->dmodel_tool_image->resizeWithWatermark($hover_image['image'], $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height')) . $image_version_number;
            } else {
              $mouse_hover_image = false;
            }

            if (isset($hover_image['product_id'])) {
              $hover_id = $hover_image['product_id'];
            } else {
              $hover_id = false;
            }
            if ($mouse_hover_image && $hover_id) {
              $this->data['image'][$product['product_id']] = array(
                'mousehover' => $mouse_hover_image,
                'hover_id' => $hover_id,
              );
            }
          }
        }

        if (!array_key_exists($product['product_id'], $this->data['image'])) {
          $this->data['image'][$product['product_id']] = array(
            'mousehover' => false,
            'hover_id' => false,
          );
        }

        $image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $product['data_atualizacao_replicacao']) . $watermark_config_date_number;

        if ($product['image']) {
            $image = $this->dmodel_tool_image->resizeWithWatermark($product['image'], $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height')) . $image_version_number;
        } else {
            $image = $this->dmodel_tool_image->resize('data/sem-imagem.png', $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
        }

        if ($product['image']) {
            $thumb = $this->dmodel_tool_image->resizeWithWatermark($product['image'], 68, 68) . $image_version_number;
        } else {
            $thumb = $this->dmodel_tool_image->resize('data/sem-imagem.png', 68, 68);
        }

        $this->data['aspect_ratio'] = str_replace(',', '.', ($this->config->get('config_image_category_height') / $this->config->get('config_image_category_width') * 100)) . '%';

        if ($this->config->get('exist_content_left') || $this->config->get('new_products_type')) {
          $exist_content = true;
        } else {
          $exist_content = false;
        }

        if (isset($this->data['slider']) && !$this->data['grid']) {
          $content = 'item-column';
        } else {
          $content = ($exist_content || (isset($this->data['home_sidebar_content']) && $this->data['home_sidebar_content']) || (isset($setting['product_list_color']) && ($setting['product_list_color']))) ? 'col-lg-4 col-md-4 col-ms-6 col-xs-12' : 'col-lg-3 col-md-4 col-sm-4 col-ms-6 col-xs-12';
        }

        if (trim(strip_tags($product['description'])) != "" && strlen(trim(strip_tags($product['description']))) > 100) {
          $description = utf8_substr(strip_tags(html_entity_decode(trim($product['description']), ENT_QUOTES, 'UTF-8'), '<br>'), 0, 100) . '...';
        } else {
          $description = strip_tags(html_entity_decode(trim($product['description']), ENT_QUOTES, 'UTF-8'), '<br>');
        }

        if($this->config->get('futuragrade_status')){
          $gridhave = $this->model_catalog_product->getGridHave($product['product_id']);

          if ($gridhave['grid_id'] && $this->listGrid) {

            $notification_value = ($this->fidelitycart->hasGridId() && in_array($gridhave['grid_id'], $this->fidelitycart->hasGridId())) ? $gridhave['grid_id'] : false;

          } else {
            $notification_value = isset($this->fidelitycart->getProducts()[$product['product_id'] . '::']) ? $this->fidelitycart->getProducts()[$product['product_id'] . '::']['quantity'] : false;
          }
        }else{
          $gridhave = false;
          $notification_value = false;
        }

        $products[] = array(
          'gridhave' => ($gridhave && $gridhave['grid_id']) ? true : false,
          'product_id' => $product['product_id'],
          'pontos' => number_format($product['pontos'], 0, '.', '.'),
          'thumb' => $image,
          'thumb_mini' => $thumb,
          'date_added' => $product['date_added'],
          'name' => $product['name'],
          'quantity' => $product['qty'],
          'description' => preg_replace('/(<br).*?(>)/', " ", strip_tags($description, '<br>')),
          'image_extra' => ($this->data['image'][$product['product_id']]['mousehover'] != "") ? $this->data['image'][$product['product_id']]['mousehover'] : $image,
          'gridhave' => ($gridhave != "") ? $gridhave['grid_id'] : '',
          'content' => $content,
          'ratio' => ($this->data['aspect_ratio']) ? 'style="height: 0; padding-bottom: ' . $this->data['aspect_ratio'] . '"' : '',
          'class_one_line' => (strlen($product['name']) <= 18) ? 'one-line' : '',
          'href' => $this->url->link('fidelity/product', parent::getUrlParameters(['product_id' => $product['product_id']], ['page'])),
          'notification_value' => ($this->customer->isLogged()) ? $notification_value : false
        );

      }
    }else{
      return false;
    }

    $this->data['products'] = $products;
    $this->load->dmodel('design/layout');
    $this->data['fidelity_id_layout'] = $this->dmodel_design_layout->getLayoutByName('fidelidade');

    $this->response->setOutput($this->render('fidelity/fidelitygrid'));
  }

  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_pontos_asc'),
      'value' => 'fp.pontos-ASC',
      'href' => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'fp.pontos', 'order' => 'ASC']))
    );

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

    return $result;

  }

  protected function loadscripts()
  {
    $this->document->addScript(array(
      'catalog/view/theme/vista/js/filter.js',
      'catalog/view/theme/vista/js/page.fidelity.js'
    ));
  }


}
