<?php

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

    public function index() {
        $this->load->language('product/product');

        $data['breadcrumbs'] = array();
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home')
        );

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

        if (isset($this->request->get['path'])) {
            $path = '';

            $parts = explode('_', (string)$this->request->get['path']);

            $category_id = (int)array_pop($parts);

            foreach ($parts as $path_id) {
                if (!$path) {
                    $path = $path_id;
                } else {
                    $path .= '_' . $path_id;
                }

                $category_info = $this->model_catalog_category->getCategory($path_id);

                if ($category_info) {
                    $data['breadcrumbs'][] = array(
                        'text' => $category_info['name'],
                        'href' => $this->url->link('product/category', 'path=' . $path)
                    );
                }
            }

            // Set the last category breadcrumb
            $category_info = $this->model_catalog_category->getCategory($category_id);

            if ($category_info) {
                $url = '';

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

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

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

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

                $data['breadcrumbs'][] = array(
                    'text' => $category_info['name'],
                    'href' => $this->url->link('product/category', 'path=' . $this->request->get['path'] . $url)
                );
            }
        }


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

        if (isset($this->request->get['manufacturer_id'])) {
            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_brand'),
                'href' => $this->url->link('product/manufacturer')
            );

            $url = '';

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

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

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

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

            $manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($this->request->get['manufacturer_id']);

            if ($manufacturer_info) {
                $data['breadcrumbs'][] = array(
                    'text' => $manufacturer_info['name'],
                    'href' => $this->url->link('product/manufacturer/info', 'manufacturer_id=' . $this->request->get['manufacturer_id'] . $url)
                );
            }
        }

        if (isset($this->request->get['search']) || isset($this->request->get['tag'])) {
            $url = '';

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

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

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

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

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

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

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

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

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

            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_search'),
                'href' => $this->url->link('product/search', $url)
            );
        }

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

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

        $product_info = $this->model_catalog_product->getProduct($product_id);

        if ($product_info) {
            $url = '';

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

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

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

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

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

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

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

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

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

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

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

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

            if ($product_info['meta_title']) {
                $this->document->setTitle($product_info['meta_title']);
            } else {
                $name_length = utf8_strlen($product_info['name']);
                $meta_title = '';

                $meta_title = $this->request->clean($meta_title);
                $this->document->setTitle($product_info['name'].$meta_title);
            }

            if ($product_info['meta_h1']) {
                $data['heading_title'] = $product_info['meta_h1'];
            } else {
                $data['heading_title'] = $product_info['name'];
            }

            $this->document->setKeywords($product_info['meta_keyword']);
            $this->document->addLink($this->url->link('product/product', 'product_id=' . $this->request->get['product_id']), 'canonical');
            $this->document->addScript('catalog/view/javascript/jquery/magnific/jquery.magnific-popup.min.js');
            $this->document->addScript('catalog/view/javascript/slick.min.js');
            $this->document->addStyle('catalog/view/javascript/jquery/magnific/magnific-popup.css');
            $this->document->addScript('catalog/view/javascript/jquery/datetimepicker/moment.js');
            $this->document->addScript('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.js');
            $this->document->addStyle('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.css');

            $data['text_select']       = $this->language->get('text_select');
            $data['text_manufacturer'] = $this->language->get('text_manufacturer');
            $data['text_model']        = $this->language->get('text_model');
            $data['text_sku']          = $this->language->get('text_sku');
            $data['text_reward']       = $this->language->get('text_reward');
            $data['text_points']       = $this->language->get('text_points');
            $data['text_stock']        = $this->language->get('text_stock');
            $data['text_discount']     = $this->language->get('text_discount');
            $data['text_tax']          = $this->language->get('text_tax');
            $data['text_option']       = $this->language->get('text_option');
            $data['text_minimum']      = sprintf($this->language->get('text_minimum'), $product_info['minimum']);
            $data['text_write_title']  = $this->language->get('text_write_title');
            $data['text_leave_feedback']  = $this->language->get('text_leave_feedback');
            $data['text_write']        = $this->language->get('text_write');
            $data['text_login']        = sprintf($this->language->get('text_login'), $this->url->link('account/login', '', true), $this->url->link('account/register', '', true));
            $data['text_note']         = $this->language->get('text_note');
            $data['text_tags']         = $this->language->get('text_tags');
            $data['text_related']      = $this->language->get('text_related');
            $data['text_payment_recurring'] = $this->language->get('text_payment_recurring');
            $data['text_loading']      = $this->language->get('text_loading');
            $data['text_benefits']     = $this->language->get('text_benefits');
            $data['text_gift']         = $this->language->get('text_gift');
            $data['text_fo']           = $this->language->get('text_fo');     

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

            $data['entry_qty']    = $this->language->get('entry_qty');
            $data['entry_name']   = $this->language->get('entry_name');
            $data['entry_review'] = $this->language->get('entry_review');
            $data['entry_rating'] = $this->language->get('entry_rating');
            $data['entry_good']   = $this->language->get('entry_good');
            $data['entry_bad']    = $this->language->get('entry_bad');
            $data['text_more']    = $this->language->get('text_more');
            $data['text_less']    = $this->language->get('text_less');

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

            $data['text_tab_delivery']    = $this->language->get('text_tab_delivery');
            $data['text_tab_payment']     = $this->language->get('text_tab_payment');
            $data['text_tab_varranty']    = $this->language->get('text_tab_varranty');

            $data['text_review_next']    = $this->language->get('text_review_next');
            $data['text_no_review']      = $this->language->get('text_no_review');
            $data['text_way']            = $this->language->get('text_way');
            $data['text_charact']        = $this->language->get('text_charact');
            $data['text_analog']         = $this->language->get('text_analog');

            //Custom
            $data['text_product_description'] = $this->language->get('text_product_description');
            $data['text_product_gift']        = $this->language->get('text_product_gift');
            $data['text_product_promotional_offer'] = $this->language->get('text_product_promotional_offer');
            $data['text_product_features']    = $this->language->get('text_product_features');
            $data['text_product_reviews']     = $this->language->get('text_product_reviews');
            $data['text_product_low_price_guarantee']  = $this->language->get('text_product_low_price_guarantee');
            $data['text_product_gifts_every_customer'] = $this->language->get('text_product_gifts_every_customer');
            $data['text_product_our_pick']             = $this->language->get('text_product_our_pick');
            $data['text_product_free_shipping']        = $this->language->get('text_product_free_shipping');
            $data['text_product_availability_in_stor'] = $this->language->get('text_product_availability_in_stor');

            $data['text_points_per_purchase'] = $this->language->get('text_points_per_purchase');
            $data['text_more_about_points']   = $this->language->get('text_more_about_points');

            $data['button_cart']     = $this->language->get('button_cart');
            $data['button_cart1']     = $this->language->get('button_cart1');
            $data['button_wishlist'] = $this->language->get('button_wishlist');
            $data['button_compare']  = $this->language->get('button_compare');
            $data['button_upload']   = $this->language->get('button_upload');
            $data['button_continue'] = $this->language->get('button_continue');

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

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

            $data['tab_description'] = $this->language->get('tab_description');
            $data['tab_attribute']   = $this->language->get('tab_attribute');
            $data['tab_review']      = sprintf($this->language->get('tab_review'), $product_info['reviews']);
            $data['review_count']    = $product_info['reviews'];

            $data['product_id']    = (int)$this->request->get['product_id'];
            $data['manufacturer']  = $product_info['manufacturer'];
            $data['manufacturers'] = $this->url->link('product/manufacturer/info', 'manufacturer_id=' . $product_info['manufacturer_id']);

            $data['model']   = $product_info['model'];
            $data['archive'] = $product_info['archive'];
            $data['reward']  = $product_info['reward'];
            $data['points']  = $product_info['points'];

            $data['description'] = html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8');
            $data['need_more_btn'] = utf8_strlen(strip_tags(html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8'))) > 1000 ? 1 : 0;
            $data['sticker']     = $this->getStickers($product_info['product_id']);

            $data['product_quantity'] = $product_info['quantity'];


            if (($product_info['quantity'] <= 0) || $product_info['archive']) {
                $data['stock'] = $product_info['stock_status'];
            } elseif ($this->config->get('config_stock_display')) {
                $data['stock'] = $product_info['quantity'];
            } else {
                $data['stock'] = $this->language->get('text_instock');
            }

            $data['product_quantity'] = $product_info['quantity'];

            $data['in_wishlist'] = false;

            if ($this->customer->isLogged()) {
                $this->load->model('account/wishlist');

                if ($this->model_account_wishlist->getTotalWishlist()) {
                    $wish_products = $this->model_account_wishlist->getWishlist();

                    if (!empty($wish_products)) {
                        foreach ($wish_products as $product) {
                            if ($product['product_id'] == $product_id) {
                                $data['in_wishlist'] = true;
                            }
                        }
                    }
                }
            }

            $this->load->model('extension/module');
 
            $module_delivery = $this->model_extension_module->getModule(117);

            if ($module_delivery && $module_delivery['status']) {
                $module_delivery_data = $module_delivery['module_description'][$this->config->get('config_language_id')]['description'];

                if ($module_delivery_data) {
                    $data['module_delivery_data'] = html_entity_decode($module_delivery_data, ENT_QUOTES, 'UTF-8');
                }
            }

            $module_paymeny = $this->model_extension_module->getModule(119);

            if ($module_paymeny && $module_paymeny['status']) {
                $module_paymeny_data = $module_paymeny['module_description'][$this->config->get('config_language_id')]['description'];

                if ($module_paymeny_data) {
                    $data['module_paymeny_data'] = html_entity_decode($module_paymeny_data, ENT_QUOTES, 'UTF-8');
                }
            }

            $module_varranty = $this->model_extension_module->getModule(118);

            if ($module_varranty && $module_varranty['status']) {
                $module_varranty_data = $module_varranty['module_description'][$this->config->get('config_language_id')]['description'];

                if ($module_varranty_data) {
                    $data['module_varranty_data'] = html_entity_decode($module_varranty_data, ENT_QUOTES, 'UTF-8');
                }
            }

            $this->load->model('tool/image');

            if ($product_info['image']) {
                $data['thumb'] = $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_thumb_width'), $this->config->get($this->config->get('config_theme') . '_image_thumb_height'));

                $data['thumb_small'] = $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_additional_width'), $this->config->get($this->config->get('config_theme') . '_image_additional_height'));

                $data['popup'] = $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height'));
            } else {
                $data['popup'] = '';
                $data['thumb'] = '';
                $data['thumb_small'] = '';
            }

            $data['image_width']  = $this->config->get($this->config->get('config_theme') . '_image_thumb_width');
            $data['image_height'] = $this->config->get($this->config->get('config_theme') . '_image_thumb_height');

			$data['video'] = $product_info['video'];



            //разметка видео
            if ($data['video']) {
            $vimeo_url    = $data['video'];
            $vimeo_data   = json_decode(file_get_contents("https://vimeo.com/api/oembed.json?url=" . urlencode($vimeo_url)), true);

            if ($vimeo_data) {
                $durationSec = $vimeo_data['duration'];                         // в секундах
                $durationISO = "PT" . floor($durationSec/60) . "M" . ($durationSec % 60) . "S";

                $uploadDateRaw = $vimeo_data['upload_date'];
                $uploadDateISO = date('c', strtotime($uploadDateRaw));

                $data['vimeo_thumb']     = $vimeo_data['thumbnail_url'];        // здесь берём из Vimeo
                $data['vimeo_duration']  = $durationISO;
                $data['vimeo_uploadAt']  = $uploadDateISO ?? null;
            }
        }
            //разметка видео


            $data['images'] = array();
            $results = $this->model_catalog_product->getProductImages($this->request->get['product_id']);

            if ($results) {
                $data['images'][] = array(
                    'popup'     => $data['popup'],
                    'thumb'     => $data['thumb_small'],
                    'thumb_big' => $data['thumb'],
                );
                foreach ($results as $result) {
                    $data['images'][] = array(
                        'popup'     => $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height')),
                        'thumb'     => $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_additional_width'), $this->config->get($this->config->get('config_theme') . '_image_additional_height')),
                        'thumb_big' => $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_thumb_width'), $this->config->get($this->config->get('config_theme') . '_image_thumb_height'))
                    );
                }
            } else {
                if ($product_info['image']) {
                    $data['images'][] = array(
                        'popup'     => $data['popup'],
                        'thumb'     => $data['thumb'],
                        'thumb_big' => $data['popup']
                    );
                }
            }

            // echo '<pre>';
            // print_r($data['images']);
            // echo "</pre>";

            $data['sub_image_width']  = $this->config->get($this->config->get('config_theme') . '_image_additional_width');
            $data['sub_image_height'] = $this->config->get($this->config->get('config_theme') . '_image_additional_height');

            if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                $data['price'] = $this->currency->format($this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
            } else {
                $data['price'] = false;
            }

            if ((float)$product_info['special']) {
                $data['special'] = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
            } else {
                $data['special'] = false;
            }

            $data['gifts'] = array();

            //Имя блока подарков
            $gift_data = $this->load->controller('extension/module/giftteaser');

            $gift_name = $gift_data['data']['FreeGiftLabel'];

            foreach ($_SESSION as $session_item) {
                if ($session_item['langmark_multi_num'] == 1) {
                    $data['gift_text'] = $gift_name[1];
                }
                if ($session_item['langmark_multi_num'] == 0) {
                    $data['gift_text'] = $gift_name[3];
                }
            }
            //Имя блока подарков

            $results = $this->cache->get('product_gifts');

            if (!$product_data) {
                $results = $this->model_catalog_product->getGifts();

                $this->cache->set('product_gifts', $results);
            }

            foreach ($results as $result) {
                if (isset($result['condition_properties'])) {
                    $properties = unserialize($result['condition_properties']);
                    if (!empty($properties['total']) && ($properties['total'] <= ($product_info['special'] ? $product_info['special'] : $product_info['price']))) {

                        $gift_info = $this->cache->get('product_gift_info_' . $result['item_id']);

                        if (!$gift_info) {
                            $gift_info = $this->model_catalog_product->getProduct($result['item_id']);

                            $this->cache->set('product_gift_info_' . $result['item_id'], $gift_info);
                        }

                        if ($gift_info['image']) {
                            $gift_image = $this->model_tool_image->resize($gift_info['image'], $this->config->get($this->config->get('config_theme') . '_image_related_width'), $this->config->get($this->config->get('config_theme') . '_image_related_height'));
                        } else {
                            $gift_image = $this->model_tool_image->resize('placeholder.png', $this->config->get($this->config->get('config_theme') . '_image_related_width'), $this->config->get($this->config->get('config_theme') . '_image_related_height'));
                        }
                        $data['gifts'][] = array(
                            'thumb' => $gift_image,
                            'name'  => $gift_info['name'],
                            'href'  => $this->url->link('product/product', 'product_id=' . $result['item_id']),
                        );
                    }
                }
            }

            if ($product_info['meta_description']) {
                $this->document->setDescription($product_info['meta_description']);
            } else {
                $price = $data['special']?$data['special']:$data['price'];
                $name_length = utf8_strlen($product_info['name'].$price);
                $meta_descr = '';

                if ($name_length < 85 ) {
                    $meta_descr  = '. Заказать за '.$price.' Секс Шоп "Афродита". Доставка по Украине! Гарантия Качества и Низкой Цены!  ☎ (044) 222-80-41';
                } elseif ($name_length < 100 ) {
                    $meta_descr  = '  Заказать за '.$price.' Секс Шоп "Афродита" Гарантия Качества и Низкой Цены!  ☎ (044) 222-80-41';
                } elseif ($name_length < 157 ) {
                    $meta_descr  = '  Заказать за '.$price.' Секс Шоп "Афродита", Киев';
                } elseif ($name_length < 171 ) {
                    $meta_descr = '  Секс Шоп "Афродита", Киев';
                }

                $meta_descr = $this->request->clean($meta_descr);
                $this->document->setDescription($product_info['name'].$meta_descr);
            }

            if ($this->config->get('config_tax')) {
                $data['tax'] = $this->currency->format((float)$product_info['special'] ? $product_info['special'] : $product_info['price'], $this->session->data['currency']);
            } else {
                $data['tax'] = false;
            }

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

            $data['discounts'] = array();

            foreach ($discounts as $discount) {
                $data['discounts'][] = array(
                    'quantity' => $discount['quantity'],
                    'price'    => $this->currency->format($this->tax->calculate($discount['price'], $product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency'])
                );
            }

            $productbenefits = $this->model_catalog_product->getProductBenefitsbyProductId($product_info['product_id']);

            $data['benefits'] = array();

            foreach ($productbenefits as $benefit) {
                if ($benefit['image'] && file_exists(DIR_IMAGE . $benefit['image'])) {
                    $bimage = $benefit['image'];
                    if ($benefit['type']) {
                        $bimage = $this->model_tool_image->resize($bimage, 25, 25);
                    } else {
                        $bimage = $this->model_tool_image->resize($bimage, 350, 140);
                    }
                } else {
                    $bimage = 'no_image.jpg';
                }
                $data['benefits'][] = array(
                    'benefit_id'        => $benefit['benefit_id'],
                    'name'              => $benefit['name'],
                    'description'       => strip_tags(html_entity_decode($benefit['description'])),
                    'thumb'             => $bimage,
                    'link'              => $benefit['link'],
                    'type'              => $benefit['type']
                );
            }

            $data['options'] = array();

            foreach ($this->model_catalog_product->getProductOptions($this->request->get['product_id']) as $option) {
                $product_option_value_data = array();

                foreach ($option['product_option_value'] as $option_value) {
                    if (!$option_value['subtract'] || ($option_value['quantity'] > 0)) {
                        if ((($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                            $price = $this->currency->format($this->tax->calculate($option_value['price'], $product_info['tax_class_id'], $this->config->get('config_tax') ? 'P' : false), $this->session->data['currency']);
                        } else {
                            $price = false;
                        }

                        $product_option_value_data[] = array(
                            'product_option_value_id' => $option_value['product_option_value_id'],
                            'option_value_id'         => $option_value['option_value_id'],
                            'name'                    => $option_value['name'],
                            'image'                   => $this->model_tool_image->resize($option_value['image'], 50, 50),
                            'price'                   => $price,
                            'price_prefix'            => $option_value['price_prefix']
                        );
                    }
                }

                $data['options'][] = array(
                    'product_option_id'    => $option['product_option_id'],
                    'product_option_value' => $product_option_value_data,
                    'option_id'            => $option['option_id'],
                    'name'                 => $option['name'],
                    'type'                 => $option['type'],
                    'value'                => $option['value'],
                    'required'             => $option['required']
                );
            }

            if ($product_info['minimum']) {
                $data['minimum'] = $product_info['minimum'];
            } else {
                $data['minimum'] = 1;
            }

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

            if ($this->config->get('config_review_guest') || $this->customer->isLogged()) {
                $data['review_guest'] = true;
            } else {
                $data['review_guest'] = false;
            }

            if ($this->customer->isLogged()) {
                $data['customer_name'] = $this->customer->getFirstName() . '&nbsp;' . $this->customer->getLastName();
            } else {
                $data['customer_name'] = '';
            }

            $data['text_reviews_tab'] = $this->language->get('text_reviews_tab');
            $data['text_video_tab']   = $this->language->get('text_video_tab');

            $data['reviews'] = sprintf($this->language->get('text_reviews'), (int)$product_info['reviews']);
            $data['rating']  = (int)$product_info['rating'];
            $data['moneymaker2_modules_quickorder_enabled'] = $this->config->get('moneymaker2_modules_quickorder_enabled');
            if ($data['moneymaker2_modules_quickorder_enabled']) {
                if ($product_info['image']) {
                    $data['quickorder_thumb'] = $this->model_tool_image->resize($product_info['image'], $this->config->get('moneymaker2_modules_quickorder_image_width'), $this->config->get('moneymaker2_modules_quickorder_image_height'));
                } else {
                    $data['quickorder_thumb'] = '';
                }
            }

            $data['attribute_groups'] = $this->model_catalog_product->getProductAttributes($this->request->get['product_id']);
            $data['warehouses']       = $this->model_catalog_product->getProductWarehouses($this->request->get['product_id']);

            $data['products'] = array();
            $results = $this->model_catalog_product->getProductRelated($this->request->get['product_id']);

                if(count($results) > 0) {
                    while (count($results) < 5) {
                        $results = array_merge($results, $results);
                    }
                }
              

            foreach ($results as $result) {
                if ($result['image']) {
                    $image = $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_related_width'), $this->config->get($this->config->get('config_theme') . '_image_related_height'));
                } else {
                    $image = $this->model_tool_image->resize('placeholder.png', $this->config->get($this->config->get('config_theme') . '_image_related_width'), $this->config->get($this->config->get('config_theme') . '_image_related_height'));
                }

                if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                    $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
                } else {
                    $price = false;
                }

                if ((float)$result['special']) {
                    $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
                } else {
                    $special = false;
                }

                $rating = (int)$result['rating'];

                $data['products'][] = array(
                    'product_id'  => $result['product_id'],
                    'thumb'       => $image,
                    'name'        => $result['name'],
                    'price'       => $price,
                    'special'     => $special,
                    'rating'      => $rating,
                    'reviews'     => $this->model_catalog_review->getTotalReviewsByProductId($result['product_id']),
                    'href'        => $this->url->link('product/product', 'product_id=' . $result['product_id'])
                );
            }
           
            $data['tags'] = array();

            if ($product_info['tag']) {
                $tags = explode(',', $product_info['tag']);

                foreach ($tags as $tag) {
                    $data['tags'][] = array(
                        'tag'  => trim($tag),
                        'href' => $this->url->link('product/search', 'tag=' . trim($tag))
                    );
                }
            }

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

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


            $data['column_left'] = $this->load->controller('common/column_left');
            $data['column_right'] = $this->load->controller('common/column_right');
            $data['content_top'] = $this->load->controller('common/content_top');
//             static $i = 1;
// $m = microtime(true);
// echo '<pre>';
// echo $i++ . '. ' . number_format(microtime(true) - $m, 2, '.', '') . PHP_EOL;
// echo '</pre>';
            $data['content_bottom'] = $this->load->controller('common/content_bottom'); //0.23
//             echo '<pre>';
// echo $i++ . '. ' . number_format(microtime(true) - $m, 2, '.', '') . PHP_EOL;
// echo '</pre>';
            $data['footer'] = $this->load->controller('common/footer');
            $data['header'] = $this->load->controller('common/header'); //0.24

            $data['product_tabs'] = array();
            $tabresults = $this->model_catalog_product->getproducttab($this->request->get['product_id']);
            foreach ($tabresults as $result) {
                $data['product_tabs'][] = array(
                    'product_tab_id' => $result['product_tab_id'],
                    'title' => $result['heading'],
                    'description' => html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8'),
                );
            }

            $data['random_products'] = false;
            $data['text_random_products'] = $this->language->get('text_random_products');
            $random_products = $this->model_catalog_product->getRandomProducts([3936,4118]);
            foreach ($random_products as $random_product) {
                $random_product_info = $this->model_catalog_product->getProduct($random_product);

                if ($random_product_info['image']) {
                    $image = $this->model_tool_image->resize($random_product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_related_width'), $this->config->get($this->config->get('config_theme') . '_image_related_height'));
                } else {
                    $image = $this->model_tool_image->resize('placeholder.png', $this->config->get($this->config->get('config_theme') . '_image_related_width'), $this->config->get($this->config->get('config_theme') . '_image_related_height'));
                }

                if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                    $price = $this->currency->format($this->tax->calculate($random_product_info['price'], $random_product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
                } else {
                    $price = false;
                }

                if ((float)$random_product_info['special']) {
                    $special = $this->currency->format($this->tax->calculate($random_product_info['special'], $random_product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
                } else {
                    $special = false;
                }

                $rating = (int)$random_product_info['rating'];

                $data['random_products'][] = array(
                    'product_id'  => $random_product_info['product_id'],
                    'thumb'       => $image,
                    'name'        => $random_product_info['name'],
                    'price'       => $price,
                    'special'     => $special,
                    'rating'      => $rating,
                    'reviews'     => $this->model_catalog_review->getTotalReviewsByProductId($random_product_info['product_id']),
                    'href'        => $this->url->link('product/product', 'product_id=' . $random_product_info['product_id'])
                );
            }

            // echo '<pre>';
            // print_r($data);
            // echo '</pre>';

            $this->response->setOutput($this->load->view('product/product', $data));
        } else {
            $url = '';

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

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

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

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

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

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

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

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

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

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

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

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

            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_error'),
                'href' => $this->url->link('product/product', $url . '&product_id=' . $product_id)
            );

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

            $data['heading_title'] = $this->language->get('text_error');

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

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

            $data['continue'] = $this->url->link('common/home');

            $this->response->addHeader($this->request->server['SERVER_PROTOCOL'] . ' 404 Not Found');

            $data['column_left'] = $this->load->controller('common/column_left');
            $data['column_right'] = $this->load->controller('common/column_right');
            $data['content_top'] = $this->load->controller('common/content_top');
            $data['content_bottom'] = $this->load->controller('common/content_bottom');
            $data['footer'] = $this->load->controller('common/footer');
            $data['header'] = $this->load->controller('common/header');

//            echo '<pre>';
//            print_r($data);
//            echo '</pre>';

            $this->response->setOutput($this->load->view('error/not_found', $data));
        }
    }

    public function review() {
        $this->load->language('product/product');

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

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

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

        $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) {
            $data['reviews'][] = array(
                'author'     => $result['author'],
                'text'       => nl2br($result['text']),
                'rating'     => (int)$result['rating'],
                '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->url = $this->url->link('product/product/review', 'product_id=' . $this->request->get['product_id'] . '&page={page}');

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

        $data['results'] = sprintf($this->language->get('text_pagination'), ($review_total) ? (($page - 1) * 5) + 1 : 0, ((($page - 1) * 5) > ($review_total - 5)) ? $review_total : ((($page - 1) * 5) + 5), $review_total, ceil($review_total / 5));

        $this->response->setOutput($this->load->view('product/review', $data));
    }

    public function write() {
        $this->load->language('product/product');

        $json = array();

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

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

            if (empty($this->request->post['rating']) || $this->request->post['rating'] < 0 || $this->request->post['rating'] > 5) {
                $json['error'] = $this->language->get('error_rating');
            }

            // Captcha
            if ($this->config->get($this->config->get('config_captcha') . '_status') && in_array('review', (array)$this->config->get('config_captcha_page'))) {
                $captcha = $this->load->controller('extension/captcha/' . $this->config->get('config_captcha') . '/validate');

                if ($captcha) {
                    $json['error'] = $captcha;
                }
            }

            if (!isset($json['error'])) {
                $this->load->model('catalog/review');

                $this->model_catalog_review->addReview($this->request->get['product_id'], $this->request->post);

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

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function getRecurringDescription() {
        $this->load->language('product/product');
        $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['recurring_id'])) {
            $recurring_id = $this->request->post['recurring_id'];
        } else {
            $recurring_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);
        $recurring_info = $this->model_catalog_product->getProfile($product_id, $recurring_id);

        $json = array();

        if ($product_info && $recurring_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 ($recurring_info['trial_status'] == 1) {
                    $price = $this->currency->format($this->tax->calculate($recurring_info['trial_price'] * $quantity, $product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
                    $trial_text = sprintf($this->language->get('text_trial_description'), $price, $recurring_info['trial_cycle'], $frequencies[$recurring_info['trial_frequency']], $recurring_info['trial_duration']) . ' ';
                } else {
                    $trial_text = '';
                }

                $price = $this->currency->format($this->tax->calculate($recurring_info['price'] * $quantity, $product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);

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

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

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    private function getStickers($product_id) {

        $stickers = $this->model_catalog_product->getProductStickerbyProductId($product_id) ;

        if (!$stickers) {
            return;
        }

        $data['stickers'] = array();

        foreach ($stickers as $sticker) {
            $data['stickers'][] = array(
                'position' => $sticker['position'],
                'image'    => HTTP_SERVER . 'image/' . $sticker['image']
            );
        }

        return $this->load->view('product/stickers', $data);

    }
}