<?php
class ControllerCheckoutCart extends Controller {

    public function index() {

        $this->load->language('checkout/cart');

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

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

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

        $data['breadcrumbs'][] = array(
            'href' => $this->url->link('checkout/cart'),
            'text' => $this->language->get('heading_title')
        );

        $data['empty_cart_button'] = false;
        if(isset($this->session->data['user_id'])){
            $data['empty_cart_button'] = true;
        }

        //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->cart->hasProducts() || !empty($this->session->data['vouchers'])) {
            $data['heading_title'] = $this->language->get('heading_title');

            $data['text_recurring_item'] = $this->language->get('text_recurring_item');
            $data['text_next'] = $this->language->get('text_next');
            $data['text_next_choice'] = $this->language->get('text_next_choice');

            $data['column_image'] = $this->language->get('column_image');
            $data['column_customer_order_image'] = $this->language->get('column_customer_order_image');
            $data['column_name'] = $this->language->get('column_name');
            $data['column_model'] = $this->language->get('column_model');
            $data['column_quantity'] = $this->language->get('column_quantity');
            $data['column_price'] = $this->language->get('column_price');
            $data['column_total'] = $this->language->get('column_total');
            $data['column_product_id'] = $this->language->get('column_product_id');

            $data['button_update'] = $this->language->get('button_update');
            $data['button_remove'] = $this->language->get('button_remove');
            $data['button_shopping'] = $this->language->get('button_shopping');
            $data['button_checkout'] = $this->language->get('button_checkout');

            if (!$this->cart->hasStock() && (!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning'))) {
                $data['error_warning'] = $this->language->get('error_stock');
            } elseif (isset($this->session->data['error'])) {
                $data['error_warning'] = $this->session->data['error'];

                unset($this->session->data['error']);
            } else {
                $data['error_warning'] = '';
            }

            if ($this->config->get('config_customer_price') && !$this->customer->isLogged()) {
                $data['attention'] = sprintf($this->language->get('text_login'), $this->url->link('account/login'), $this->url->link('account/register'));
            } else {
                $data['attention'] = '';
            }

            if (isset($this->session->data['success'])) {
                $data['success'] = $this->session->data['success'];

                unset($this->session->data['success']);
            } else {
                $data['success'] = '';
            }

            $data['action'] = $this->url->link('checkout/cart/edit', '', true);

            if ($this->config->get('config_cart_weight')) {
                $data['weight'] = $this->weight->format($this->cart->getWeight(), $this->config->get('config_weight_class_id'), $this->language->get('decimal_point'), $this->language->get('thousand_point'));
            } else {
                $data['weight'] = '';
            }

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

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

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

            $products = $this->cart->getProducts();

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

            $additional_product_ids = array('140165', '140166', '140167', '140168', '140169', '519427');
            $check_other_product_exists_in_cart = false;
            
            foreach ($products as $product) {
                
                $breadcrumb1=$breadcrumb2=$breadcrumb3=$color=$collection='';
                
                if (!in_array($product['product_id'], $additional_product_ids)) {
                $categorti_id_info = $this->model_catalog_product->getCategoryByProductId($product['product_id']);
                $product_info = $this->model_catalog_product->getProduct($product['product_id']);
                $color=$product_info['attribute_groups'][1]['attribute'][0]['name'];
                        $collection=$product_info['attribute_groups'][0]['attribute'][0]['name'];
                        $p_stock=$product_info['quantity'];
                        
                         $breadcrumb1 = $categorti_id_info[0]['name'];
                        $breadcrumb2 = $categorti_id_info[1]['name'];
                        $breadcrumb3 = $categorti_id_info[2]['name'];
                }
                $product_total = 0;
                if (!in_array($product['product_id'], $additional_product_ids)) {
                    $check_other_product_exists_in_cart = true;
                }

                foreach ($products as $product_2) {
                    if ($product_2['product_id'] == $product['product_id']) {
                        $product_total += $product_2['quantity'];
                    }
                }


                if ($product['minimum'] > $product_total) {
                    $data['error_warning'] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);
                }

                if ($product['image']) {
                    $image = $this->model_tool_image->resize($product['image'], $this->config->get($this->config->get('config_theme') . '_image_cart_width'), $this->config->get($this->config->get('config_theme') . '_image_cart_height'));
                } else {
                    $image = '';
                }

                $option_data = array();

                foreach ($product['option'] as $option) {
                    if ($option['type'] != 'file') {
                        $value = $option['value'];
                    } else {
                        $upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

                        if ($upload_info) {
                            $value = $upload_info['name'];
                        } else {
                            $value = '';
                        }
                    }

                    $option_data[] = array(
                        'name' => $option['name'],
                        'value' => $value
                    );

                    if (isset($option['option_thumb_image'])) {
                        $option_thumb_image = json_decode($option['option_thumb_image'], true);
                        if ($option_thumb_image[0]) {
                            $image = $this->model_tool_image->resize($option_thumb_image[0], $this->config->get($this->config->get('config_theme') . '_image_cart_width'), $this->config->get($this->config->get('config_theme') . '_image_cart_height'));
                        }
                    }
                }

                //10/01/2020 CATEGORY NAME
                $category_id = $this->model_catalog_category->getCategoryByProductId($product['product_id']);
                $catss = $this->db->query("SELECT * FROM ps_product_to_category WHERE product_id = '" . $product['product_id'] . "'");
                if (isset($category_id['category_id'])) {
                    $cats_name = $this->model_catalog_category->getCategory($category_id['category_id']);
                } else {
                    $cats_name['name'] = '';
                }

                if (isset($catss->rows[1]['category_id']))
                    $category_names = $this->model_catalog_category->getCategory($catss->rows[1]['category_id']);
                //10/01/2020 CATEGORY NAME

                $optionss = $this->db->query("SELECT * FROM ps_cart WHERE product_id = '" . $product['product_id'] . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "' ");

                $sub_products_as_options = array();
                if (isset($optionss->row) AND $optionss->row) {
                    $optionss = json_decode($optionss->row['option'], TRUE);
                    foreach ($optionss as $p_id => $opt) {
                        $data['gift_products'][] = $p_id;
                        $sub_p_info = $this->model_catalog_product->getProduct($p_id);

                        //$find_cart_id = $this->db->query("SELECT ");
                        $sub_products_as_options[] = array(
                            'cart_id' => $opt,
                            'name' => $sub_p_info['name'],
                            'price' => $sub_p_info['price'],
                            'thumb' => $this->model_tool_image->resize($sub_p_info['image'], 100, 100),
                        );
                    }
                }

                // Display prices
                if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                    $unit_price = $this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'));

                    $price = $this->currency->format($unit_price, $this->session->data['currency']);
                    $total = $this->currency->format($unit_price * $product['quantity'], $this->session->data['currency']);
                } else {
                    $price = false;
                    $total = false;
                }

                $recurring = '';


                $customcase_image = $case_image = '';
                if ($product['customcase_image'] != '') {
                    $str = explode('***', $product['customcase_image']);
                    $customcase_image = ($this->request->server['HTTPS'] ? HTTPS_SERVER : HTTP_SERVER) . 'image/' . $str[1];
                    $case_image = ($this->request->server['HTTPS'] ? HTTPS_SERVER : HTTP_SERVER) . 'image/' . $product['image'];
                }


                if($product['customer_order_image']){
                    $customer_order_image = ($this->request->server['HTTPS'] ? HTTPS_SERVER : HTTP_SERVER) . 'image/' . $product['customer_order_image'];
                }else{
                    $customer_order_image = $image;
                }
                $product_type = $this->model_catalog_product->getProduct_type($product['product_id']);
                if ($product_type==11) {
                    $customcase_image=$this->model_catalog_product->get_c_blob($product['p_11_pattern_img']);
                    $customcase_image='data:image;base64,'.($customcase_image);
                }
                $data['products'][] = array(
                    'cart_id' => $product['cart_id'],
                    'product_id' => $product['product_id'],
                    'product_type' => $product_type,
                    'category_brands' => $cats_name['name'],
                    'category_name' => (isset($category_names)) ? $category_names['name'] : '',
                    'thumb' => $image,
                    'sub_products_as_options' => $sub_products_as_options,
                    'name' => $product['name'],
                    'customer_order_image' => $customer_order_image,
                    'customcase_image' => $customcase_image,
                    'case_image' => $case_image,
                    'model' => $product['model'],
                    'option' => array(),
                    'recurring' => $recurring,
                    'quantity' => $product['quantity'],
                    'stock' => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
                    'reward' => ($product['reward'] ? sprintf($this->language->get('text_points'), $product['reward']) : ''),
                    'price' => $price,
                    'total' => $total,
                    'href' => $this->url->link('product/product', 'product_id=' . $product['product_id']),
                    'currency'=>$this->session->data['currency'],
                    'breadcrumb1'=>$breadcrumb1,
                    'breadcrumb2'=>$breadcrumb2,
                    'breadcrumb3'=>$breadcrumb3,
                    'p_stock'=> isset($p_stock) ? $p_stock : 0,
                    'color'=>$color,
                    'collection'=>$collection
                    
                );
            }
            $data['currency']=$this->session->data['currency'];
            if (!$check_other_product_exists_in_cart) {
                $data['error_checkout'] = $this->language->get('error_checkout');
            }

            array_unique($data['gift_products']);

            // Gift Voucher
            $data['vouchers'] = array();

            if (!empty($this->session->data['vouchers'])) {
                foreach ($this->session->data['vouchers'] as $key => $voucher) {
                    $data['vouchers'][] = array(
                        'key' => $key,
                        'description' => $voucher['description'],
                        'amount' => $this->currency->format($voucher['amount'], $this->session->data['currency']),
                        'remove' => $this->url->link('checkout/cart', 'remove=' . $key)
                    );
                }
            }

            // Totals
            $this->load->model('extension/extension');

            $totals = array();
            $taxes = $this->cart->getTaxes();
            $total = 0;

            // Because __call can not keep var references so we put them into an array.
            $total_data = array(
                'totals' => &$totals,
                'taxes' => &$taxes,
                'total' => &$total
            );


            // Display prices
            if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                $sort_order = array();

                $results = $this->model_extension_extension->getExtensions('total');

                foreach ($results as $key => $value) {
                    $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
                }

                array_multisort($sort_order, SORT_ASC, $results);

                foreach ($results as $result) {
                    if ($this->config->get($result['code'] . '_status')) {
                        $this->load->model('extension/total/' . $result['code']);
                        // We have to put the totals in an array so that they pass by reference.
                        $this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
                    }
                }

                $sort_order = array();

                foreach ($totals as $key => $value) {
                    $sort_order[$key] = $value['sort_order'];
                }
                

                array_multisort($sort_order, SORT_ASC, $totals);
            }

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

            foreach ($totals as $total) {
                $data['totals'][] = array(
                    'title' => $total['title'],
                    'text' => $this->currency->format($total['value'], $this->session->data['currency'])
                );
                if($total['code']=='total'){
                    $data['total_amt']=str_replace(',','.',str_replace('₺','',$this->currency->format($total['value'], $this->session->data['currency'])));
                }
            }
            

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

            $data['checkout'] = $this->url->link('checkout/checkout', '', true);

            $this->load->model('extension/extension');

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

            $files = glob(DIR_APPLICATION . '/controller/extension/total/*.php');

            if ($files) {
                foreach ($files as $file) {
                    $result = $this->load->controller('extension/total/' . basename($file, '.php'));

                    if ($result) {
                        $data['modules'][] = $result;
                    }
                }
            }

            $data['CretioOneTag_status'] = $this->config->get('CretioOneTag_status');
            $data['CretioOneTag_id'] = $this->config->get('CretioOneTag_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');
            $data['content_bottom'] = $this->load->controller('common/content_bottom');
            $data['footer'] = $this->load->controller('common/footer');
            $data['header'] = $this->load->controller('common/header');


            /**
             * 02.09.20 check promotions and coupon, if there is return coupon, delete it (ali a.)
             */
            $this->load->model('checkout/coupon');
            //var_dump($data);

            //if (isset($this->session->data['campaign_price_total']) && count($this->session->data['campaign_price_total']) > 0
            if (isset($this->session->data['campaign_price_total'])
                && isset($this->session->data['coupon']) && $this->model_checkout_coupon->isReturnCoupon($this->session->data['coupon']) === true) {

                unset($this->session->data['coupon']);
                $data['error_warning'] = 'Bu kupon promosyon ile kullanılamaz';

                $this->response->redirect($this->url->link('checkout/cart'));
            }
            /**
             * end of update (ali a.)
             */

            if (file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/checkout/cart.tpl')) {
                $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/checkout/cart', $data));
            } else {
                $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'default/template/checkout/cart', $data));
            }
        } else {
            $data['heading_title'] = $this->language->get('heading_title');
            $data['text_error'] = $this->language->get('text_empty');
            $data['button_continue'] = $this->language->get('button_continue');
            $data['continue'] = $this->url->link('common/home');
            unset($this->session->data['success']);
            $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/checkout/emptycart.tpl')) {
                $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/checkout/emptycart', $data));
            } else {
                $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'default/template/checkout/emptycart', $data));
            }
        }
    }

    public function add() {

        $this->load->language('checkout/cart');

        $json = array();

        if (isset($this->request->post['product_id'])) {
            $product_id = (int) $this->request->post['product_id'];
        } else {
            $product_id = 0;
        }
        $p_11_pattern_img="";
        if (isset($this->request->post['p_11_pattern_img'])) {
            $p_11_pattern_img=$this->request->post['p_11_pattern_img'];
        }
        
        $returnError = false;
        if (isset($this->request->post['customizetext']) && mb_strlen($this->request->post['customizetext'])>15) {
            $returnError = true;
        }

        if (isset($this->request->post['gradienttext']) && mb_strlen($this->request->post['gradienttext'])>3) {
            $returnError = true;
        }

        if ($returnError) {
            header('HTTP/1.1 500 Validation Error X');
            header('Content-Type: application/json; charset=UTF-8');
            //die(json_encode(array('message' => 'VALIDATION ERROR', 'code' => 500)));
            $json['error']['text_count'] = 'Kullandiginiz metinde "&" sembolu varsa, lutfen max 10 karakter giriniz! Uyari pencerisini kapattiktan sonra, sayfayi yenileyiniz';
        }

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

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

        if ($product_info) {
            if (isset($this->request->post['quantity']) && ((int) $this->request->post['quantity'] >= $product_info['minimum'])) {
                $quantity = (int) $this->request->post['quantity'];
            } else {
                $quantity = $product_info['minimum'] ? $product_info['minimum'] : 1;
            }


            if (isset($this->request->post['option'])) {
                $option = array_filter($this->request->post['option']);
            } else {
                $option = array();
            }

            $product_options = $this->model_catalog_product->getProductOptions($this->request->post['product_id']);

            foreach ($product_options as $product_option) {
                if ($product_option['required'] && empty($option[$product_option['product_option_id']])) {
                    $json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
                }
            }


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

            $recurrings = $this->model_catalog_product->getProfiles($product_info['product_id']);

            if ($recurrings) {
                $recurring_ids = array();

                foreach ($recurrings as $recurring) {
                    $recurring_ids[] = $recurring['recurring_id'];
                }

                if (!in_array($recurring_id, $recurring_ids)) {
                    $json['error']['recurring'] = $this->language->get('error_recurring_required');
                }
            }
            $pattern_data = $customer_order_image = $order_img = $customcaseimage = '';

            if (isset($this->request->post['order_img']) && $this->request->post['order_img'] != '') {
                $order_img = 'pattern_resize/' . $this->request->post['order_img'];
            }

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

                if ($product_info['product_type'] == 4 || $product_info['product_type'] == 8)
                    $text_position = 'Center';
                else
                    $text_position = 'Bottom';
                $font = 'Glitter';
                $font_color = '000000';
                $texture = '1.jpg';
                $gradienttext = '';
                $text = '';
                $is_circle = '';

                if ($this->request->post['customizetext'] != '') {
                    $text = str_replace('amp;','', trim($this->request->post['customizetext']));
                   
                    $text_count = mb_strlen($text, 'UTF-8');
                    if ($text_count > 15) {
                        $json['error']['text_count'] = 'Kullandiginiz metinde "&" sembolu varsa, lutfen max 10 karakter giriniz! Uyari pencerisini kapattiktan sonra, sayfayi yenileyiniz';
                    }
                }

                if ($this->request->post['customizeFont'] != null) {
                    $font = $this->request->post['customizeFont'];
                }
                if ($this->request->post['customizeColor'] != null) {
                    $font_color = $this->request->post['customizeColor'];
                }
                if ($this->request->post['customizetextPosition'] != null) {
                    $text_position = $this->request->post['customizetextPosition'];
                }

                if (isset($this->request->post['texture'])) {
                    $texture = $this->request->post['texture'];
                }
                if (isset($this->request->post['product_type'])) {
                    $product_type = $this->request->post['product_type'];
                }
                if (isset($this->request->post['gradienttext']) && trim($this->request->post['gradienttext']) != '') {
                    $gradienttext = $this->request->post['gradienttext'];
                }
                $text2 = '';
                if (isset($this->request->post['customizetext2'])) {
                    $text2 = trim($this->request->post['customizetext2']);
                    $text_count = mb_strlen($text2, 'UTF-8');
                    if ($text_count > 15) {
                        $json['error']['text_count'] = 'Kullandiginiz metinde "&" sembolu varsa, lutfen max 10 karakter giriniz! Uyari pencerisini kapattiktan sonra, sayfayi yenileyiniz';
                    }
                }

                $pattern_data = json_encode(array('pattern_text' => htmlspecialchars_decode($text), 'font' => $font, 'font_color' => $font_color, 'text_pos' => $text_position, 'pattern_text2' => htmlspecialchars_decode($text2), 'gradienttext' => htmlspecialchars_decode($gradienttext), 'texture' => $texture, 'product_type' => $product_type), JSON_UNESCAPED_UNICODE);
            }

            if (isset($this->request->post['customcaseimage'])) {
                $customcaseimage = $this->request->post['customcaseimage'];
                $customcaseimage = $product_info['href'] . '***' . $customcaseimage;
            }

            if (!$json) {
                $cart_id = $this->cart->add($this->request->post['product_id'], $quantity, $option, $recurring_id, $order_img, $customer_order_image, $pattern_data, $customcaseimage,$p_11_pattern_img);

               // $log = new Log("cart_items/". $cart_id ."_AddLog.txt");
               // $log->write($this->request->post);
                $this->session->data['cart_count_log'][] = $cart_id;

                $json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('checkout/cart'));
                $json['cart_id'] = $cart_id;
                // Unset all shipping and payment methods
                unset($this->session->data['shipping_method']);
                unset($this->session->data['shipping_methods']);
                unset($this->session->data['payment_method']);
                unset($this->session->data['payment_methods']);

                // Totals
                $this->load->model('extension/extension');

                $totals = array();
                $taxes = $this->cart->getTaxes();
                $total = 0;

                // Because __call can not keep var references so we put them into an array.
                $total_data = array(
                    'totals' => &$totals,
                    'taxes' => &$taxes,
                    'total' => &$total
                );

                // Display prices
                if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                    $sort_order = array();

                    $results = $this->model_extension_extension->getExtensions('total');

                    foreach ($results as $key => $value) {
                        $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
                    }

                    array_multisort($sort_order, SORT_ASC, $results);

                    foreach ($results as $result) {
                        if ($this->config->get($result['code'] . '_status')) {
                            $this->load->model('extension/total/' . $result['code']);

                            // We have to put the totals in an array so that they pass by reference.
                            $this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
                        }
                    }

                    $sort_order = array();

                    foreach ($totals as $key => $value) {
                        $sort_order[$key] = $value['sort_order'];
                    }

                    array_multisort($sort_order, SORT_ASC, $totals);
                }
                
                /////////////////show toast messages/////////////////////////////////
                $total_cart_item = $this->cart->countProducts();

                $field_arr = $this->config->get('ToastMessages');


                
                if($field_arr){
                    $final_array = array();
                    for ($i=0; $i < count($field_arr['message']) ; $i++) { 
                        $final_array[$i]['no_of_item'] = $field_arr['no_of_item'][$i];
                        $final_array[$i]['message'] = $field_arr['message'][$i];
                        $final_array[$i]['status'] = $field_arr['status'][$i];
                    }
            
                    $toast_message = '';
                    $message_flag = false;
                    foreach ($final_array as $value) {
                        if($value['no_of_item'] == $total_cart_item){
                            if($value['status'] == 1){
                                $toast_message = $value['message'];
                                $message_flag = true;
                            }
                        }
                    }
    
                    if($message_flag){
                        $json['flag'] = true;
                        $json['toast_msgs'] = $toast_message;
                    }else{
                        $json['flag'] = false;
                    }
                }else{
                    $json['flag'] = false;
                }
                
                /////////////////////////////////////////////////////////////////////

                $json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total, $this->session->data['currency']));
                $json['itemstotal'] = $this->cart->countProducts();
                $json['text_items_only'] = $this->cart->countProducts();

                $json['text_price_only'] = $this->currency->format($total, $this->session->data['currency']);
            } else {
                $json['redirect'] = str_replace('&amp;', '&', $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']));
                if (isset($this->request->post['click']) || isset($this->request->post['ad_click'])) {
                    return $json;
                }
            }
        }

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

    public function addproductcampaign() {

        $this->load->language('checkout/cart');

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


        $json = array();

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

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

        if (isset($this->request->post['is_add_to_cart'])) {
            $is_add_to_cart = $this->request->post['is_add_to_cart'];
        }
        if ($campaign_product_id == 0 || $product_id == 0) {
            die;
        }

        $product_info = $this->model_catalog_product->getProduct($campaign_product_id);
        $cart_query = $this->db->query("SELECT cart_id,product_id,`option` FROM ps_cart WHERE api_id = '" . (isset($this->session->data['api_id']) ? (int) $this->session->data['api_id'] : 0) . "' AND customer_id = '" . (int) $this->customer->getId() . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "' AND product_id=" . $product_id . "  order by cart_id desc limit 1")->row;

        if ($cart_query) {

            $result = $this->db->query("SELECT cart_id FROM ps_cart WHERE api_id = '" . (isset($this->session->data['api_id']) ? (int) $this->session->data['api_id'] : 0) . "' AND customer_id = '" . (int) $this->customer->getId() . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "' AND product_id=" . $campaign_product_id . " order by cart_id desc limit 1")->row;

            //$this->product->dump($result);
            if ($is_add_to_cart) {
                /*if ($result)
                    $cart_id = $result['cart_id'];
                else*/
                    $cart_id = $this->cart->add($campaign_product_id, 1, array(), 0, '', '', '', '');
            }else {

                if ($result)
                    $this->db->query("delete from   ps_cart  WHERE cart_id = '" . $result['cart_id'] . "'");
            }

            $product_option = json_decode($cart_query['option'], true);

            if ($is_add_to_cart) {
                if (!isset($product_option[$campaign_product_id])) {
                    $product_option[$campaign_product_id] = $cart_id;
                    $product_option = json_encode($product_option);
                } else {
                    $product_option = json_encode($product_option);
                }
                $json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('checkout/cart'));
            } else {
                unset($product_option[$campaign_product_id]);
                $product_option = json_encode($product_option);
                $json['success'] = sprintf($this->language->get('text_removed'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('checkout/cart'));
            }

            $this->db->query("update  ps_cart set  `option`='" . $product_option . "' WHERE cart_id = '" . $cart_query['cart_id'] . "'");
            $json['itemstotal'] = $this->cart->countProducts();
            $json['text_items_only'] = $this->cart->countProducts();
        } /*else {
            if ($this->cart->hasProducts()) {
                $product_info = $this->model_catalog_product->getProduct($campaign_product_id);
                $result = $this->db->query("SELECT cart_id FROM ps_cart WHERE api_id = '" . (isset($this->session->data['api_id']) ? (int) $this->session->data['api_id'] : 0) . "' AND customer_id = '" . (int) $this->customer->getId() . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "' AND product_id=" . $campaign_product_id . " order by cart_id desc limit 1")->row;
                $pattern_data = json_encode(array('pattern_text' => '', 'font' => 'Glitter', 'font_color' => '000000', 'text_pos' => 'Bottom', 'pattern_text2' => '', 'gradienttext' => '', 'texture' => '1.jpg', 'product_type' => $product_info['product_type']), JSON_UNESCAPED_UNICODE);
                $customer_order_image = '';

                if ($is_add_to_cart) {
                    if ($product_info['image'] != '') {
                        $pathinfo = pathinfo($product_info['image']);

                        $image = 'cache/' . $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '-100x100.' . $pathinfo['extension'];

                        $pattern_image = file_get_contents(DIR_IMAGE . $image);
                        if ($pattern_image) {
                            $filename = md5(uniqid(rand(), true));
                            $customer_order_image = 'customer_order_images/' . $filename . '.jpg';
                            $file = DIR_IMAGE . $customer_order_image;
                            file_put_contents($file, $pattern_image);
                        }
                    }

                    if ($result)
                        $cart_id = $result['cart_id'];
                    else
                        $cart_id = $this->cart->add($campaign_product_id, 1, array(), 0, ($customer_order_image != '' ? $customer_order_image : ''), ($customer_order_image != '' ? $customer_order_image : ''), $pattern_data, '');
                    $json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $campaign_product_id), $product_info['name'], $this->url->link('checkout/cart'));
                }else {
                    if ($result)
                        $this->db->query("delete from   ps_cart  WHERE cart_id = '" . $result['cart_id'] . "'");
                    $json['success'] = sprintf($this->language->get('text_removed'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('checkout/cart'));
                }

                $json['itemstotal'] = $this->cart->countProducts();
                $json['text_items_only'] = $this->cart->countProducts();
            }else {
                if ($is_add_to_cart) {
                    $json['error'] = $this->language->get('text_error_product');
                    $json['text_items_only'] = $this->cart->countProducts();
                }
            }
        }*/

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

    public function edit() {
        $this->load->language('checkout/cart');

        $json = array();

        // Update
        if (!empty($this->request->post['quantity'])) {
            foreach ($this->request->post['quantity'] as $key => $value) {
                $this->cart->update($key, $value);
            }

            $this->session->data['success'] = $this->language->get('text_remove');

            unset($this->session->data['shipping_method']);
            unset($this->session->data['shipping_methods']);
            unset($this->session->data['payment_method']);
            unset($this->session->data['payment_methods']);
            unset($this->session->data['reward']);

            $this->response->redirect($this->url->link('checkout/cart'));
        }



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

    public function remove() {
        $this->load->language('checkout/cart');

        $json = array();

        // Remove
        if (isset($this->request->post['key'])) {


            $remove_options = $this->db->query("SELECT * FROM ps_cart WHERE cart_id = '" . $this->request->post['key'] . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "' ");
            $remove_options = json_decode($remove_options->rows [0]['option']);

            foreach ($remove_options as $r_option)
                $this->cart->remove($r_option);

            $this->cart->remove($this->request->post['key']);

            unset($this->session->data['vouchers'][$this->request->post['key']]);

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

            unset($this->session->data['shipping_method']);
            unset($this->session->data['shipping_methods']);
            unset($this->session->data['payment_method']);
            unset($this->session->data['payment_methods']);
            unset($this->session->data['reward']);

            // Totals
            $this->load->model('extension/extension');

            $totals = array();
            $taxes = $this->cart->getTaxes();
            $total = 0;

            // Because __call can not keep var references so we put them into an array.
            $total_data = array(
                'totals' => &$totals,
                'taxes' => &$taxes,
                'total' => &$total
            );

            // Display prices
            if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                $sort_order = array();

                $results = $this->model_extension_extension->getExtensions('total');

                foreach ($results as $key => $value) {
                    $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
                }

                array_multisort($sort_order, SORT_ASC, $results);

                foreach ($results as $result) {
                    if ($this->config->get($result['code'] . '_status')) {
                        $this->load->model('extension/total/' . $result['code']);

                        // We have to put the totals in an array so that they pass by reference.
                        $this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
                    }
                }

                $sort_order = array();

                foreach ($totals as $key => $value) {
                    $sort_order[$key] = $value['sort_order'];
                }

                array_multisort($sort_order, SORT_ASC, $totals);
            }

            $json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total, $this->session->data['currency']));
        }

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

    public function test() {
        $this->load->model('checkout/coupon');

        if ($this->model_checkout_coupon->isReturnCoupon('R-PNYETJGGJss') === true) {
            echo 'yes';
        }
        else {
            echo 'no';
        }

    }

    public function cartMailNotice()
    {

        die();

        //https://www.deercase.com/index.php?route=checkout/cart/cartMailNotice

        $last_2_day = date('Y-m-d', strtotime('-2 days'));

        $rows = $this->db->query("SELECT cart_id, customer_id, product_id, date_added, quantity  FROM ps_cart WHERE customer_id != 0 AND mail = 0 AND date_added < '". $last_2_day ."' LIMIT 10 ")->rows;
        //var_dump($rows); die();
        foreach($rows as $row){
                $this->sendMail($row);
            
        }
    }

    public function sendMail($mailData)
    {

        //var_dump($mailData); die();

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

        $customer = $this->model_account_customer->getCustomer($mailData['customer_id']);
        //var_dump($customer ); die();
        $text = "\n\n";

        $this->load->model('catalog/product');
        $product = $this->model_catalog_product->getProduct($mailData['product_id']);

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

        $productData[] = array(
            'image' => $this->model_tool_image->resize($product['image'], $this->config->get($this->config->get('config_theme') . '_image_cart_width'), $this->config->get($this->config->get('config_theme') . '_image_cart_height')),
            'name' => $product['name'],
            'model' => $product['model'],
            'price' => $price,
            'total' => $total,
            'quantity' => $mailData['quantity'],
            'option' => []
            
        );

        $data = array(
            'store_name' => 'Deercase',
            'store_url' => 'https://www.deercase.com/',
            'title' => 'Deercase Cart Notice Mail',
            'logo' => 'https://www.deercase.com/catalog/view/theme/deercase/image/deer-case-logo-86x30.png',
            'text_greeting' => '..',
            'text_link' => '..',
            'customer' => $customer,
            'text_order_detail' => 'text_order_detail',
            'text_footer' => 'Deercase',
            'products' => $productData,
            'text_product' => 'Ürünler',
            'text_model' => 'Ürün Kodu',
            'text_quantity' => 'Adet',
            'text_price' => 'Fiyat',
            'text_total' => 'Total',
            'totals' => []

        );

        $password = 'ixtklziaahaxveom';
        $mail_from = 'marketing@deercase.com';

        $subject = 'Sepetinizde Kalan Ürünler!';

        $mail = new Mail();
        $mail->protocol = 'mail';
        $mail->parameter = $this->config->get('config_mail_parameter');
        $mail->smtp_hostname = 'smtp.yandex.com';
        $mail->smtp_username = $mail_from;
        $mail->smtp_password = html_entity_decode($password, ENT_QUOTES, 'UTF-8');
        $mail->smtp_port = $this->config->get('config_mail_smtp_port');
        $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

        $mail->setTo($customer['email']);
        $mail->setFrom($mail_from);
    
        $mail->setSender(html_entity_decode('Deercase', ENT_QUOTES, 'UTF-8'));
        $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));

        //var_dump($data); die();

        $mail->setHtml($this->load->view(DIR_TEMPLATE . 'default/template/mail/cart_mail_notice', $data));

        //var_dump($mail); die();

        $log = new Log("cartNoticeMailLog/" . $mailData['cart_id']. '_Log.txt');
        $log->write($mail);

        $mail->setText($text);
        $response = $mail->send();

        $this->db->query("UPDATE ps_cart SET mail = 1 WHERE cart_id = '". (int)$mailData['cart_id'] ."' ");

        //var_dump($response); die();

        
    }

    public function TestSendMail()
    {

        die();
        //https://www.deercase.com/index.php?route=checkout/cart/TestSendMail


        $password = 'ixtklziaahaxveom';
        $mail_from = 'marketing@deercase.com';

        $subject = 'Sepet maili';

        $text = 'Test Mail Deercase';

        $data = [];

        $mail = new Mail();
        $mail->protocol = 'mail';
        $mail->parameter = $this->config->get('config_mail_parameter');
        $mail->smtp_hostname = 'smtp.yandex.com';
        $mail->smtp_username = $mail_from;
        $mail->smtp_password = html_entity_decode($password, ENT_QUOTES, 'UTF-8');
        $mail->smtp_port = $this->config->get(465);
        $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

        $mail->setTo('bilal603@gmail.com');
        $mail->setFrom($mail_from);
    
        $mail->setSender(html_entity_decode('Deercase', ENT_QUOTES, 'UTF-8'));
        $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));

        $mail->setHtml($this->load->view(DIR_TEMPLATE . 'default/template/mail/order', $data));

        $mail->setText($text);
        $response = $mail->send();

        var_dump($response ); die();

    }




}
