<?php

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

class ControllerFidelityProduct extends ControllerProductProductPage
{
  private $error = array();

  public function index()
  {

    $this->app();

    parent::loadScript();
    $this->document->addScript(array(
      'catalog/view/theme/vista/js/page.fidelity.js'
    ));

    parent::loadStyle();

    parent::index();

    parent::getDadosProduto();

    parent::getProductOption();

    $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'      => 'Resgatar Pontos',
      'href'      => $this->url->link('fidelity/category','','NONSSL'),
      'separator' => $this->language->get('text_separator')
    );

    $this->data['breadcrumbs'][] = array(
      'text'      => $this->data['product_name'],
      'href'      => $this->url->link('fidelity/product', $this->getUrlParameters() . '&product_id=' . $this->request->get['product_id']),
      'separator' => $this->language->get('text_separator')
    );

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

    parent::getGrade(['fidelity' => true]);

    parent::getImages();

    parent::getVideos();

    $this->data['vValue'] = $this->model_catalog_product->getProductPrice($this->request->get['product_id']);


    if (parent::getProductInfo()) {

      $this->document->addLink($this->url->link('product/product', 'product_id=' . $this->request->get['product_id']), 'canonical');
      $this->document->addScript('catalog/view/javascript/jquery/tabs.js');
      $this->document->addScript('catalog/view/javascript/jquery/colorbox/jquery.colorbox-min.js');
      $this->document->addStyle('catalog/view/javascript/jquery/colorbox/colorbox.css');

      if ($this->data['thumb']) {
        $this->document->addProperty('og:image', $this->data['thumb']);
      } else {
        $this->document->addProperty('og:image', $this->data['popup']);
      }

      $this->data['product_id'] = $this->request->get['product_id'];
      $this->data['notification_value'] = isset($this->fidelitycart->getProducts()[$this->request->get['product_id'] . '::']) ? $this->fidelitycart->getProducts()[$this->request->get['product_id'] . '::']['quantity'] : false;
      $this->data['review_status'] = ($this->config->get('config_rating_status') == Type_Status::Tp_Habilitado) ? true : false;
      $this->data['attribute_groups'] = $this->model_catalog_product->getProductAttributes($this->request->get['product_id']);
      $this->data['text_payment_profile'] = $this->language->get('text_payment_profile');
      $this->data['route2'] = $this->request->get['route'];//usado para fazer o link da grade

      $this->model_catalog_product->updateViewed($this->request->get['product_id']);

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

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

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

  public function review()
  {

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

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

    if (isset($this->data['status']) && ($this->data['status'])) {
      $this->language->load('product/avise_me');
    }

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

    $this->data['text_on'] = $this->language->get('text_on');
    $this->data['text_no_reviews'] = $this->language->get('text_no_reviews');

    if (isset($this->request->get['page'])) {
      $page = $this->request->get['page'];
    } else {
      $page = 1;
    }

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

    $review_total = $this->model_catalog_review->getTotalReviewsByProductId($this->request->get['product_id']);

    $results = $this->model_catalog_review->getReviewsByProductId($this->request->get['product_id'], ($page - 1) * 5, 5);

    foreach ($results as $result) {
      $this->data['reviews'][] = array(
        'author' => $result['author'],
        'text' => $result['text'],
        'rating' => (int)$result['rating'],
        'reviews' => sprintf($this->language->get('text_reviews'), (int)$review_total),
        'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
      );
    }

    $pagination = new Pagination();
    $pagination->total = $review_total;
    $pagination->page = $page;
    $pagination->limit = 5;
    $pagination->text = $this->language->get('text_pagination');
    $pagination->url = $this->url->link('product/product/review', 'product_id=' . $this->request->get['product_id'] . '&page={page}');

    $this->data['pagination'] = $pagination->render();

    $this->response->setOutput($this->render('product/review'));
  }

  public function getRecurringDescription()
  {

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

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

    if (isset($this->data['status']) && ($this->data['status'])) {
      $this->language->load('product/avise_me');
    }

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

    if (isset($this->request->post['product_id'])) {
      $product_id = $this->request->post['product_id'];
    } else {
      $product_id = 0;
    }

    if (isset($this->request->post['profile_id'])) {
      $profile_id = $this->request->post['profile_id'];
    } else {
      $profile_id = 0;
    }

    if (isset($this->request->post['quantity'])) {
      $quantity = $this->request->post['quantity'];
    } else {
      $quantity = 1;
    }

    $product_info = $this->model_catalog_product->getProduct($product_id);
    $profile_info = $this->model_catalog_product->getProfile($product_id, $profile_id);

    $json = array();

    if ($product_info && $profile_info) {

      if (!$json) {
        $frequencies = array(
          'day' => $this->language->get('text_day'),
          'week' => $this->language->get('text_week'),
          'semi_month' => $this->language->get('text_semi_month'),
          'month' => $this->language->get('text_month'),
          'year' => $this->language->get('text_year'),
        );

        if ($profile_info['trial_status'] == 1) {
          $price = $this->currency->format($profile_info['trial_price'] * $quantity);
          $trial_text = sprintf($this->language->get('text_trial_description'), $price, $profile_info['trial_cycle'], $frequencies[$profile_info['trial_frequency']], $profile_info['trial_duration']) . ' ';
        } else {
          $trial_text = '';
        }

        $price = $this->currency->format($profile_info['price'] * $quantity);

        if ($profile_info['duration']) {
          $text = $trial_text . sprintf($this->language->get('text_payment_description'), $price, $profile_info['cycle'], $frequencies[$profile_info['frequency']], $profile_info['duration']);
        } else {
          $text = $trial_text . sprintf($this->language->get('text_payment_until_canceled_description'), $price, $profile_info['cycle'], $frequencies[$profile_info['frequency']], $profile_info['duration']);
        }

        $json['success'] = $text;
      }
    }

    $this->response->setOutput(json_encode($json));
  }

  public function write()
  {

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

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

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

    $json = array();

    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      if (empty($this->session->data['captcha']) || ($this->session->data['captcha'] != $this->request->post['captcha'])) {
        $json['warning'] = $this->language->get('error_captcha');
        $json['error']['captcha'] = $this->language->get('error_captcha');
      }

      if ((utf8_strlen($this->request->post['text']) < 25) || (utf8_strlen($this->request->post['text']) > 1000)) {
        $json['warning'] = $this->language->get('error_text');
        $json['error']['text'] = $this->language->get('error_text');
      }

      if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 25)) {
        $json['warning'] = $this->language->get('error_name');
        $json['error']['name'] = $this->language->get('error_name');
      }

      if (!isset($json['error'])) {
        $this->model_catalog_review->addReview($this->request->get['product_id'], $this->request->post);

        $json['success'] = $this->language->get('text_success');
      }
    }

    $this->response->setOutput(json_encode($json));
  }

  public function captcha()
  {
    $this->load->library('captcha');

    $captcha = new Captcha();

    $this->session->data['captcha'] = $captcha->getCode();

    $captcha->showImage();
  }

  public function upload()
  {

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

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

    if (isset($this->data['status']) && ($this->data['status'])) {
      $this->language->load('product/avise_me');
    }


    $json = array();

    if (!empty($this->request->files['file']['name'])) {
      $filename = basename(preg_replace('/[^a-zA-Z0-9\.\-\s+]/', '', html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8')));

      if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 64)) {
        $json['error'] = $this->language->get('error_filename');
      }

      // Allowed file extension types
      $allowed = array();

      $filetypes = explode("\n", $this->config->get('config_file_extension_allowed'));

      foreach ($filetypes as $filetype) {
        $allowed[] = trim($filetype);
      }

      if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
        $json['error'] = $this->language->get('error_filetype');
      }

      // Allowed file mime types
      $allowed = array();

      $filetypes = explode("\n", $this->config->get('config_file_mime_allowed'));

      foreach ($filetypes as $filetype) {
        $allowed[] = trim($filetype);
      }

      if (!in_array($this->request->files['file']['type'], $allowed)) {
        $json['error'] = $this->language->get('error_filetype');
      }

      if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
        $json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
      }
    } else {
      $json['error'] = $this->language->get('error_upload');
    }

    if (!$json && is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
      $file = basename($filename) . '.' . md5(mt_rand());

      // Hide the uploaded file name so people can not link to it directly.
      $json['file'] = $this->encryption->encrypt($file);

      move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $file);

      $json['success'] = $this->language->get('text_upload');
    }

    $this->response->setOutput(json_encode($json));
  }

  public function quickView()
  {
    $this->language->load('product/product_quick_view');
    $this->load->helper('ftr_geral');

    $this->data['text_go_product_page'] = $this->language->get('text_go_product_page');
    $this->data['text_close'] = $this->language->get('text_close');
    $this->data['text_choose_size'] = $this->language->get('text_choose_size');
    $this->data['text_size_error'] = $this->language->get('text_size_error');
    $this->data['text_choose_specification'] = $this->language->get('text_choose_specification');
    $this->data['text_specification_error'] = $this->language->get('text_specification_error');

    parent::index();

    parent::getDadosProduto();

    parent::getProductOption();

    parent::getGrade();

    parent::getImages();

    parent::getVideos();

    $this->data['notification_value'] = isset($this->cart->getProducts()[$this->request->get['product_id'] . '::']) ? $this->cart->getProducts()[$this->request->get['product_id'] . '::']['quantity'] : false;

    $this->data['description'] = ftr_geral::formatText($this->data['description'], 400);

    $this->data['customerIsLogged'] = $this->customer->isLogged();

    $this->data['encodeSelected'] = json_encode($this->data['selected']);

    $this->data['futura_preco_dinamico_produto'] = $this->getChild('product/product/precodinamico');
    $this->template = parent::getTemplate('product/product_quick_view.twig');

    $this->response->setOutput($this->render());
  }

  public function precodinamico()
  {

    parent::index();

    parent::getDadosProduto();

    $this->data['futura_preco_dinamico_produto'] = parent::getPrecoDinamico();

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

    $this->response->setOutput($this->render());

  }

  public function app()
  {
    if ($this->ftrgeralregistry->isApp()) {
      $this->document->addScriptApp(array(
        'catalog/view/theme/vista/plugins/photoswipe/photoswipe.min.js',
        'catalog/view/theme/vista/plugins/photoswipe/photoswipe-ui-default.min.js',
        'catalog/view/theme/vista/js/jquery/jquery.validate.js',
        'catalog/view/theme/vista/js/jquery/additional-methods.js',
        'catalog/view/theme/vista/js/jquery/jquery.validate.futura-methods.js',
        'catalog/view/theme/vista/js/jquery/localization/messages_pt_BR.js',
        'catalog/view/theme/appmobile/public/js/jquery.mask.js',
        'catalog/view/theme/appmobile/js/page.product.js',
        'catalog/view/theme/appmobile/js/template/fidelity/fidelity.js'
      ));
    }

  }

}
