<?php

class ControllerCommonHome extends Controller
{
  public function index()
  {
    $this->document->setTitle($this->config->get('config_title'));
    $this->document->setDescription($this->config->get('config_meta_description'));
    $this->load->type('tipocomum');

    $this->data['heading_title'] = $this->config->get('config_title');
    $this->data['tipo_banner'] = $this->config->get('tipo_banner');
    $this->data['habilita_banner'] = $this->config->get('habilita_banner');
    $this->data['tipo_configuracao'] = $this->config->get('tipo_configuracao');

    $this->data['hide_responsive'] = (Ftr_Geral::isIsset($this->config->get('hide_responsive'))) ? ($this->config->get('hide_responsive') == Type_DsimDnao::Tp_Sim) ? 'hidden-md-down' : '' : 'hidden-md-down';

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

    $server = $this->url->link('', '', 'SSL', false);

    $this->document->addLink($server, 'canonical');

    $this->load->model('design/banner');
    $this->load->dmodel('tool/image');
    $this->load->type('tipocomum');
    $this->load->helper('ftr_geral');

//===============================começo do mundo========================================//
    $this->data['fc_popup'] = $this->config->get('fc_popup');
    if ($this->config->get('newsletter_status')) {
        $this->data['newsletter_name'] = $this->config->get('newsletter_name');
        $this->data['fc_newsletter'] = $this->config->get('newsletter_fc');
    }

    if (isset($this->data['fc_popup']['status']) && $this->data['fc_popup']['status']) {
        if ($this->data['fc_popup']['image']) {
            list($width_orig, $height_orig) = getimagesize(DIR_IMAGE . $this->data['fc_popup']['image']);
            $this->data['fc_popup']['image'] = $this->dmodel_tool_image->resize($this->data['fc_popup']['image'], $width_orig, $height_orig);
        }

        if ($this->data['fc_popup']['responsive_image']) {
            list($width_orig, $height_orig) = getimagesize(DIR_IMAGE . $this->data['fc_popup']['responsive_image']);
            $this->data['fc_popup']['responsive_image'] = $this->dmodel_tool_image->resize($this->data['fc_popup']['responsive_image'], $width_orig, $height_orig);
        }
    }

    $this->language->load('module/featured');
    $this->data['heading_title'] = $this->language->get('heading_title');
    $this->data['button_cart'] = $this->language->get('button_cart');
    $this->load->model('catalog/product');
    $this->load->dmodel('tool/image');
    $this->data['pagseguro_parcela'] = $this->config->get('pagseguro_parcela');
    $this->data['products'] = array();
    $this->data['efeitoimg'] = $this->config->get('wg24_prod_efec_img');

    $products = $this->data['banner_product'];

    if (empty($setting['limit'])) {
      $setting['limit'] = 5;
    }

    $this->data['banner_time'] = ($this->config->get('banner_time') * 1000);

    /* COMECO - Habilita e Desabilita Lista de Desejo e Comparação - por Henrique R. Pohl */
    $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);
    /* FIM - Habilita e Desabilita Lista de Desejo e Comparação - por Henrique R. Pohl */

    //Validação para exibir opção de lista escolar
    $this->data['exibe_listaescolar'] = $this->config->get('listaescolar_status');
    $this->data['link_listaescolar'] = $this->urlloja->link('listaescolar/listaescolar');


    /* COMECO - Habilita e Desabilita Selo para novos produtos e filtra a data de cadastro - por Henrique R. Pohl */
    $this->data['wg24_futura_prod_exibe_selo'] = ($this->config->get('wg24_futura_prod_exibe_selo') == '') || ($this->config->get('wg24_futura_prod_exibe_selo') == Type_Status::Tp_Habilitado);
    $this->data['wg24_futura_prod_qtd_dias_novo'] = $this->config->get('wg24_futura_prod_qtd_dias_novo');
    /* FIM - Habilita e Desabilita Selo para novos produtos e filtra a data de cadastro - por Henrique R. Pohl */

    $this->data['futuraquantidadeatacado_status'] = $this->config->get('futuraquantidadeatacado_status');
    $this->data['image'] = array();
    $this->data['banner_product_model'] = array();

    $this->data['aspect_ratio'] = false;
    $this->data['banner_height'] = false;

    if($this->config->get('habilita_banner')) {


      if ($this->config->get('banner_dinamico')) {
        $products = $this->getBannerProduct();
      } else {
        $products = ($this->config->get('banner_product')) ? $this->config->get('banner_product') : $products = array();
      }

      $this->load->model('setting/analyze');

      foreach ($products as $product_id) {
        $analyze_code = '';
        if (isset($product_id['analyze_id'])) {
          $codigo = $this->model_setting_analyze->getAnalyze($product_id['analyze_id']);
          $analyze_code = ($codigo) ? $codigo['codigo'] : '';
        }

        $product_info = $this->model_catalog_product->getProduct($product_id['product_id'], $this->getStatusAviseme(), false, false);

        if ($product_info) {

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

          if ($product_info['image']) {
            $image = $this->dmodel_tool_image->resizeProductImageWebp($product_info['image'], 400, 400);

              if (!is_null($image)) {
                  $image = array_map(function ($array) use ($product_info) {
                      $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
                      return $array . '?version=' . preg_replace("/[^0-9]/", "", $product_info['data_atualizacao_replicacao']) . $watermark_config_date_number;
                  }, $image);
              } else {
                  $image = $this->dmodel_tool_image->resizeWebp('data/sem-imagem.png', $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
              }

          } else {
            $image = $this->dmodel_tool_image->resizeWebp('data/sem-imagem.png', 400, 400);
          }

          if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
            $price = $this->currency->format($product_info['price']);
          } else {
            $price = false;
          }

          if ((float)$product_info['special']) {
            $special = $this->currency->format($product_info['special']);
          } else {
            $special = false;
          }

          if ($this->config->get('config_review_status')) {
            $rating = $product_info['rating'];
          } else {
            $rating = false;
          }

          if (($this->config->get('futura_preco_dinamico_exibicoes'))) {
            $this->data['futura_preco_dinamico_exibicoes'] = $this->config->get('futura_preco_dinamico_exibicoes');
          } else {
            $this->data['futura_preco_dinamico_exibicoes'] = 'echo \'R$ \'. number_format( $price_pr , 2,\',\',\'.\')
					.html_entity_decode(nl2br(\'<br> ou 3x de  R$ \'))
					.number_format( ($price_pr / 3) , 2,\',\',\'.\') ;';
          }

          if (isset($product_id['banner_model']) && $product_id['banner_model'] == 'model-a') {
            $product_id['banner_model'] = 'model-' . rand(1, 4);
          }

          if (isset($product_id['banner_model'])) {
            $this->data['banner_product_model'][$product_id['banner_model']] = true;
          }

          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 ;
          }

          $banner_group_order = property_exists((Object)$product_id, 'banner_group_order') ? $product_id['banner_group_order'] : 0;

          $promotion = $this->model_catalog_product->getProductPromotion($product_info['product_id']);

            $this->data['products'][] = array(
            'product_id' => $product_info['product_id'],
            'banner_model' => (isset($product_id['banner_model'])) ? $product_id['banner_model'] : 'model-1',
            'banner_order' => $product_id['banner_order'],
            'banner_group_order' => $banner_group_order,
            'price_pr' => $product_info['price'],
            'thumb' => $image,
            'name' => $product_info['name'],
            'price' => $price,
            'gridhave' => ($gridhave != "") ? $gridhave['grid_id'] : '',
            'href' => $this->url->link('product/product', 'product_id=' . $product_info['product_id'] . $analyze_code),
            'porcentagemDesconto' => ftr_geral::calculaDescontoPromocao($product_info['price'], $product_info['special']),
            'special' => $special,
            'promotion_id' => $promotion ? $promotion['order_promotion_id'] : false,
            'status' => (isset($product_id['date_initial']) && isset($product_id['date_end'])) ? $this->statusBanner($product_id['date_initial'], $product_id['date_end']) : true
          );
        }
      }

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

      $results = $this->model_design_banner->getBanner($this->config->get('banner_rotativo'));

      $bannerwidth = ($this->config->get('banner_largura')) ? $this->config->get('banner_largura') : Type_BannerHome::Tp_Largura;
      $bannerheight = ($this->config->get('banner_altura')) ? $this->config->get('banner_altura') : Type_BannerHome::Tp_Altura;

      $banner_responsive_width = ($this->config->get('banner_responsive_largura')) ? $this->config->get('banner_responsive_largura') : Type_BannerHome::Tp_Largura;
      $banner_responsive_height = ($this->config->get('banner_responsive_altura')) ? $this->config->get('banner_responsive_altura') : Type_BannerHome::Tp_Altura;

      foreach ($results as $result) {
        if (file_exists(DIR_IMAGE . $result['image'])) {
          $this->data['banners'][] = array(
            'title' => $result['title'],
            'link' => $result['link'],
            'image' => $this->dmodel_tool_image->resizeWebp($result['image'], $bannerwidth, $bannerheight)
          );
        }
      }


      //=================================banner com imagem no banner html============================================
      $this->data['banner_image'] = ($this->config->get('banner_image')) ? $this->config->get('banner_image') : $this->data['banner_image'] = array();

      foreach ($this->data['banner_image'] as $value_image) {
        $analyze_code = '';
        if (isset($value_image['analyze_id'])) {
          $codigo = $this->model_setting_analyze->getAnalyze($value_image['analyze_id']);
          $analyze_code = ($codigo) ? $codigo['codigo'] : '';
          $analyze_code = ($analyze_code && !strpos($value_image['link'], '?')) ? '?' . $analyze_code : $analyze_code;
        }

        if ($value_image['image'] && file_exists(DIR_IMAGE . $value_image['image'])) {
          $image = $value_image['image'];
        } else {
          $image = 'no_image.jpg';
        }

        if (isset($value_image['image_responsive']) && file_exists(DIR_IMAGE . $value_image['image_responsive'])) {
          $image_responsive = $value_image['image_responsive'];
        } else {
          $image_responsive = 'no_image.jpg';
        }

        $banner_order = ($value_image['banner_order'] != '') ? $value_image['banner_order'] : 0;
        $banner_group_order = property_exists((Object)$value_image, 'banner_group_order') ? $value_image['banner_group_order'] : 0;

        $thumb = $this->dmodel_tool_image->resizeWebp($image, $bannerwidth, $bannerheight);
        $thumb_responsive = $this->dmodel_tool_image->resizeWebp($image_responsive, $banner_responsive_width, $banner_responsive_height);

        $this->data['products'][] = array(
          'banner_image_description' => $value_image['banner_image_description'][$this->config->get('config_language_id')]['title'],
          'link' => isset($value_image['link']) ? $value_image['link'] . $analyze_code : false,
          'target' => (isset($value_image['target'])) ? $value_image['target'] : false,
          'banner_order' => $banner_order,
          'banner_group_order' => $banner_group_order,
          'image' => $image,
          'image_responsive' => $image_responsive,
          'thumb' => $thumb,
          'thumb_responsive' => $thumb_responsive,
          'status' => (isset($value_image['date_initial']) && isset($value_image['date_end'])) ? $this->statusBanner($value_image['date_initial'], $value_image['date_end']) : true
        );
      }

      function compara($a, $b)
      {
          return (($a['banner_group_order'] > $b['banner_group_order'])
              || (($a['banner_group_order'] == $b['banner_group_order']) && ($a['banner_order'] > $b['banner_order']))) ? 1 : -1;
      }

      usort($this->data['products'], "compara");

      $this->data['aspect_ratio'] = str_replace(',', '.', ($bannerheight / $bannerwidth * 100)) . '%';
      $this->data['banner_height'] = $bannerheight;
    }

    if ($this->config->get('wg24_categories_sidebar_home') == Type_Status::Tp_Habilitado) {
      $this->data['position_categories_sidebar_home'] = ($this->config->get('wg24_position_categories_sidebar_home')) ? $this->config->get('wg24_position_categories_sidebar_home') : '';

      // Menu
      $this->load->model('catalog/category');

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

      $categories = $this->model_catalog_category->getCategories(0);

      foreach ($categories as $category) {
        // Level 2
        $children_data = array();

        $children = $this->model_catalog_category->getCategories($category['category_id']);

        foreach ($children as $child) {
          $data = array(
            'filter_category_id' => $child['category_id'],
            'filter_sub_category' => true
          );

          $subchildren_data = array();

          $subchildren = $this->model_catalog_category->getCategories($child['category_id']);

          //level 3
          foreach ($subchildren as $subchild) {
            $subchildren_data[] = array(
              'category_id' => $subchild['category_id'],
              'name' => $subchild['name'],
              'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'] . '_' . $subchild['category_id'])
            );
          }


          $children_data[] = array(
            'category_id' => $child['category_id'],
            'name' => $child['name'],
            'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id']),
            'subchildren' => $subchildren_data
          );
        }

        // Level 1
        $this->data['categories'][] = array(
          'name' => $category['name'],
          'children' => $children_data,
          'column' => $category['column'] ? $category['column'] : 1,
          'href' => $this->url->link('product/category', 'path=' . $category['category_id'])
        );
      }

    }

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

    $this->children = array(
      'common/content_app',
      'common/column_left',
      'common/column_right',
      'common/content_top',
      'common/content_bottom',
      'common/footer',
      'common/header'
    );


    $this->response->setOutput($this->render('common/home'));
  }

  /* COMECO - % de desconto do produto  por Henrique R. Pohl */
  public function calculaDescontoPromocao($preco, $precoPromocao)
  {

    return round(($precoPromocao * 100) / $preco - 100) . "%";

  }
  /* FIM - % de desconto do produto  por Henrique R. Pohl */

  /* COMECO - 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;
    }

  }
  /* FIM - Função que calcula a diferença quantodade de dias para mostrar ou nao o selo de produto novo - por Henrique R. Pohl */

  /*COMEÇO: Função para habilitar/desabilitar o banner de acordo com a data cadastrada - por Dionis Mendanha */
  public function statusBanner($dataInicio, $dataFinal)
  {
    $this->load->helper('ftr_geral');

    if (isset($dataInicio) && isset($dataFinal) && ($dataFinal != '')) {
      return (ftr_geral::compareDate($dataInicio, date('d/m/Y'), 'menorigual') && ftr_geral::compareDate($dataFinal, date('d/m/Y'), 'maiorigual'));
    } else {
      return ftr_geral::compareDate($dataInicio, date('d/m/Y'), 'menorigual');
    }
  }

  /*FIM: Função para habilitar/desabilitar o banner de acordo com a data cadastrada - por Dionis Mendanha */


  public function getBannerProduct()
  {
    $this->load->model('catalog/product');
    $arrayResult = array();

    if ($this->config->get('banner_product')) {
      $arrayProduct = array();
      $arrayResult = array_merge($arrayResult, $this->config->get('banner_product'));
    }

    $arrayDinamico = $this->config->get('banner_dinamico');
    foreach ($arrayDinamico as $value) {
      $dataDefault = array(
        'sort' => 'p.date_added',
        'order' => 'DESC',
        'start' => 0,
        'limit' => $value['banner_dinamico_quantidade'],
        'filter_quantity' => $this->getStatusAviseme(),
        'filter_content' => (ftr_geral::isIsset($this->config->get('config_setting_search_name'))) ? $this->config->get('config_setting_search_name') : Type_FilterContent::Tp_Default
      );

      switch ($value['banner_dinamico_tipolista']) {
        case Type_ModulesListBanner::Tp_Bestseller:
          $results = $this->model_catalog_product->getBestSellerProducts($value['banner_dinamico_quantidade']);
          $arrayResult = array_merge($arrayResult, $this->setArrayProducts($results, $value));
          break;
        case Type_ModulesListBanner::Tp_Latest:
          $results = $this->model_catalog_product->getProducts($dataDefault);
          $arrayResult = array_merge($arrayResult, $this->setArrayProducts($results, $value));
          break;
        case Type_ModulesListBanner::Tp_Random:
          $results = $this->model_catalog_product->getRProducts($dataDefault);
          $arrayResult = array_merge($arrayResult, $this->setArrayProducts($results, $value));
          break;
        case Type_ModulesListBanner::Tp_ProductViewedAll:
          $data = array(
            'sort' => 'p.viewed',
            'start' => 0,
            'limit' => $value['banner_dinamico_quantidade'],
            'filter_aviseme' => $this->getStatusAviseme(),
            'viewed' => true,
            'filter_content' => (ftr_geral::isIsset($this->config->get('config_setting_search_name'))) ? $this->config->get('config_setting_search_name') : Type_FilterContent::Tp_Default
          );

          $results = $this->model_catalog_product->getProducts($data);
          $arrayResult = array_merge($arrayResult, $this->setArrayProducts($results, $value));
          break;
        case Type_ModulesListBanner::Tp_ProductVisualized:
          if (isset($this->session->data['product_visualized']) && ($this->config->get('product_visualized_status'))) {
            $data = array(
              'start' => 0,
              'limit' => $value['banner_dinamico_quantidade'],
              'filter_quantity' => $this->getStatusAviseme()
            );
            $results = $this->productvisualized->getProducts($data);
            $arrayResult = array_merge($arrayResult, $this->setArrayProducts($results, $value));
          }
          break;
      }
    }
    return $arrayResult;
  }

  public function setArrayProducts($results, $value)
  {

    $arrayAux = array();
    foreach ($results as $key => $result) {
      if (isset($value['banner_dinamico_model']) && $value['banner_dinamico_model'] == 'model-a') {
        $banner_dinamico_model = 'model-' . rand(1, 4);
      } else {
        $banner_dinamico_model = $value['banner_dinamico_model'];
      }

      $arrayAux[$key]['product_id'] = $result['product_id'];
      $arrayAux[$key]['banner_model'] = $banner_dinamico_model;
      $arrayAux[$key]['banner_order'] = $value['banner_dinamico_ordem'];
      $arrayAux[$key]['banner_group_order'] = $value['banner_group_order'] ?? 0;
      $arrayAux[$key]['date_initial'] = $value['banner_dinamico_date_initial'] ?? null;
      $arrayAux[$key]['date_end'] = $value['banner_dinamico_date_end'] ?? null;
    }

    return $arrayAux;
  }

  public function getStatusAviseme()
  {
    $aviseme_status = Type_Status::Tp_Desabilitado;
    if (ftr_geral::isIsset($this->config->get('avise_me_status'))) {
      if ($this->config->get('config_stock_checkout')) {
        $aviseme_status = Type_Status::Tp_Desabilitado;
      } else {
        $aviseme_status = $this->config->get('avise_me_status');
      }
    }
    return $aviseme_status;
  }

}
