<?php

class ControllerProductProduct extends Controller {

    private $error = array();
    

    private function parseText($node, $keyword, $dom, $link, $target = '', $tooltip = 0) {
        if (mb_strpos($node->nodeValue, $keyword) !== false) {
            $keywordOffset = mb_strpos($node->nodeValue, $keyword, 0, 'UTF-8');
            $newNode = $node->splitText($keywordOffset);
            $newNode->deleteData(0, mb_strlen($keyword, 'UTF-8'));
            $span = $dom->createElement('a', $keyword);
            if ($tooltip) {
                $span->setAttribute('href', '#');
                $span->setAttribute('style', 'text-decoration:none');
                $span->setAttribute('class', 'title');
                $span->setAttribute('title', $keyword . '|' . $link);
            } else {
                $span->setAttribute('href', $link);
                $span->setAttribute('target', $target);
                $span->setAttribute('style', 'text-decoration:none');
            }

            $node->parentNode->insertBefore($span, $newNode);
            $this->parseText($newNode, $keyword, $dom, $link, $target, $tooltip);
        }
    }

    protected function getReviewsFirstPage($product_id) {
        $this->load->language('product/product');
        $this->load->model('catalog/review');
        $data['text_no_reviews'] = $this->language->get('text_no_reviews');

        $page = 1;
        $data['reviews'] = array();
        $review_total = $this->model_catalog_review->getTotalReviewsByProductId($product_id);
        $results = $this->model_catalog_review->getReviewsByProductId($product_id, 0, $review_total);
        foreach ($results as $result) {
            $data['reviews'][] = array(
                'author'     => $result['author'],
                'text'       => nl2br($result['text']),
                'rating'     => (int)$result['rating'],
                'date_added_fixed' => date('Y-m-d', strtotime($result['date_added'])),
                '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=' . $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));

        return $data;
    }
    public function index() {

        $this->load->language('product/product');
        //breadcrumbs data
        $this->load->language('common/header');

        if ($this->request->server['HTTPS']) {
        $server = $this->config->get('config_ssl');
        } else {
        $server = $this->config->get('config_url');
        }
        $data['base'] = $server;
        $data['text_home'] = $this->language->get('text_home');
        
        $data['breadcrumbs'] = array();

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


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

        //dataLayer
        if (isset($this->session->data['customer_id']) && !empty($this->session->data['customer_id'])) {
            $data['dataLayer']['customer_id'] = $this->session->data['customer_id'];
            $data['dataLayer']['userType'] = 'member';

            $this->load->model('account/customer');

            $customerData = $this->model_account_customer->getCustomer($data['dataLayer']['customer_id']);
            $data['dataLayer']['emailHash'] = sha1($customerData['email']);

        }
        else {
            if (isset($_COOKIE['guest_id']) && !empty($_COOKIE['guest_id'])) {
                $guestId = $_COOKIE['guest_id'];
            }
            else {
                $guestId = rand(500000,999999);
                setcookie('guest_id', $guestId,time()+60*60*24*30, '/');
            }

            $data['dataLayer']['customer_id'] = $guestId;
            $data['dataLayer']['userType'] = 'guest';
            $data['dataLayer']['emailHash'] = '';
        }
        //dataLayer End

        if ($this->config->get('promotion_total_status')) {
            $this->load->language('extension/module/promotion');
            $this->load->model('extension/module/promotion');
            $promos = $this->model_extension_module_promotion->getPromotionsFromProductID($product_id);
            $data['promotions'] = $promos['promotions'];
            $data['promo_button'] = $promos['button'];
            $data['view_more_button_text'] = $this->language->get('view_more_button_text');
        }

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

        $all_categories = $this->model_catalog_category->getJsonCategory();
        $data['all_categories'] = array();
        foreach ($all_categories as $category) {
            $data['all_categories'][] = array(
                'name' => $category['name'],
                'category_id' => $category['category_id'],
                'href' => $this->url->link('product/category', 'path=' . $category['category_id'], true)
            );
        }

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

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

        if ($product_info) {

            $this->load->model('extension/module/recently_viewed');
            if($this->model_extension_module_recently_viewed->isEnabled()){
                if ($this->customer->isLogged()) {
                    $this->model_extension_module_recently_viewed->setRecentlyViewedProducts($this->customer->getId(), $product_info['product_id']);

                } else {

                    if(isset($this->request->cookie['recently_viewed']) && !empty($this->request->cookie['recently_viewed'])) {
                        $recently_viewed = json_decode(base64_decode($this->request->cookie['recently_viewed']), true);
                        $recently_viewed[$product_info['product_id']] = date("Y-m-d H:i:s");
                        // sort by in recent viewed order
                        uasort($recently_viewed, function($a, $b){ return strtotime($a) > strtotime($b); });
                        array_unique($recently_viewed); // remove duplicates
                    } else {
                        $recently_viewed[$product_info['product_id']] = date("Y-m-d H:i:s");
                    }
                    
                    $recently_viewed = base64_encode(json_encode($recently_viewed));
                    setcookie('recently_viewed', $recently_viewed, 0, '/', $this->request->server['HTTP_HOST']);
                }
            }

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

            $categorti_id_info = $this->model_catalog_product->getCategoryByProductId($product_id);

            $data['category_id'] = $categorti_id_info[0]['category_id'];
            $data['sub_category_id'] = $categorti_id_info[1]['category_id'];
            $data['sub_category_id2'] = $categorti_id_info[2]['category_id'];

            $data['breadcrumbs'][] = array(
                'text' => $categorti_id_info[0]['name'],
                'href' => $this->url->link('product/category', 'path=' . $categorti_id_info[0]['category_id'])
            );

            $data['breadcrumbs'][] = array(
                'text' => $categorti_id_info[1]['name'],
                'href' => $this->url->link('product/category', 'path=' . $categorti_id_info[1]['category_id'])
            );

            $data['breadcrumbs'][] = array(
                'text' => $categorti_id_info[2]['name'],
                'href' => $this->url->link('product/category', 'path=' . $categorti_id_info[2]['category_id'])
            );

            $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' => $product_info['name'],
                'href' => $server.$product_info['href']
            );
            
            $breadcrumbs1 = array();
            $count=1;
            foreach($data['breadcrumbs'] as $bread){
                $breadcrumbs1[] = array(
                 "@type"=> "ListItem",
                 "position"=> $count,
                 "name"=> $bread['text'],
                 "item"=> $bread['href']);
                $count++;
            }
            $data['breadcrumbs1']=  json_encode($breadcrumbs1);

            $extendedseo = $this->config->get('extendedseo');
            $this->document->setTitle(((isset($category_info['name']) && isset($extendedseo['categoryintitle'])) ? ($category_info['name'] . ' : ') : '') . ($product_info['meta_title'] ? $product_info['meta_title'] : $product_info['name']));
            $this->document->setDescription($product_info['meta_description']);
            $this->document->setKeywords($product_info['meta_keyword']);
            $this->document->addLink($product_info['href'], 'canonical');

            $data['heading_title'] = ($product_info['custom_h1'] <> '') ? $product_info['custom_h1'] : $product_info['name'];

            $data['custom_alt'] = $product_info['custom_alt'];
            $data['custom_imgtitle'] = $product_info['custom_imgtitle'];
            $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_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_price'] = $this->language->get('text_price');
            $data['text_price_tax'] = $this->language->get('text_price_tax');
            $data['havale_price'] = $this->language->get('havale_price');
            $data['text_option'] = $this->language->get('text_option');
            $data['text_transfer_price'] = $this->language->get('text_transfer_price');
            $data['text_in_stock'] = $this->language->get('text_in_stock');
            $data['text_order_critical'] = $this->language->get('text_order_critical');
            $data['text_minimum'] = sprintf($this->language->get('text_minimum'), $product_info['minimum']);
            $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_percentsaving'] = $this->language->get('text_percentsaving');

            $data['text_discount'] = $this->language->get('text_discount');
            $data['text_view'] = $this->language->get('text_view');
            $data['text_quick_view'] = $this->language->get('text_quick_view');
            $data['text_no_stock'] = $this->language->get('text_no_stock');
            $data['text_product_done'] = $this->language->get('text_product_done');
            $data['text_buynow'] = $this->language->get('text_buynow');

            $data['text_order_in_stock'] = $this->language->get('text_order_in_stock');
            $data['text_order_private'] = $this->language->get('text_order_private');
            $data['text_compare'] = $this->language->get('text_compare');
            $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['button_cart'] = $this->language->get('button_cart');
            $data['button_take_it_now'] = $this->language->get('button_take_it_now');
            $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_color'] = $this->language->get('text_color');
            $data['text_back'] = $this->language->get('text_back');
            $data['text_similar_product'] = $this->language->get('text_similar_product');

            // SOsyal medya bağlantıları Bilal 04/02/2019
            $data['config_facebook'] = $this->config->get('config_facebook');
            $data['config_twitter'] = $this->config->get('config_twitter');
            $data['config_instagram'] = $this->config->get('config_instagram');
            $data['config_youtube'] = $this->config->get('config_youtube');
            $data['config_linkedin'] = $this->config->get('config_linkedin');
            $data['config_pinterest'] = $this->config->get('config_linkedin');
            // SOsyal medya bağlantıları Bilal 04/02/2019


            $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['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'], true);
            $data['model'] = $product_info['model'];
            $data['reward'] = $product_info['reward'];
            $data['points'] = $product_info['points'];


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

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


            $collection_attr_g_id = 11;
            // Bu ürünün 11 ID'li özellik grubuna ailt özelliğini getiriyoruz.
            $data['collection_attr_id'] = $this->model_catalog_product->getProductAttribute($product_id, $collection_attr_g_id);

            $color_attr_id = 13;
            $data['color_attr_id'] = $this->model_catalog_product->getProductAttribute($product_id, $color_attr_id);

            $data['review_no'] = $product_info['reviews'];
            $data['quantity'] = $product_info['quantity'];
            $data['product_type'] = $product_info['product_type'];
            $data['currency_code'] = $this->session->data['currency'];
//            $data['richsnippets'] = $this->config->get('richsnippets');

            $data['texture1'] = HTTPS_SERVER . "image/texture/1.jpg";
            $data['texture2'] = HTTPS_SERVER . "image/texture/2.jpg";
            $data['texture3'] = HTTPS_SERVER . "image/texture/3.jpg";
            $data['texture4'] = HTTPS_SERVER . "image/texture/4.jpg";
            $data['texture5'] = HTTPS_SERVER . "image/texture/5.jpg";
            $data['texture6'] = HTTPS_SERVER . "image/texture/6.jpg";
            $data['texture7'] = HTTPS_SERVER . "image/texture/7.jpg";
            $data['texture8'] = HTTPS_SERVER . "image/texture/8.jpg";


            $extendedseo = $this->config->get('extendedseo');
            $data['description'] = ((isset($extendedseo['productseo'])) ? '<h2>' . $product_info['name'] . '</h2>' : '') . html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8');

            $data['description'] = ($product_info['custom_h2'] != '') ? '<h2>' . $product_info['custom_h2'] . '</h2>' . $data['description'] : $data['description'];

            if ($product_info['quantity'] <= 0) {
                $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');
            }

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

            if ($product_info['image']) {
                $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'), 'product_popup');
            } else {
                $data['popup'] = '';
            }

            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'), 'product_thumb');
            } else {
                $data['thumb'] = '';
            }

            if ($this->request->server['HTTPS']) {
                $config_url = $this->config->get('config_ssl') . 'image/';
            } else {
                $config_url = $this->config->get('config_url') . 'image/';
            }

            if ($product_info['image']) {
                $data['no_cache_image'] = $config_url . $product_info['image'];
            } else {
                $data['no_cache_image'] = '';
            }

            $fbmetaimg = '';
            if ($product_info['image']) {
                $fbmetaimg = $this->model_tool_image->resize($product_info['image'], 600, 315);
                $fbfeedimg = $this->model_tool_image->resize($product_info['image'], 600, 600);
            } else {
                $fbimage = '';
            }

            $this->document->setFBog($fbmetaimg);

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

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

            if ($product_info['images']) {
                foreach ($product_info['images'] 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'), 'product_popup'),
                        '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'), 'product_thumb'),
                        'no_cache_image' => $config_url . $result['image'],
                    );
                }
            }
            
            if($product_info['product_type']==11){
                require_once DIR_SYSTEM_LOCAl.'library/instabasic/instagram.php';
                $insta = new Instagram($this->registry);
                $login_url=$insta->get_login_url();
                $data['insta_login_url']=$login_url;
                header("Access-Control-Allow-Origin: *");
                $data['pattern1']=$config_url.$product_info['pattern'];
                $data['pattern1']=str_replace("catalog/","catalog/custom/product11/",$data['pattern1']);
                $pattern_imgs1=explode(",",$product_info['pattern_names']);
                foreach ($pattern_imgs1 as $key => $value) {
                    $data['pattern_names'][]=str_replace("images","image",$config_url).'catalog/custom/product11/'.$value.".png";
                }
                $pattern_imgs1=explode(",",$product_info['cover_names']);
                foreach ($pattern_imgs1 as $key => $value) {
                    $data['cover_names'][]=str_replace("images","image",$config_url).'catalog/custom/product11/'.$value.".png";
                }
            }

            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']);
                $data['price1'] = $this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax'));
            } else {
                $data['price'] = false;
            }


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

            $data['soft_currency_price'] = false;

            /* HAVALE FİYATI */

            $havale_price = 0;
            $havale_status = $this->config->get('payment_feediscount_status');

            $data['havale_price'] = 0;
            $data['soft_currency_special'] = false;
            $data['special1'] = '';

            if ((float) $product_info['special'] and ( $this->customer->isLogged() || !$this->config->get('config_customer_price'))) {
                $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']);
                $data['percentsaving'] = round((($product_info['price'] - $product_info['special']) / $product_info['price']) * 100, 0);
            } else {
                $data['special'] = false;
                $data['percentsaving'] = false;
            }

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

            $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) {
                    $option_value['price'] = $this->currency->convert($option_value['price'], $this->currency->getCodeOrDefault($product_info['currency_id'], $this->session->data['currency']), $this->currency->getDefaultcurrency());
                    if ($option_value['subtract']) {
                        if ((($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                            $o_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 {
                            $o_price = false;
                        }

                        $op_images = array();
                        $o_images = json_decode($option_value['image'], true);
                        if(is_array($o_images)){
                            foreach ($o_images as $o_image) {
                                if($o_image){
                                    $op_images[] = $this->model_tool_image->resize($o_image, $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height'),'product_popup');
                                }
                            }
                        }

                        $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' => $op_images,
                            'price' => $o_price,
                            'quantity' => $option_value['quantity'],
                            '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']
                );
            }




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

            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['reviews'] = sprintf($this->language->get('text_reviews'), (int) $product_info['reviews']);
            $data['rating'] = (int) $product_info['rating'];

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

            $data['share'] = $product_info['href'];


            $autolinks = $this->config->get('autolinks');

            if (isset($autolinks) && (strpos($data['description'], 'iframe') == false) && (strpos($data['description'], 'object') == false)) {
                $xdescription = mb_convert_encoding(html_entity_decode($data['description'], ENT_COMPAT, "UTF-8"), 'HTML-ENTITIES', "UTF-8");

                libxml_use_internal_errors(true);
                $dom = new DOMDocument;
                $dom->loadHTML('<div>' . $xdescription . '</div>');
                libxml_use_internal_errors(false);


                $xpath = new DOMXPath($dom);

                foreach ($autolinks as $autolink) {
                    $keyword = $autolink['keyword'];
                    $xlink = mb_convert_encoding(html_entity_decode($autolink['link'], ENT_COMPAT, "UTF-8"), 'HTML-ENTITIES', "UTF-8");
                    $target = $autolink['target'];
                    $tooltip = isset($autolink['tooltip']);

                    $pTexts = $xpath->query(
                            sprintf('///text()[contains(., "%s")]', $keyword)
                    );

                    foreach ($pTexts as $pText) {
                        $this->parseText($pText, $keyword, $dom, $xlink, $target, $tooltip);
                    }
                }

                $data['description'] = $dom->saveXML($dom->documentElement);
            }


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

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

            $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))
                        'href' => ''
                    );
                }
            }

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

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

            // Twitter Cart #Bilal 10/05/2019

            if ($data['special'] == false) {
                $this->document->addMetaTags(
                        array(
                            array(
                                'name' => 'twitter:card',
                                'content' => 'product',
                            ),
                            array(
                                'name' => 'twitter:site',
                                'content' => '@site_username',
                            ),
                            array(
                                'name' => 'twitter:creator',
                                'content' => '@creator_username',
                            ),
                            array(
                                'name' => 'twitter:title',
                                'content' => $this->document->getTitle(),
                            ),
                            array(
                                'name' => 'twitter:description',
                                'content' => $this->document->getDescription(),
                            ),
                            array(
                                'name' => 'twitter:image:src',
                                'content' => $data['thumb'],
                            ),
                            array(
                                'name' => 'twitter:data1',
                                'content' => $data['price'],
                            ),
                            array(
                                'name' => 'twitter:label1',
                                'content' => $data['text_price'],
                            ),
                            array(
                                'name' => 'twitter:data2',
                                'content' => $data['stock'],
                            ),
                            array(
                                'name' => 'twitter:label2',
                                'content' => $data['text_stock'],
                            ),
                            array(
                                'name' => 'twitter:domain',
                                'content' => HTTP_SERVER,
                            ),
                        )
                );
            } else {
                $this->document->addMetaTags(
                        array(
                            array(
                                'name' => 'twitter:card',
                                'content' => 'product',
                            ),
                            array(
                                'name' => 'twitter:title',
                                'content' => $this->document->getTitle(),
                            ),
                            array(
                                'name' => 'twitter:description',
                                'content' => $this->document->getDescription(),
                            ),
                            array(
                                'name' => 'twitter:image:src',
                                'content' => $data['thumb'],
                            ),
                            array(
                                'name' => 'twitter:data1',
                                'content' => $data['special'],
                            ),
                            array(
                                'name' => 'twitter:label1',
                                'content' => $data['text_price'],
                            ),
                            array(
                                'name' => 'twitter:data2',
                                'content' => $data['stock'],
                            ),
                            array(
                                'name' => 'twitter:label2',
                                'content' => $data['text_stock'],
                            ),
                            array(
                                'name' => 'twitter:domain',
                                'content' => HTTP_SERVER,
                            ),
                        )
                );
            }

            // Twitter Cart #Bilal 10/05/2019

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

            /*
            $data['footer'] = $this->cache->cache_get('product_footer' . $product_id, 'product_footer/');
            if (!$data['footer']) {
                $data['footer'] = $this->load->controller('common/footer');
                $this->cache->cache_set('product_footer' . $product_id, $data['footer'], 'product_footer/');
            } */

            $data['header'] = $this->load->controller('common/header');

            $data['header'] = $this->cache->cache_get('product_header' . $product_id, 'product_header/');
            if (!$data['header']) {
                $data['header'] = $this->load->controller('common/header');
                $this->cache->cache_set('product_header' . $product_id, $data['header'], 'product_header/');
            }

            $data['CretioOneTag_status']=	$this->config->get('CretioOneTag_status');
            $data['CretioOneTag_id']=	$this->config->get('CretioOneTag_id');
            
            $data['useinsider_status']=	$this->config->get('useinsider_status');
            $data['useinsider_partner_id']=	$this->config->get('useinsider_partner_id');
            
            //reviews add without ajax
            $data['reviews_first'] = $this->getReviewsFirstPage((int)$this->request->get['product_id']);
            //product data
            $data['rich_snippets'] = array();
            $data['rich_snippets']['name'] = htmlspecialchars($data['heading_title'], ENT_QUOTES, "UTF-8");
            $rich_snippets_images = array();
            if ($product_info['image']) {
                $rich_snippets_images[] = '"' . $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')) . '"';
                $rich_snippets_images[] = '"' . $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')) . '"';
                $rich_snippets_images[] = '"' . $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height')) . '"';
                $rich_snippets_images[] = '"' . $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_compare_width'), $this->config->get($this->config->get('config_theme') . '_image_compare_height')) . '"';
            }
            $data['rich_snippets']['image'] = implode(",", $rich_snippets_images);
            $data['rich_snippets']['description'] = htmlentities(preg_replace('/[\n\r]/', '', strip_tags(html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8'))));
            $data['rich_snippets']['sku'] = !empty($product_info['sku']) ? $product_info['sku'] : $data['model'];
            $data['rich_snippets']['brand'] = htmlspecialchars($data['manufacturer'], ENT_QUOTES, "UTF-8");
            $data['rich_snippets']['ratingValue'] = number_format((float)$product_info['rating'], 1, '.', '');
            $data['rich_snippets']['ratingCount'] = $product_info['reviews'];
            $data['rich_snippets']['reviewCount'] = $product_info['reviews'];
            $data['rich_snippets']['reviews_snippet'] = '';
            $reviews_array = array();
            $reviews_snippet = $data['reviews_first']['reviews'];
            if (!empty($reviews_snippet)) {
                foreach ($reviews_snippet as $review_snippet) {
                    $reviews_array[] = '{"@type": "Review", "reviewRating": {"@type": "Rating", "ratingValue": "' . $review_snippet['rating'] . '", "bestRating": "5", "worstRating": "1"}, "author": {"@type": "Person", "name": "' . $review_snippet['author'] . '"}}';
                }
            }
            $data['rich_snippets']['reviews_snippet'] = implode(",", $reviews_array);
            $data['rich_snippets']['priceCurrency'] = $this->session->data['currency'];
            $rich_snippets_price = trim(trim(($data['special'] != false) ? $data['special'] : $data['price'], $this->currency->getSymbolLeft($this->session->data['currency'])), $this->currency->getSymbolRight($this->session->data['currency']));
            $decimal_point_rs_price = $this->language->get('decimal_point') ? $this->language->get('decimal_point') : '.';
            $thousand_point_rs_price = $this->language->get('thousand_point')? $this->language->get('thousand_point') : ' ';
            $rich_snippets_price = str_replace($thousand_point_rs_price, '', $rich_snippets_price);
            if ( $decimal_point_rs_price != '.' ) {
              $rich_snippets_price = str_replace($decimal_point_rs_price, '.', $rich_snippets_price);
            }
            $rich_snippets_price = number_format($rich_snippets_price, 2, '.', '');
            $data['rich_snippets']['price'] = $rich_snippets_price;
            $data['rich_snippets']['availability'] = (($product_info['quantity'] <= 0) ? 'OutOfStock' : 'InStock');
            $data['rich_snippets']['url'] = $this->url->link('product/product', 'product_id=' . $this->request->get['product_id']);
            $data['rich_snippets']['seller_name'] = $this->config->get('config_name');
            $data['rich_snippets']['priceValidUntil'] = '';
            if ($data['special'] != false) {
                $special_info = $this->model_catalog_product->getSpecialDates($this->request->get['product_id']);
                if ($special_info && ($special_info['date_end'] !== '0000-00-00')) {
                    $data['rich_snippets']['priceValidUntil'] = $special_info['date_end'];
                }
            }
            if($_SERVER['REMOTE_ADDR']=='111.88.7.0'){
                $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/product_dev', $data));
            }else{
                 if (file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/product/'.$data['product_type'].'.tpl')) {
                    $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/product/' . $data['product_type'], $data));
                 }else if (file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/product.tpl')) {
                     $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/product', $data));
                 } else {
                     $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'default/template/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)
            );

            $extendedseo = $this->config->get('extendedseo');
            $this->document->setTitle(((isset($category_info['name']) && isset($extendedseo['categoryintitle'])) ? ($category_info['name'] . ' : ') : '') . $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');

            if (file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/error/not_found.tpl')) {
                $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/error/not_found', $data));
            } else {
                $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'default/template/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']);
        $review_total = 10;

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

        foreach ($pagination->prevnext() as $pagelink) {
            $this->document->addLink($pagelink['href'], $pagelink['rel']);
        }


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

        if (file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/review.tpl')) {
            $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/review', $data));
        } else {
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'default/template/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));
    }

    public function getoptions() {
        if (isset($this->request->post['product_id'])) {
            $this->load->model('catalog/product');
            $this->load->model('tool/image');
            $product_info = $this->model_catalog_product->getProduct($this->request->post['product_id']);
            $options = array();
            foreach ($this->model_catalog_product->getProductOptions($product_info['product_id']) as $option) {
                $product_option_value_data = array();

                foreach ($option['product_option_value'] as $option_value) {
                    if ($option_value['subtract']) {
                        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'],
                            'quantity' => $option_value['quantity'],
                            'image' => $this->model_tool_image->resize($option_value['image'], 50, 50),
                            'price' => $price,
                            'price_prefix' => $option_value['price_prefix']
                        );
                    }
                }

                $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']
                );
            }

            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($options));
            //OPTİONS #BİLAL 01/03/2019
        } else {
            return false;
        }
    }
    public function getInstaSession() {
        $s="";
        if (array_key_exists('insta_imgs',$this->session->data)) {
            $s=$this->session->data['insta_imgs'];
            $this->session->data['insta_imgs']="";
        }
        $json['insta_session']=$s;
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function getimages() {
        if (isset($this->request->post['product_id'])) {

            if ($this->request->server['HTTPS']) {
                $config_url = $this->config->get('config_ssl') . 'image/';
            } else {
                $config_url = $this->config->get('config_url') . 'image/';
            }

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

            $results = $this->model_catalog_product->getProductImages($this->request->post['product_id']);
            $data['images'] = array();
            if ($results) {
                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'), 'product_popup'),
                        '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'), 'product_thumb'),
                        'no_cache_image' => $config_url . $result['image'],
                    );
                }
            } else {
                $option_thumbs = $this->model_catalog_product->getProductOptionValueThumbs($this->request->post['product_id']);
                foreach ($option_thumbs as $o_thumbs) {
                    $data['images'][] = array(
                        'popup' => $this->model_tool_image->resize($o_thumbs, $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height'), 'product_popup'),
                        'thumb' => $this->model_tool_image->resize($o_thumbs, $this->config->get($this->config->get('config_theme') . '_image_additional_width'), $this->config->get($this->config->get('config_theme') . '_image_additional_height'), 'product_thumb'),
                        'no_cache_image' => $config_url . $o_thumbs,
                    );
                }
            }

            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($data['images']));
        } else {
            return false;
        }
    }

    public function getAttributes() {

        $json = array();

        if (isset($this->request->post['category_id'])) {
            $this->load->model('catalog/product');
            $this->load->model('tool/image');

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

            $attributes = $this->model_catalog_product->getProductAttributesByCategoryId($attribute_group_id, $this->request->post['category_id'], $this->request->post['product_id'], $this->request->post['model']);
            $json['attributes'] = array();
            foreach ($attributes as $attribute) {
                $json['attributes'][] = array(
                    'name' => $attribute['name'],
                    'attribute_id' => $attribute['attribute_id'],
                    'attribute_group_id' => $attribute['attribute_group_id'],
                    'image' => $this->model_tool_image->resize($attribute['image'], 50, 50)
                );
            }
        } else {
            $json['error'] = 'Category was not select!';
        }

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

    public function getAttributesByOtherAttributeId() {
        $json = array();

        //$this->product->dump( $this->request->post['category_id']);

        if (isset($this->request->post['category_id'])) {
            $this->load->model('catalog/product');
            $this->load->model('tool/image');

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


            $attribute_group_id = 13;

            $attributes = $this->model_catalog_product->getProductAttributesByOtherAttributeId($attribute_id, $attribute_group_id, $this->request->post['category_id'], $this->request->post['model']);

            $json['attributes'] = array();
            foreach ($attributes as $attribute) {
                $json['attributes'][] = array(
                    'name' => $attribute['name'],
                    'attribute_id' => $attribute['attribute_id'],
                    'product_id' => $attribute['product_id'],
                    'attribute_group_id' => $attribute['attribute_group_id'],
                    'image' => $this->model_tool_image->resize($attribute['image'], 50, 50)
                );
            }
        } else {
            $json['error'] = 'Category was not select!';
        }

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

    public function getSubCategories()
    {

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

        if (isset($this->request->post['category_id'])) {


            $category_id = $this->request->post['category_id'];
            //$product_id = $this->request->post['product_id'];

            //$collection_attr_g_id = 11;
            // Bu ürünün 11 ID'li özellik grubuna ailt özelliğini getiriyoruz.
            //$json['collection_attr_id'] = $this->model_catalog_product->getProductAttribute($product_id, $collection_attr_g_id);


            //$categories = $all_categories = $this->model_catalog_product->getExistCollectionCategories($json['collection_attr_id'], $product_id, $category_id);
            $this->load->model('catalog/category');

            $categories = $this->model_catalog_category->getCategories($category_id);
            foreach ($categories as $result) {
                $data['categories'][] = array(
                    'name' => $result['name'],
                    'href' => $result['href'],
                    'category_id' => $result['category_id'],
                );
            }
        }


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

    public function getExistCollectionSubCategories(){

        $json = array();

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

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

            $collection_attr_g_id = 11;
            // Bu ürünün 11 ID'li özellik grubuna ailt özelliğini getiriyoruz.
            $json['collection_attr_id'] = $this->model_catalog_product->getProductAttribute($product_id, $collection_attr_g_id);

            //$all_categories = $this->model_catalog_category->getCategories();
            $categories = $this->model_catalog_product->getExistCollectionCategories($json['collection_attr_id'], $product_id, $category_id, $category_id);

            $json['categories'] = array();
            foreach ($categories as $category) {
                $json['categories'][] = array(
                    'name' => $category['name'],
                    'category_id' => $category['category_id'],
                    'href' => $category['href'],
                );
            }

            // $json['collection_attr_id']
            $color_attr_id = 13;
            $json['color_attr_id'] = $this->model_catalog_product->getProductAttribute($product_id, $color_attr_id);

        } else {
            $json['error'] = 'Product was not found!';
        }

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

    public function getProductInfo() {

        //Sayfa ilk yüklendiği zaman bu ürün Id'sine göre kategoriler ve alt kategoriler gelicek,
        //

        $json = array();

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

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


            $categorti_id_info = $this->model_catalog_product->getCategoryByProductId($product_id);
            $json['category_id'] = $categorti_id_info[0]['category_id'];
            $json['sub_category_id'] = $categorti_id_info[1]['category_id'];

            $collection_attr_g_id = 11;
            // Bu ürünün 11 ID'li özellik grubuna ailt özelliğini getiriyoruz.
            $json['collection_attr_id'] = $this->model_catalog_product->getProductAttribute($product_id, $collection_attr_g_id);

            //$all_categories = $this->model_catalog_category->getCategories();
            $all_categories = $this->model_catalog_product->getExistCollectionCategories($json['collection_attr_id'], $product_id, 0, $json['category_id']);

            $json['all_categories'] = array();
            foreach ($all_categories as $category) {
                $json['all_categories'][] = array(
                    'name' => $category['name'],
                    'category_id' => $category['category_id'],
                    'href' => $category['href'],
                );
            }

            $all_sub_categories = $this->model_catalog_product->getExistCollectionCategories($json['collection_attr_id'], $this->request->post['product_id'], $json['category_id'], $json['category_id']);

            $json['all_sub_categories'] = array();
            foreach ($all_sub_categories as $category) {
                $json['all_sub_categories'][] = array(
                    'name' => $category['name'],
                    'category_id' => $category['category_id'],
                    'href' => $category['href'],
                );
            }



            // $json['collection_attr_id']
            $color_attr_id = 13;
            $json['color_attr_id'] = $this->model_catalog_product->getProductAttribute($product_id, $color_attr_id);

        } else {
            $json['error'] = 'Product was not found!';
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
    public function upload_img_on_server(){
        $url="";
        if (isset($this->request->post['url'])) {
            $url=$this->request->post['url'];
        }

        //$json['decoded_b4']=$base64string;

        if (!file_exists(DIR_IMAGE . 'upload')) {
            mkdir(DIR_IMAGE . 'upload', 0777, true);
        }

        $arr1=explode("/",DIR_IMAGE);
        $m_time=explode(" ",microtime());
        if(count($m_time)>1){
            $m_time=$m_time[0].$m_time[1];
        }

        $length = 5;
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        $name1=substr(str_shuffle(MD5(microtime())), 0, 10);
        $img_name=DIR_IMAGE.'p_11/'.$randomString.$name1.'.png';

        $json['img_name']="/image/p_11/".$randomString.$name1.'.png';

        if(file_exists($img_name)) {
            if(unlink($img_name)){
                $json['deleted']="Found and deleted";
            }
        }
        else{
            $json['deleted']="File Not Found!";
        }
        ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)');
        $url=str_replace("&amp;","&",$url);
        $mel_url = $url;

        $agent = "Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
        $header = array (
            'Accept-Encoding: deflate',
            'Accept-Language: ja, en-US;q = 0.9, en;q = 0.8',
        );
        $conn = curl_init ();
        curl_setopt ($conn, CURLOPT_URL, $mel_url);
        curl_setopt ($conn, CURLOPT_RETURNTRANSFER, true);
        curl_setopt ($conn, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt ($conn, CURLOPT_USERAGENT, $agent);
        curl_setopt ($conn, CURLOPT_HTTPHEADER, $header);

        $res="";
        if(curl_exec($conn) === false)
        {
            $json['error'] = curl_error($conn);
        }
        else
        {
            $json['error'] = "No error at all";
            $res=curl_exec($conn);
        }
        curl_close ($conn);

        if(file_put_contents($img_name,$res))
        {
            $json['status']=1;
        } else {
            $json['status']=0;
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
    public function writeImg(){
        $img_c = base64_encode(file_get_contents(addslashes($_FILES['c_image']['tmp_name'])));
        $img_a = base64_encode(file_get_contents(addslashes($_FILES['a_image']['tmp_name'])));
        
        $this->load->model('catalog/product');
        $id=$this->model_catalog_product->set_blobs($img_c,$img_a);
        
        $json['id']=$id;
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
    public function getProductDetail() {



        $json = array();
        $product_type="";
        if (isset($this->request->post['product_type'])) {
         $product_type=(int)$this->request->post['product_type'];
        }
        if (isset($this->request->post['attribute_id'])) {

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

            // ALL categories -------------------------------------------------------------------------------------------------------------------------------------------------------------------------

            $categorti_id_info = $this->model_catalog_product->getCategoryByProductId($this->request->post['product_id']);
            $json['category_id'] = $categorti_id_info[0]['category_id'];
            $json['sub_category_id'] = $categorti_id_info[1]['category_id'];


            $collection_attr_g_id = 11;
            // Bu ürünün 11 ID'li özellik grubuna ailt özelliğini getiriyoruz.
            $collection_attr_id = $this->model_catalog_product->getProductAttribute($this->request->post['product_id'], $collection_attr_g_id);

            $all_categories = $this->model_catalog_product->getExistCollectionCategories($collection_attr_id, $this->request->post['product_id'], 0, $json['category_id']);

            $json['all_categories'] = array();
            foreach ($all_categories as $category) {
                $json['all_categories'][] = array(
                    'name' => $category['name'],
                    'category_id' => $category['category_id'],
                    'href' => $category['href'],
                );
            }

            $all_sub_categories = $this->model_catalog_product->getExistCollectionCategories($collection_attr_id, $this->request->post['product_id'], $json['category_id'], $json['category_id']);

            $json['all_sub_categories'] = array();
            foreach ($all_sub_categories as $category) {
                $json['all_sub_categories'][] = array(
                    'name' => $category['name'],
                    'category_id' => $category['category_id'],
                    'href' => $category['href'],
                );
            }

            // ALL categories-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

            $collection_attr_g_id = 13;
            $product_info = $this->model_catalog_product->getProductByAttributeId($collection_attr_g_id, $this->request->post['attribute_id'], $this->request->post['product_id']);

            if ($this->request->server['HTTPS']) {
                $config_url = $this->config->get('config_ssl') . 'image/';
            } else {
                $config_url = $this->config->get('config_url') . 'image/';
            }


            $special = $this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax'));
            $price = $this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax'));

            #FaceBook Pixel
            $facebook_param = '{\"event_name\":\"ViewContent\",\"content_type\":\"product\",\"content_ids\":[\"'. $this->request->post['product_id'] .'\"],\"value\":'.( $special ? $special : $price).',\"currency\":\"TRY\",\"content_name\":\"'. $product_info['name'] .'\",\"num_items\":1}';

            $json['facebook_js'] = '';
            
            $json['facebook_js'] = ' facebook_loadScript("https://dr.deercase.com/catalog/view/javascript/facebook/facebook_pixel.js",function() {
                  var params = {'. "'agent'" . ':' . "'deercase-2.3.0.2-2.1.3'" .'};
                  _facebookAdsExtension.facebookPixel.init(
                    '. $this->fbevents['facebook_pixel_id_FAE'] .',
                    '. $this->fbevents['facebook_pixel_pii_FAE'] .',
                    params);';
                  if ($facebook_param) {
                      $json['facebook_js'] .= '_facebookAdsExtension.facebookPixel.firePixel(
                      JSON.parse(\'' .$facebook_param. '\'));';
                  }
                  $json['facebook_js'] .= ' }); ';
            
            #FaceBook Pixel



            // remove away the facebook_pixel_event_params_FAE in session data
            // to avoid duplicate firing after the 1st fire
            unset($this->session->data['facebook_pixel_event_params_FAE']);

            $json['product_info'] = $product_info;

            if ($product_info['image']) {
                $json['product_info']['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'), 'product_popup');
            } else {
                $option_thumb = $this->model_catalog_product->getProductOptionValueThumb($this->request->get['product_id']);
                if ($option_thumb) {
                    $json['product_info']['popup'] = $this->model_tool_image->resize($option_thumb, $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height'), 'product_popup');
                } else {
                    $json['product_info']['popup'] = '';
                }
            }

            if ($product_info['image']) {
                $json['product_info']['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'), 'product_thumb');
            } else {
                $option_thumb = $this->model_catalog_product->getProductOptionValueThumb($this->request->get['product_id']);
                if ($option_thumb) {
                    $json['product_info']['thumb'] = $this->model_tool_image->resize($option_thumb, $this->config->get($this->config->get('config_theme') . '_image_thumb_width'), $this->config->get($this->config->get('config_theme') . '_image_thumb_height'), 'product_thumb');
                    $product_info['image'] = $option_thumb;
                } else {
                    $json['product_info']['thumb'] = '';
                }
            }
            

            if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                $json['product_info']['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 {
                $json['product_info']['price'] = false;
            }

            if ((float) $product_info['special']) {
                $json['product_info']['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 {
                $json['product_info']['special'] = false;
            }

            $json['product_info']['images'] = array();

            $results = $this->model_catalog_product->getProductImages($json['product_info']['product_id']);

            if ($json['product_info']['product_type'] != 0) {
                if ($results) {
                    foreach ($results as $result) {
                        $json['product_info']['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'), 'product_popup'),
                            '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'), 'product_thumb'),
                            'no_cache_image' => $config_url . $result['image'],
                        );
                    }
                } else {
                    $option_thumbs = $this->model_catalog_product->getProductOptionValueThumbs($this->request->get['product_id']);
                    foreach ($option_thumbs as $o_thumbs) {
                        $json['product_info']['images'][] = array(
                            'popup' => $this->model_tool_image->resize($o_thumbs, $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height'), 'product_popup'),
                            'thumb' => $this->model_tool_image->resize($o_thumbs, $this->config->get($this->config->get('config_theme') . '_image_additional_width'), $this->config->get($this->config->get('config_theme') . '_image_additional_height'), 'product_thumb'),
                            'no_cache_image' => $config_url . $o_thumbs,
                        );
                    }
                }
            }


            $json['product_info']['media'] = $config_url . $json['product_info']['image'];
            if($product_type==11){
                $json['product_info']['media'] = str_replace("catalog/","catalog/custom/product11/",$json['product_info']['media']);
            }
            $json['product_info']['media_extension'] = 'image';

            $json['product_info']['pattern'] = '';

            $json['product_info']['mask'] = $config_url . $json['product_info']['mask'];

            //----------------------
            $media_dir_path = '';
            $media_path = '';
            $model2 = explode('/', $product_info['image']);
            if((strstr($product_info['name'],'Neon') OR strstr($product_info['name'],'Simli Sulu')) ){
                if(isset($model2[3])){

                    if($product_info['product_type'] != 4){
                        $model2 = explode('-', $model2[3]);
                        $case_category = $model2[2];
                        $case_attr= mb_convert_case($model2[3], 1, "UTF-8");
                        $case_color = explode('_', $model2[4]);
                        $case_color = mb_convert_case($case_color[1], 1, "UTF-8");
                        $json['product_info']['mask'] = $config_url . $this->model_tool_case_image_crop->crop($product_info);

                    }elseif ($product_info['product_type'] == 4){
                        $model2 = explode('-', $model2[3]);
                        $case_category = $model2[1];
                        $case_attr= mb_convert_case($model2[2], 1, "UTF-8");
                        $case_color = explode('_', str_replace('.jpg','', $model2[3]));
                        $case_color = mb_convert_case($case_color[1], 1, "UTF-8");
                        $json['product_info']['mask'] = '';
                    }

                    $case_category = str_replace('_', ' ', $case_category);
                    $case_category = str_replace(' ', '', ucwords(mb_convert_case($case_category, 1, "UTF-8")));
                    $media_path = $config_url . 'catalog/media/' . $case_category . '/' . $case_attr . '/' . $case_color . '';
                    if($product_info['model'] != 'lms093'){
                        $media_dir_path = DIR_IMAGE . 'catalog/media/' . $case_category . '/' . $case_attr . '/' . $case_color . '.mp4';

                    }


                }


                $json['product_info']['media_dir_path'] = $media_dir_path;
                $json['product_info']['media_path'] = $media_path;

                if(file_exists($media_dir_path)){
                    $json['product_info']['media'] = $media_path;
                    $json['product_info']['media_extension'] = 'video';
                }


            }


            //----------------------


            $json['product_info']['product_image'] = $config_url . $json['product_info']['image'];
            $json['product_info']['image'] = $config_url . $json['product_info']['image'];



            //---------------------- POPSOCETSIZ HARF KOLEKSİYONU -------------------------
            if($product_info['product_type'] == 2){

                $cacth = explode('/', $product_info['image']);

                if(isset($cacth[3])){
                    $cacth = explode('-', $cacth[3]);
                    if(isset($cacth[4]) AND $cacth[4] == 'POPSOCKETSIZ'){ 
                        $background_image = 'repository/PS/BACKGROUND/' . $cacth[0] . '-' . $cacth[1] . '-' . $cacth[2] . '-' . $cacth[3] . '-' . $cacth[4] . '-BACKGROUND.jpeg';
                        $json['product_info']['image'] = $config_url . $background_image;
                        $json['product_info']['media'] = $config_url . $background_image;
                        $json['product_info']['product_image'] = $config_url . $background_image;
                    }elseif($cacth[3] == '1.jpeg'){
                        $background_image = 'repository/ALF/background/' . $cacth[0] . '-' . $cacth[1] . '-' . $cacth[2] . '.jpeg';
                        $json['product_info']['image'] = $config_url . $background_image;
                        $json['product_info']['media'] = $config_url . $background_image;
                        $json['product_info']['product_image'] = $config_url . $background_image;
                    } else{
                        $background_image = 'repository/ALF/background/' . $cacth[0] . '-' . $cacth[1] . '-' . $cacth[2] . '-' . $cacth[3] . '-BACKGROUND.jpeg';
                        $json['product_info']['image'] = $config_url . $background_image;
                        $json['product_info']['media'] = $config_url . $background_image;
                        $json['product_info']['product_image'] = $config_url . $background_image;
                    }
                }

            }
            //---------------------- POPSOCETSIZ HARF KOLEKSİYONU -------------------------
            
            
            
            $json['options'] = array();
            $this->load->language('product/product');
            $json['text_option'] = $this->language->get('text_option');
             $json['text_select'] = $this->language->get('text_select');

            foreach ($this->model_catalog_product->getProductOptions($this->request->post['product_id']) as $option) {
                $product_option_value_data = array();
                foreach ($option['product_option_value'] as $option_value) {
                    $option_value['price'] = $this->currency->convert($option_value['price'], $this->currency->getCodeOrDefault($product_info['currency_id'], $this->session->data['currency']), $this->currency->getDefaultcurrency());
                    if ($option_value['subtract']) {
                        if ((($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                            $o_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 {
                            $o_price = false;
                        }

                        $op_images = array();
                        $o_images = json_decode($option_value['image'], true);
                        if(is_array($o_images)){
                            foreach ($o_images as $o_image) {
                                if($o_image){
                                    $op_images[] = $this->model_tool_image->resize($o_image, $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height'),'product_popup');
                                }
                            }
                        }

                        $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' => $op_images,
                            'price' => $o_price,
                            'quantity' => $option_value['quantity'],
                            'price_prefix' => $option_value['price_prefix']
                        );
                    }
                }

                $json['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']
                );
            }
            
            $json['product_info']['currency']=$this->session->data['currency'];
           $json['product_info']['stock'] = $product_info['quantity'];
            
            $json['breadcrumb1'] =  $categorti_id_info[0]['name'];
            $json['breadcrumb2'] =$categorti_id_info[1]['name'];
            $json['breadcrumb3'] =$categorti_id_info[2]['name'];
            
           $json['options']=$this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/product_ajax_options', $json,true);
           $json['tempdata']=$this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/product_ajax', $json,true);

           $url = '';
           if(isset($this->request->post['href'])){
               $paths = explode('&', $this->request->post['href']);
               if(isset($paths[0])){
                   unset($paths[0]);
                   foreach ($paths as $path){
                       $url .= $path;
                   }
               }

           }

           $json['product_info']['href'] = $this->url->link('product/product', 'product_id=' . $json['product_info']['product_id'], true) . htmlentities($url);

        } else {
            $json['error'] = 'Product was not found!';
        }

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

}
