<?php

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

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

    public function getProductGridLink()
    {
        $this->load->model('catalog/product');

        $product_id       = $this->request->get['product_id']       ?? false;
        $color_id         = $this->request->get['color_id']         ?? false;
        $size_id          = $this->request->get['size_id']          ?? false;
        $specification_id = $this->request->get['specification_id'] ?? false;

        $keys = [
            'search',
            'tag',
            'description',
            'category_id',
            'sub_category',
            'sort',
            'order',
            'limit',
            'filcolor',
            'filsize',
            'filspecification',
            'path',
            'manufacturer_id',
            'filbrand',
            'color_id',
            'name',
            'index',
            'price_initial',
            'price_laste',
            'filrange'
        ];

        $params = [];

        if ($product_id) {
            $gradeId = $this->model_catalog_product->getIDProductGrid($product_id);
            $productResult = $this->model_catalog_product->getProductdGrade($color_id, $size_id, $specification_id, $gradeId);

            if ($productResult['product_id']) {
                $params['product_id'] = $productResult['product_id'];
            }

            if ($size_id && $productResult['sizeexists']) {
                array_push($keys, 'size_id');
            }

            if ($specification_id && $productResult['specificationexists']) {
                array_push($keys, 'specification_id');
            }
        }

        $params = array_merge(
            $params,
            array_filter($this->request->get, function ($key) use ($keys) {
                return in_array($key, $keys);
            }, ARRAY_FILTER_USE_KEY)
        );

        $route = $this->request->get['route2'] ?? "product/product";
        $urlGet = http_build_query($params);

        if (isset($this->request->get['quick_view']) && $this->request->get['quick_view']) {
            $this->request->get['product_id'] = $productResult['product_id'];
            unset($this->request->get['quick_view']);
            $this->quickView();
        } else {
            $this->isAjax = isset($this->request->get['ajax']) && $this->request->get['ajax'];
            $urlFinal = $this->url->link($route, $urlGet);

            if ($this->isAjax) {
                $this->redirect($urlFinal . '&ajax=1');
            } else {
                return $this->response->setOutput($urlFinal);
            }
        }
    }

    public function index()
    {
        $this->data['futuraquantidadeatacado_status'] = $this->config->get('futuraquantidadeatacado_status');

        $this->load->model('localisation/zone');
        $this->data['zones_id'] = $this->model_localisation_zone->getZonesByCountryId(Type_PaisId::Tp_Brasil);
        $this->load->library('google_tracking_code');

        $google_tracking_code = new GoogleTrackingCode($this->registry);

        if (isset($this->request->post['zone_id'])) {
            $this->data['zone_id'] = $this->request->post['zone_id'];
        } elseif (isset($this->session->data['shipping_zone_id'])) {
            $this->data['zone_id'] = $this->session->data['shipping_zone_id'];
        } else {
            $this->data['zone_id'] = '';
        }

        $this->app();

        parent::loadScript();

        parent::loadStyle();

        parent::index();

        parent::getDadosProduto();

        parent::getProductOption();

        parent::getBreadcrumbs();

        parent::getGrade();

        parent::getImages();

        parent::getVideos();

        $this->data['ferramentas_facebook'] = ($this->config->get('wg24_seo_fer_facebook_status') == 'enable' && !$this->config->get('wg24_seo_fer_facebook_pixel') == '') ? 1 : 0;
        $this->data['google_analytics'] = $google_tracking_code->getGATrackingCodes();

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

        /*não remover essa validação para não bugar a exibição do produto no delphi */
        if (isset($this->request->get['delphi'])) {
            $this->data['delphi'] = true;
        } else {
            $this->data['delphi'] = false;
        }
        /*registra as visualizações para o modulo quem viu, tambem viu */
        if($this->customer->isLogged()){
            $this->load->model('catalog/product_who_saw');
            $this->model_catalog_product_who_saw->storeProductVizualized($this->request->get['product_id'], $this->customer->getId());
        }

        $this->data['pagseguro_parcela'] = $this->config->get('pagseguro_parcela');
        $this->data['pagseguro_status'] = $this->config->get('pagseguro_status');
        if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
            $this->data['config_customer_price'] = true;
        } else {
            $this->data['config_customer_price'] = false;
        }

        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->cart->getProducts()[$this->request->get['product_id'] . '::']) ? $this->cart->getProducts()[$this->request->get['product_id'] . '::']['quantity'] : false;

            if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                $this->data['exibe_frete'] = 1;
            } else {
                $this->data['exibe_frete'] = 0;
            }

            $discounts = $this->model_catalog_product->getProductDiscounts($this->request->get['product_id']);

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

            foreach ($discounts as $discount) {
                $this->data['discounts'][] = array(
                    'quantity' => $discount['quantity'],
                    'price' => $this->currency->format($discount['price']),
                    'text_discounts' => sprintf($this->data['text_discount'], $discount['quantity'], $discount['price'])
                );
            }

            $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['futura_preco_dinamico_produto'] = $this->getChild('product/product/precodinamico');

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

            if ($this->config->get('fidelity_status')) {
                $this->load->dmodel('fidelity/fidelity');
                $config = $this->dmodel_fidelity_fidelity->getConfiFidelity();

                if ($config['tipo_pontuacao'] == Type_FidelityPoints::Tp_ValorVenda) {
                    $pontos = (round($this->data['pr'] / $config['valor_venda']) * $config['pontos']);
                    if ($pontos) {
                        $this->data['pontos'] = sprintf($this->language->get('text_pontos'), $pontos);
                    }
                } else {
                    $result = $this->dmodel_fidelity_fidelity->getCategoryPointsByProductId($this->request->get['product_id']);
                    if (isset($result['pontos']) && ($result['pontos'] > 0)) {
                        $this->data['pontos'] = sprintf($this->language->get('text_pontos'), $result['pontos']);
                    } else {
                        $this->data['pontos'] = false;
                    }
                }
            }

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

            $this->children = parent::getChildren();
            
            $dataInfo = [
                "productId" => $this->data['product_id'],
                "productName" => $this->data['product_name'],
                "productBrand" => $this->data['manufacturer_product'],
                "value" => $this->data['vValue'],
                "futuraGradeStatus" => $this->data['futuragrade_status'],
                "stock_checkout" => $this->data['config_stock_checkout'],
                "tipo_ex_cor" => isset($this->data['tipo_ex_cor'])  ? $this->data['tipo_ex_cor'] : 0,
                "typeZoom" => $this->data['type_zoom'],
                "facebook" => $this->data['ferramentas_facebook'],
                "types_zoom" => Type_TipoZoom::getEnumListConst(),
                "product_show_type" => $this->config->get('product_show_type'),
                "type_productshow" => Type_ProductShow::getEnumListConst(),
                "googleAnalytics" => json_encode($this->data['google_analytics']),
                "thumb" => $this->data['thumb']
            ];


            $dataInfo["carousel"][] = $this->data['popup'];

            foreach($this->data['images'] as $image){
                $dataInfo["carousel"][] = $image['popup'];
            }

            $this->data["model"] = $this->config->get('model');
            $this->data["product_show_type"] = $this->config->get('product_show_type');
            $this->data["type_productshow"] = Type_ProductShow::getEnumListConst();

            $this->data['carousel'] = $dataInfo["carousel"];

            $this->data['dataInfo'] = json_encode($dataInfo, JSON_HEX_APOS);

            $this->isAjax = isset($this->request->get['ajax']) && $this->request->get['ajax'];

            if ($this->isAjax) {
                $protocolo = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']=="on") ? "https" : "http");
                $url = "$protocolo://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                $this->response->setOutputJson([
                    'url' => $url,
                    'html' => $this->render('base/product_content')
                ]);
            } else {
                $this->response->setOutput($this->render('product/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, 10);

        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',
                'public/js/postcode.js'
            ));
        }
    }
}
