<?php
require_once DIR_SYSTEM . "library" . DIRECTORY_SEPARATOR . "iyzico" . DIRECTORY_SEPARATOR . "IyzipayBootstrap.php";

class ControllerToolFunctions extends Controller{

    use Byexpress;

    public function index()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions


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

        $results = $this->model_catalog_product->getProductImages(1125182);

        foreach ($results as $result) {
            $exten = $ext = pathinfo($result['image'], PATHINFO_EXTENSION);
            var_dump($exten);
        }

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

        var_dump($config_product); die();

    }

    public function zubizu_report_export()
    {

        die();

        $coupons = $this->db->query("SELECT c.coupon_id ,c.name, c.code FROM ps_coupon c WHERE c.name = 'ZUBIZU' ")->rows;

        $coupon_histories = $this->db->query("SELECT o.order_id, c.name, c.coupon_id, c.code, ch.date_added, o.total, ch.amount FROM ps_coupon_history ch
        LEFT JOIN ps_coupon  c ON (ch.coupon_id = c.coupon_id)
        LEFT JOIN ps_order o ON (ch.order_id = o.order_id)
        WHERE c.name = 'ZUBIZU' ")->rows;

        //var_dump($coupon_histories); die();

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)

            ->setCellValue('A1','ExternalCampaignCode')
            ->setCellValue('B1','CouponCode')
            ->setCellValue('C1','TransactionDate')
            ->setCellValue('D1','OrignalTotalPrice')
            ->setCellValue('E1','PaidTotal')
            ->setCellValue('F1','ZubizuDiscountAmount')
            ->setCellValue('G1','TaxRate')
            ->setCellValue('H1','InvoiceNumber/OrderNumber');

        $file_name = $this->config->get('config_name').'-'.@date("Y-m-d-His")."-zubizu-orders.xls" ;


        $row_i = 2;
        foreach ($coupon_histories as $order){

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'. $row_i, 'ZUBIZU')
                ->setCellValue('B'. $row_i, $order['code'])
                ->setCellValue('C'. $row_i, $order['date_added'])
                ->setCellValue('D'. $row_i, $order['total'])
                ->setCellValue('E'. $row_i, $order['total'] + $order['amount'])
                ->setCellValue('F'. $row_i, $order['amount'])
                ->setCellValue('G'. $row_i, '0,18')
                ->setCellValue('H'. $row_i, $order['order_id']);

            $row_i++;

        }


        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$file_name.'"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;








    }

    public function zubizu_report()
    {

        die();

        //echo abs(((50.31 / 55.90) * 100) - 100); die();

        $coupons = $this->db->query("SELECT c.coupon_id ,c.name, c.code FROM ps_coupon c WHERE c.name = 'ZUBIZU' ")->rows;

        $coupon_histories = $this->db->query("SELECT o.order_id, c.name, c.coupon_id FROM ps_coupon_history ch
        LEFT JOIN ps_coupon  c ON (ch.coupon_id = c.coupon_id)
        LEFT JOIN ps_order o ON (ch.order_id = o.order_id)
        WHERE c.name = 'ZUBIZU' ")->rows;

        var_dump($coupon_histories); die();

        // (50.31 / 55.90) - 100

        $orders = $this->db->query("SELECT order_id, order_status_id, customer_id, date_added FROM ps_order WHERE order_status_id = 5 AND date_added > '2020-04-01 00:00:00' ")->rows;
        //var_dump($orders); die();
        $order_ids = array();
        foreach ($orders as $order){

            $get_order_totals = $this->db->query("SELECT * FROM ps_order_total WHERE order_id = '".$order['order_id']."' ")->rows;
            $coupon_flag = false;
            $row_total = 0;
            $coupon_price = 0;
            $promotion_total = 0;

            foreach ($get_order_totals as $total){
                if($total['code'] == 'promotion_total'){
                    $promotion_total = $total['value'];
                }

                if($total['code'] == 'coupon'){
                    $coupon_price = abs($total['value']);
                }

                if($total['code'] == 'total'){
                    $row_total = $total['value'];
                }
                if($total['code'] == 'coupon')
                    $coupon_flag = true;
            }
            if($coupon_flag){

                $discount_rate =  round(abs((($row_total / ($row_total + $coupon_price)) * 100) - 100));

                if($discount_rate != 20 AND $discount_rate != 100){
                    $order_ids[] = array(
                        'order_id' => $order['order_id'],
                        'customer_id' => $order['customer_id'],
                        'date_added' => $order['date_added'],
                        'amount' => $coupon_price
                    );
                }
            }


        }


        $coupons = $this->db->query("SELECT code, coupon_id FROM ps_coupon WHERE name = 'ZUBIZU' ")->rows;



        $count = 0;
        foreach ($order_ids as $order_id){
            $count++;
            $rand = rand(0,20000);
            //var_dump($coupons[$rand]['code']);
            //$rand_coupon = $this->db->query("SELECT * FROM ps_coupon WHERE code = '". $this->db->escape($coupons[rand(0,20000)]['code']) ."' ")->row;
                //var_dump($rand_coupon); die();
            $this->db->query("INSERT INTO ps_coupon_history
				SET coupon_id = '" . (int)$coupons[$rand]['coupon_id'] . "', 
				order_id = '" . (int)$order_id['order_id'] . "',
				customer_id = '" . (int)$order_id['customer_id'] . "',
				amount = '" . (float)$order_id['amount'] . "',
				date_added = '" . $this->db->escape($order_id['date_added']) . "' ");
        }

        echo $count;

    }

    public function barcode_generate()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/barcode_generate

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


        $products = $this->db->query("SELECT p.product_id FROM ps_product p 
        LEFT JOIN ps_product_description pd ON (p.product_id = pd.product_id) WHERE p.product_stock_id = 0 AND RAND() LIMIT 15000 ")->rows;

        $count = 0;

        foreach ($products as $product){

            $product_stock_id = 0;

            $categorti_id_info = $this->model_catalog_product->getCategoryByProductId($product['product_id']);


            if(isset($categorti_id_info[1]['category_id'])){

                $category_id = $categorti_id_info[1]['category_id'];
                $category_name = $categorti_id_info[1]['name'];


                $get_attributes = $this->db->query("SELECT ad.name, pa.product_id, pa.attribute_id, ag.attribute_group_id FROM ps_product_attribute pa
                LEFT JOIN ps_attribute a ON (pa.attribute_id = a.attribute_id) 
                LEFT JOIN ps_attribute_description ad ON (a.attribute_id = ad.attribute_id)
                LEFT JOIN ps_attribute_group ag ON (a.attribute_group_id = ag.attribute_group_id) 
                WHERE pa.product_id = '". (int)$product['product_id'] ."' ORDER BY ag.attribute_group_id ASC ")->rows;

                $collection_id = $get_attributes[0]['attribute_id'];
                $collection_name = $get_attributes[0]['name'];

                $color_id = $get_attributes[1]['attribute_id'];
                $color_name = $get_attributes[1]['name'];

                $product_stock_id = $category_id . $collection_id . $color_id;



                try {
                    $this->db->query("UPDATE ps_product SET product_stock_id = '". $product_stock_id ."' WHERE product_id = '". (int)$product['product_id'] ."' ");
                    $get_product_stock_id = $this->db->query("SELECT product_stock_id FROM ps_product_stock WHERE product_stock_id = '". $product_stock_id ."' ")->row;
                    if(!$get_product_stock_id){
                        $this->db->query("INSERT INTO ps_product_stock SET product_stock_id = '". $product_stock_id ."', category_id	= '". (int)$category_id ."', category_name = '". $this->db->escape($category_name) ."', collection_id = '". (int)$collection_id ."', collection_name = '". $this->db->escape($collection_name) ."', color_id = '". (int)$color_id ."', color_name = '". $this->db->escape($color_name) ."', date_added = NOW() ");


                        $count++;
                    }

                }catch (Exception $e){
                    echo 'Message: ' .$e->getMessage();
                }


               // echo $product_stock_id . '<br>';
                //echo $category_id . ' -> ' . $category_name . ' --> ' . $product_stock_id . '<br>';


                //$this->db->query("UPDATE ps_product SET product_stock_id = '". $product_stock_id ."' WHERE product_id = '". (int)$product['product_id'] ."' ");

                //$this->db->query("DELETE FROM ps_product_stock WHERE product_stock_id = '". $product_stock_id ."' ");


               /* $get_product_stock_id = $this->db->query("SELECT product_stock_id FROM ps_product_stock WHERE product_stock_id = '". $product_stock_id ."' ")->row;

                if(!$get_product_stock_id){
                    $this->db->query("INSERT INTO ps_product_stock SET product_stock_id = '". $product_stock_id ."', category_id	= '". (int)$category_id ."', category_name = '". $this->db->escape($category_name) ."', collection_id = '". (int)$collection_id ."', collection_name = '". $this->db->escape($collection_name) ."', color_id = '". (int)$color_id ."', color_name = '". $this->db->escape($color_name) ."', date_added = NOW() ");

                } */





            }else{
                //echo "Ürüne bağlı 2. alt kategori bulunamadı!. Ürün ID: " . $product['product_id'] . '<hr>';
            }


            //2147483647


        }

        echo $count . ' Adet satır işlendi! <br>';

        echo $this->db->query("SELECT product_id FROM ps_product WHERE product_stock_id = 0 ")->num_rows . ' Adet işlenmemiş satır var!';






    }

    public function barcode_generate_new_count()
    {
        die();
        //https://www.deercase.com/index.php?route=tool/functions/barcode_generate_new_count

        echo count($this->session->data['ps_product_stock']);

    }

    public function barcode_generate_new()
    {

        die();


        $this->session->data['ps_product_stock'] = $this->db->query("SELECT * FROM ps_product_stock WHERE name != '' ")->rows;


        //$results = $this->db->query("SELECT * FROM ps_product_stock WHERE name != '' LIMIT 0,20 ")->rows;
        //$results = $this->db->query("SELECT * FROM ps_product_stock WHERE name != '' ")->rows;

        $results = $this->session->data['ps_product_stock'];

        var_dump($results); die();


        $count = 0;
        foreach ($results as $key => $result){
            $category_id = $result['category_id'];
            $collection_id = $result['collection_id'];
            $color_id = $result['color_id'];

            $products = $this->db->query("SELECT p.product_id FROM ps_product p 
                LEFT JOIN ps_product_to_category p2c ON (p.product_id = p2c.product_id)     
                LEFT JOIN ps_product_attribute pa ON (p.product_id = pa.product_id)
                WHERE p2c.category_id = '".$category_id."' AND pa.attribute_id IN ('". $collection_id ."','". $color_id ."') 
            
                ")->rows;
            //var_dump($products); die();



            if($products){
                echo $result['product_stock_id'] . '<br>';
                foreach ($products as $product){
                    $count++;
                    $this->db->query("UPDATE ps_product SET product_stock_id = '". $result['product_stock_id'] ."' WHERE product_id = '".$product['product_id']."' ");
                    //$this->db->query("UPDATE ps_product SET product_stock_id = 333 WHERE product_id = '".$product['product_id']."' ");
                }
            }
            //echo $count;
            unset($this->session->data['ps_product_stock'][$key]);

            $log->write(count($this->session->data['ps_product_stock']));
            echo count($this->session->data['ps_product_stock']); die();

        }

        echo count($this->session->data['ps_product_stock']);


    }

    public function mail_template_testing()
    {


        die();
        if(isset($this->request->get['order_id'])){

            $order_id = (int)$this->request->get['order_id'];
            $this->addOrderHistory($order_id, 0);

        }else{
            echo "Order ID yok!";
        }

    }

    private function addOrderHistory($order_id, $order_status_id, $comment = '', $notify = false, $override = false) {
        

        die();
        $this->load->model('checkout/order');

        $order_info = $this->model_checkout_order->getOrder($order_id);

        if ($order_info) {
           
            // Fraud Detection
            $this->load->model('account/customer');
            $this->load->model('tool/image');

            $customer_info = $this->model_account_customer->getCustomer($order_info['customer_id']);

            if ($customer_info && $customer_info['safe']) {
                $safe = true;
            } else {
                $safe = false;
            }

            /*
            // Only do the fraud check if the customer is not on the safe list and the order status is changing into the complete or process order status
            if (!$safe && !$override && in_array($order_status_id, array_merge($this->config->get('config_processing_status'), $this->config->get('config_complete_status')))) {
                // Anti-Fraud
                $this->load->model('extension/extension');

                $extensions = $this->model_extension_extension->getExtensions('fraud');

                foreach ($extensions as $extension) {
                    if ($this->config->get($extension['code'] . '_status')) {
                        $this->load->model('extension/fraud/' . $extension['code']);
                        $fraud_status_id = $this->{'model_fraud_' . $extension['code']}->check($order_info);
                        if ($fraud_status_id) {
                            $order_status_id = $fraud_status_id;
                        }
                    }
                }
            }

            // If current order status is not processing or complete but new status is processing or complete then commence completing the order
            if (!in_array($order_info['order_status_id'], array_merge($this->config->get('config_processing_status'), $this->config->get('config_complete_status'))) && in_array($order_status_id, array_merge($this->config->get('config_processing_status'), $this->config->get('config_complete_status')))) {
                // Redeem coupon, vouchers and reward points
                $order_total_query = $this->db->query("SELECT * FROM ps_order_total WHERE order_id = '" . (int) $order_id . "' ORDER BY sort_order ASC");

                foreach ($order_total_query->rows as $order_total) {
                    $this->load->model('extension/total/' . $order_total['code']);

                    if (property_exists($this->{'model_extension_total_' . $order_total['code']}, 'confirm')) {
                        // Confirm coupon, vouchers and reward points
                        $fraud_status_id = $this->{'model_extension_total_' . $order_total['code']}->confirm($order_info, $order_total);


                        // If the balance on the coupon, vouchers and reward points is not enough to cover the transaction or has already been used then the fraud order status is returned.
                        if ($fraud_status_id) {
                            $order_status_id = $fraud_status_id;
                        }
                    }
                }


                // Add commission if sale is linked to affiliate referral.
                if ($order_info['affiliate_id'] && $this->config->get('config_affiliate_auto')) {
                    $this->load->model('affiliate/affiliate');

                    $this->model_affiliate_affiliate->addTransaction($order_info['affiliate_id'], $order_info['commission'], $order_id);
                }

                // Stock subtraction
                $order_product_query = $this->db->query("SELECT * FROM ps_order_product WHERE order_id = '" . (int) $order_id . "'");

                foreach ($order_product_query->rows as $order_product) {
                    $this->db->query("UPDATE ps_product SET quantity = (quantity - " . (int) $order_product['quantity'] . ") WHERE product_id = '" . (int) $order_product['product_id'] . "' AND subtract = '1'");

                    $order_option_query = $this->db->query("SELECT * FROM ps_order_option WHERE order_id = '" . (int) $order_id . "' AND order_product_id = '" . (int) $order_product['order_product_id'] . "'");

                    foreach ($order_option_query->rows as $option) {
                        $this->db->query("UPDATE ps_product_option_value SET quantity = (quantity - " . (int) $order_product['quantity'] . ") WHERE product_option_value_id = '" . (int) $option['product_option_value_id'] . "' AND subtract = '1'");
                    }
                }
            }


            // If old order status is the processing or complete status but new status is not then commence restock, and remove coupon, voucher and reward history
            if (in_array($order_info['order_status_id'], array_merge($this->config->get('config_processing_status'), $this->config->get('config_complete_status'))) && !in_array($order_status_id, array_merge($this->config->get('config_processing_status'), $this->config->get('config_complete_status')))) {
                // Restock
                $product_query = $this->db->query("SELECT * FROM ps_order_product WHERE order_id = '" . (int) $order_id . "'");

                foreach ($product_query->rows as $product) {
                    $this->db->query("UPDATE ps_product SET quantity = (quantity + " . (int) $product['quantity'] . ") WHERE product_id = '" . (int) $product['product_id'] . "' AND subtract = '1'");

                    $option_query = $this->db->query("SELECT * FROM ps_order_option WHERE order_id = '" . (int) $order_id . "' AND order_product_id = '" . (int) $product['order_product_id'] . "'");

                    foreach ($option_query->rows as $option) {
                        $this->db->query("UPDATE ps_product_option_value SET quantity = (quantity + " . (int) $product['quantity'] . ") WHERE product_option_value_id = '" . (int) $option['product_option_value_id'] . "' AND subtract = '1'");
                    }
                }

                // Remove coupon, vouchers and reward points history
                $this->load->model('account/order');

                $order_total_query = $this->db->query("SELECT * FROM ps_order_total WHERE order_id = '" . (int) $order_id . "' ORDER BY sort_order ASC");

                foreach ($order_total_query->rows as $order_total) {
                    $this->load->model('extension/total/' . $order_total['code']);

                    if (property_exists($this->{'model_extension_total_' . $order_total['code']}, 'unconfirm')) {
                        $this->{'model_extension_total_' . $order_total['code']}->unconfirm($order_id);
                    }
                }

                // Remove commission if sale is linked to affiliate referral.
                if ($order_info['affiliate_id']) {
                    $this->load->model('affiliate/affiliate');

                    $this->model_affiliate_affiliate->deleteTransaction($order_id);
                }
            }

            */
            $this->cache->delete('product');

            //var_dump($order_info); die();

            $order_status_id = $order_info['order_status_id'];

            // If order status is 0 then becomes greater than 0 send main html email
            if ($order_status_id) {
                // Check for any downloadable products
                $download_status = false;

                $order_product_query = $this->db->query("SELECT * FROM ps_order_product WHERE order_id = '" . (int) $order_id . "'");

                foreach ($order_product_query->rows as $order_product) {
                    // Check if there are any linked downloads
                    $product_download_query = $this->db->query("SELECT COUNT(*) AS total FROM ps_product_to_download WHERE product_id = '" . (int) $order_product['product_id'] . "'");

                    if ($product_download_query->row['total']) {
                        $download_status = true;
                    }
                }

                // Load the language for any mails that might be required to be sent out
                $language = new Language($order_info['language_code']);
                $language->load($order_info['language_code']);
                $language->load('mail/order');

                $order_status_query = $this->db->query("SELECT * FROM ps_order_status WHERE order_status_id = '" . (int) $order_status_id . "' AND language_id = '" . (int) $order_info['language_id'] . "'");

                if ($order_status_query->num_rows) {
                    $order_status = $order_status_query->row['name'];
                } else {
                    $order_status = '';
                }

                $subject = sprintf($language->get('text_new_subject'), html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'), $order_id);

                // HTML Mail
                $data = array();

                $data['title'] = sprintf($language->get('text_new_subject'), $order_info['store_name'], $order_id);

                $data['text_greeting'] = sprintf($language->get('text_new_greeting'), $order_info['store_name']);
                $data['text_link'] = $language->get('text_new_link');
                $data['text_download'] = $language->get('text_new_download');
                $data['text_order_detail'] = $language->get('text_new_order_detail');
                $data['text_instruction'] = $language->get('text_new_instruction');
                $data['text_order_id'] = $language->get('text_new_order_id');
                $data['text_date_added'] = $language->get('text_new_date_added');
                $data['text_payment_method'] = $language->get('text_new_payment_method');
                $data['text_shipping_method'] = $language->get('text_new_shipping_method');
                $data['text_email'] = $language->get('text_new_email');
                $data['text_telephone'] = $language->get('text_new_telephone');
                $data['text_ip'] = $language->get('text_new_ip');
                $data['text_order_status'] = $language->get('text_new_order_status');
                $data['text_payment_address'] = $language->get('text_new_payment_address');
                $data['text_shipping_address'] = $language->get('text_new_shipping_address');
                $data['text_product'] = $language->get('text_new_product');
                $data['text_model'] = $language->get('text_new_model');
                $data['text_quantity'] = $language->get('text_new_quantity');
                $data['text_price'] = $language->get('text_new_price');
                $data['text_total'] = $language->get('text_new_total');
                $data['text_footer'] = $language->get('text_new_footer');

                $data['logo'] = $this->config->get('config_url') . 'image/' . $this->config->get('config_logo');
                $data['store_name'] = $order_info['store_name'];
                $data['store_url'] = $order_info['store_url'];
                $data['customer_id'] = $order_info['customer_id'];
                $data['link'] = $order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_id;
                $data['link2'] = $order_info['store_url'] . 'index.php?route=account/guestorder&order_id=' . $order_id . '&email=' . $order_info['email'];

                $data['firstname'] = $order_info['firstname'];
                $data['lastname'] = $order_info['lastname'];


                if ($download_status) {
                    $data['download'] = $order_info['store_url'] . 'index.php?route=account/download';
                } else {
                    $data['download'] = '';
                }

                $data['order_id'] = $order_id;
                $data['date_added'] = date($language->get('date_format_short'), strtotime($order_info['date_added']));
                $data['payment_method'] = $order_info['payment_method'];
                $data['shipping_method'] = $order_info['shipping_method'];
             
              if($_SERVER['REMOTE_ADDR']=='111.88.6.229'){
                   $data['email'] = 'alirasooldev@gmail.com';
              }else{
                   $data['email'] = $order_info['email'];
                   
                 // $data['email'] = $order_info['tolga.turkmen@piyersoft.com'];
              }
              
               
                $data['telephone'] = $order_info['telephone'];
                $data['ip'] = $order_info['ip'];
                $data['order_status'] = $order_status;

               // print_r($data); die();


                $xshippingpro_desc_mail = $this->config->get('xshippingpro_desc_mail');
                if (strstr($order_info['shipping_code'], 'xshippingpro')) {
                    if ($xshippingpro_desc_mail) {
                        $language_id = $order_info['language_id'];
                        $tab_id = str_replace('xshippingpro.xshippingpro', '', $order_info['shipping_code']);
                        $method = $this->db->query("SELECT * FROM ps_xshippingpro WHERE tab_id='" . (int) $tab_id . "'")->row;

                        $xshippingpro = $method['method_data'];
                        $xshippingpro = @unserialize(@base64_decode($xshippingpro));
                        if (!is_array($xshippingpro))
                            $xshippingpro = array();
                        if (!isset($xshippingpro['desc']))
                            $xshippingpro['desc'] = array();

                        $data['shipping_method'] .= (isset($xshippingpro['desc'][$language_id]) && $xshippingpro['desc'][$language_id]) ? '<br /><span style="color: #999999;font-size: 11px;display:block" class="x-shipping-desc">' . $xshippingpro['desc'][$language_id] . '</span>' : '';
                    }
                }

                if ($comment && $notify) {
                    $data['comment'] = nl2br($comment);
                } else {
                    $data['comment'] = '';
                }

                if ($order_info['payment_address_format']) {
                    $format = $order_info['payment_address_format'];
                } else {
                    $format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
                }

                $find = array(
                    '{firstname}',
                    '{lastname}',
                    '{company}',
                    '{address_1}',
                    '{address_2}',
                    '{city}',
                    '{postcode}',
                    '{zone}',
                    '{zone_code}',
                    '{country}'
                );

                $replace = array(
                    'firstname' => $order_info['payment_firstname'],
                    'lastname' => $order_info['payment_lastname'],
                    'company' => $order_info['payment_company'],
                    'address_1' => $order_info['payment_address_1'],
                    'address_2' => $order_info['payment_address_2'],
                    'city' => $order_info['payment_city'],
                    'postcode' => $order_info['payment_postcode'],
                    'zone' => $order_info['payment_zone'],
                    'zone_code' => $order_info['payment_zone_code'],
                    'country' => $order_info['payment_country']
                );

                $data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

                if ($order_info['shipping_address_format']) {
                    $format = $order_info['shipping_address_format'];
                } else {
                    $format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
                }

                $find = array(
                    '{firstname}',
                    '{lastname}',
                    '{company}',
                    '{address_1}',
                    '{address_2}',
                    '{city}',
                    '{postcode}',
                    '{zone}',
                    '{zone_code}',
                    '{country}'
                );

                $replace = array(
                    'firstname' => $order_info['shipping_firstname'],
                    'lastname' => $order_info['shipping_lastname'],
                    'company' => $order_info['shipping_company'],
                    'address_1' => $order_info['shipping_address_1'],
                    'address_2' => $order_info['shipping_address_2'],
                    'city' => $order_info['shipping_city'],
                    'postcode' => $order_info['shipping_postcode'],
                    'zone' => $order_info['shipping_zone'],
                    'zone_code' => $order_info['shipping_zone_code'],
                    'country' => $order_info['shipping_country']
                );

                $data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

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

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

                foreach ($order_product_query->rows as $product) {
                    $option_data = array();

                    $order_option_query = $this->db->query("SELECT * FROM ps_order_option WHERE order_id = '" . (int) $order_id . "' AND order_product_id = '" . (int) $product['order_product_id'] . "'");

                    foreach ($order_option_query->rows 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' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
                        );
                    }

                    $data['products'][] = array(
                        'name' => $product['name'],
                        'model' => $product['model'],
                        'image' => $this->model_tool_image->resize($product['case_order_image'], 100, 100),
                        'option' => $option_data,
                        'quantity' => $product['quantity'],
                        'price' => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
                        'total' => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value'])
                    );
                }

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

                $order_voucher_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_voucher WHERE order_id = '" . (int) $order_id . "'");

                foreach ($order_voucher_query->rows as $voucher) {
                    $data['vouchers'][] = array(
                        'description' => $voucher['description'],
                        'amount' => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']),
                    );
                }

                // Order Totals
                $data['totals'] = array();

                $order_total_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_total` WHERE order_id = '" . (int) $order_id . "' ORDER BY sort_order ASC");

                foreach ($order_total_query->rows as $total) {
                    if($total['code'] == 'coupon'){
                        $c_title = explode(' ', $total['title']);
                        $data['totals'][] = array(
                            'title' => $c_title[0],
                            'text' => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
                        );
                    }else{
                        $data['totals'][] = array(
                            'title' => $total['title'],
                            'text' => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
                        );
                    }

                }

                // Text Mail
                $text = sprintf($language->get('text_new_greeting'), html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8')) . "\n\n";
                $text .= $language->get('text_new_order_id') . ' ' . $order_id . "\n";
                $text .= $language->get('text_new_date_added') . ' ' . date($language->get('date_format_short'), strtotime($order_info['date_added'])) . "\n";
                $text .= $language->get('text_new_order_status') . ' ' . $order_status . "\n\n";

                if ($comment && $notify) {
                    $text .= $language->get('text_new_instruction') . "\n\n";
                    $text .= $comment . "\n\n";
                }
                
                // Products
                $text .= $language->get('text_new_products') . "\n";

                foreach ($order_product_query->rows as $product) {
                    $text .= $product['quantity'] . 'x ' . $product['name'] . ' (' . $product['model'] . ') ' . html_entity_decode($this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value']), ENT_NOQUOTES, 'UTF-8') . "\n";

                    $order_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int) $order_id . "' AND order_product_id = '" . $product['order_product_id'] . "'");

                    foreach ($order_option_query->rows 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 = '';
                            }
                        }

                        $text .= chr(9) . '-' . $option['name'] . ' ' . (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value) . "\n";
                    }
                }

                foreach ($order_voucher_query->rows as $voucher) {
                    $text .= '1x ' . $voucher['description'] . ' ' . $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']);
                }

                $text .= "\n";

                $text .= $language->get('text_new_order_total') . "\n";

                foreach ($order_total_query->rows as $total) {
                    $text .= $total['title'] . ': ' . html_entity_decode($this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']), ENT_NOQUOTES, 'UTF-8') . "\n";
                }

                $text .= "\n";

                if ($order_info['customer_id']) {
                    $text .= $language->get('text_new_link') . "\n";
                    $text .= $order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_id . "\n\n";
                }

                if ($download_status) {
                    $text .= $language->get('text_new_download') . "\n";
                    $text .= $order_info['store_url'] . 'index.php?route=account/download' . "\n\n";
                }

                // Comment
                if ($order_info['comment']) {
                    $text .= $language->get('text_new_comment') . "\n\n";
                    $text .= $order_info['comment'] . "\n\n";
                }

                $text .= $language->get('text_new_footer') . "\n\n";
                if($_SERVER['REMOTE_ADDR']=='111.88.6.229'){
                //print_r($this->load->view(DIR_TEMPLATE . 'deercase/template/mail/order_history_dev', $data)); die;
                }
                $mail = new SendgridMail($this->config->get('sendgrid_api_key'));

                $mail->protocol = $this->config->get('config_mail_protocol');
                $mail->parameter = $this->config->get('config_mail_parameter');
                $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
                $mail->smtp_username = $this->config->get('config_mail_smtp_username');
                $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_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');

              
                
                if($_SERVER['REMOTE_ADDR']=='111.88.6.229'){
                   $mail->setTo('alirasooldev@gmail.com');
              }else{
                  //$mail->setTo('bilal.cakir@piyersoft.com');
                   $mail->setTo('tolga.turkmen@piyersoft.com');
              }

                $mail->setFrom($this->config->get('config_mail_smtp_username'));
                //$mail->setFrom($this->config->get('config_email'));
                $mail->setSender(html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'));
                $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));

                if($_SERVER['REMOTE_ADDR']=='111.88.6.229'){

                $mail->setHtml($this->load->view(DIR_TEMPLATE . 'deercase/template/mail/order_history_dev', $data));
                }else{
                    $mail->setHtml($this->load->view(DIR_TEMPLATE . 'deercase/template/mail/order_history', $data));
                }

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

                echo $response;

                $log = new Log("SendGridMailLog.txt");
                $log->write($response);



                // Admin Alert Mail
                if (in_array('order', (array) $this->config->get('config_mail_alert'))) {
                    $subject = sprintf($language->get('text_new_subject'), html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'), $order_id);

                    // HTML Mail
                    $data['text_greeting'] = $language->get('text_new_received');

                    if ($comment) {
                        if ($order_info['comment']) {
                            $data['comment'] = nl2br($comment) . '<br/><br/>' . $order_info['comment'];
                        } else {
                            $data['comment'] = nl2br($comment);
                        }
                    } else {
                        if ($order_info['comment']) {
                            $data['comment'] = $order_info['comment'];
                        } else {
                            $data['comment'] = '';
                        }
                    }

                    $data['text_download'] = '';

                    $data['text_footer'] = '';

                    $data['text_link'] = '';
                    $data['link'] = '';
                    $data['download'] = '';

                    // Text
                    $text = $language->get('text_new_received') . "\n\n";
                    $text .= $language->get('text_new_order_id') . ' ' . $order_id . "\n";
                    $text .= $language->get('text_new_date_added') . ' ' . date($language->get('date_format_short'), strtotime($order_info['date_added'])) . "\n";
                    $text .= $language->get('text_new_order_status') . ' ' . $order_status . "\n\n";
                    $text .= $language->get('text_new_products') . "\n";

                    foreach ($order_product_query->rows as $product) {
                        $text .= $product['quantity'] . 'x ' . $product['name'] . ' (' . $product['model'] . ') ' . html_entity_decode($this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value']), ENT_NOQUOTES, 'UTF-8') . "\n";

                        $order_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int) $order_id . "' AND order_product_id = '" . $product['order_product_id'] . "'");

                        foreach ($order_option_query->rows as $option) {
                            if ($option['type'] != 'file') {
                                $value = $option['value'];
                            } else {
                                $value = utf8_substr($option['value'], 0, utf8_strrpos($option['value'], '.'));
                            }

                            $text .= chr(9) . '-' . $option['name'] . ' ' . (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value) . "\n";
                        }
                    }

                    foreach ($order_voucher_query->rows as $voucher) {
                        $text .= '1x ' . $voucher['description'] . ' ' . $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']);
                    }

                    $text .= "\n";

                    $text .= $language->get('text_new_order_total') . "\n";

                    foreach ($order_total_query->rows as $total) {
                        $text .= $total['title'] . ': ' . html_entity_decode($this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']), ENT_NOQUOTES, 'UTF-8') . "\n";
                    }

                    $text .= "\n";

                    if ($order_info['comment']) {
                        $text .= $language->get('text_new_comment') . "\n\n";
                        $text .= $order_info['comment'] . "\n\n";
                    }

                    $mail = new SendgridMail($this->config->get('sendgrid_api_key'));
                    $mail->protocol = $this->config->get('config_mail_protocol');
                    $mail->parameter = $this->config->get('config_mail_parameter');
                    $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
                    $mail->smtp_username = $this->config->get('config_mail_smtp_username');
                    $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_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($this->config->get('config_email'));
                    $mail->setFrom($this->config->get('config_mail_smtp_hostname'));
                    $mail->setSender(html_entity_decode($order_info['store_name'], 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);
                    $mail->send();

                    // Send to additional alert emails
                    $emails = explode(',', $this->config->get('config_mail_alert_email'));

                    foreach ($emails as $email) {
                        if ($email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            $mail->setTo($email);
                            $mail->send();
                        }
                    }
                }
            }

            // If order status is not 0 then send update text email
            if ($order_info['order_status_id'] && $order_status_id && $notify) {
                $language = new Language($order_info['language_code']);
                $language->load($order_info['language_code']);
                $language->load('mail/order');

                $subject = sprintf($language->get('text_update_subject'), html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'), $order_id);

                $message = $language->get('text_update_order') . ' ' . $order_id . "\n";
                $message .= $language->get('text_update_date_added') . ' ' . date($language->get('date_format_short'), strtotime($order_info['date_added'])) . "\n\n";

                $order_status_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_status WHERE order_status_id = '" . (int) $order_status_id . "' AND language_id = '" . (int) $order_info['language_id'] . "'");

                if ($order_status_query->num_rows) {
                    $message .= $order_status_query->row['name'] . "\n\n";
                }

                if ($order_info['customer_id']) {

                    $message .= $order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_id . "\n\n";
                }

                if ($comment) {

                    $message .= strip_tags($comment) . "\n\n";
                }

                $message .= $language->get('text_update_footer');

                $mail = new SendgridMail($this->config->get('sendgrid_api_key'));
                $mail->protocol = $this->config->get('config_mail_protocol');
                $mail->parameter = $this->config->get('config_mail_parameter');
                $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
                $mail->smtp_username = $this->config->get('config_mail_smtp_username');
                $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_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($order_info['email']);
                $mail->setFrom($this->config->get('config_email'));
                $mail->setSender(html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'));
                $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
                $mail->setText($message);
                $mail->send();
            }
        }else{
            echo "Sipariş bulunamadı!";
        }
    }

    public function saveReturnShipmentCode()
    {

        die();
        $wsUserName  = $this->config->get('yurticikargo_gonderici_odemeli_kullanici_adi');
        $wsPassword = $this->config->get('yurticikargo_gonderici_odemeli_sifre');
        $userLanguage = 'TR';

        $serviceurl = 'http://webservices.yurticikargo.com:8080/KOPSWebServices/ShippingOrderDispatcherServices?wsdl';

        $updateDesiWeightParamsVO = array(
            'ngiDocumentKey' => '6716165',
            'cancellationDescription' => '6716165'
        );

        $fieldName = array(
            'specialFieldName' => 3,
            'specialFieldValue' => '100052611'
        );

        //580215178
        $post_data = array(
            'wsUserName' => $wsUserName,
            'wsPassword' => $wsPassword,
            'wsLanguage' => $userLanguage,
            'fieldName' => '1',
            'returnCode' => '580215178',
            'startDate' => '20200606',
            'endDate' => '20200610',
            'maxCount' => 1,
            //'cargoKeys' => '100052611'
        );


        $client 	= new SoapClient($serviceurl, array('trace' => 1, 'exceptions' => 1));
        $response 	= $client->saveReturnShipmentCode( $post_data );

        var_dump($response); die();
        
    }

    public function returnOrderDbCheck()
    {

        die();

        $results = $this->db->query("SELECT * FROM ps_return WHERE product_id = '0' ")->rows;

        foreach ($results as $result){
            //var_dump($result); die();

            $product_ask = $this->db->query("SELECT * FROM ps_product p 
            LEFT JOIN ps_product_description pd ON (p.product_id = pd.product_id) 
            WHERE pd.language_id = '1' AND p.model = '". $result['model'] ."' AND pd.name LIKE '%". $this->db->escape($result['product']) ."%' ")->row;
            if($product_ask){
                echo $product_ask['name'] . ' == ' . $result['product'] . ' ---' . $result['date_added'] .'<br>';
                //$this->db->query("UPDATE ps_return SET product_id = '". $product_ask['product_id'] ."' WHERE return_id = '". $result['return_id'] ."' ");
            }


        }



    }

    public function hataliIadeKayitlari()
    {


        die();

        $results = $this->db->query("SELECT o.order_id FROM ps_order o LEFT JOIN ps_order_product op ON (o.order_id = op.order_id) 
        WHERE op.return_status != 0 AND (o.date_added > '2020-06-15 00:00:00' AND o.date_added < '2020-06-26 00:00:00') AND order_status_id != 5 ")->rows;
        //var_dump($results); die();
        foreach ($results as $result){
            $return = $this->db->query("SELECT * FROM ps_return WHERE order_id = '". $result['order_id'] ."'  ")->row;

            if(!$return){
                echo $result['order_id'] . '<br>';
            }
        }



    }

    public function reOrderAdd()
    {



        /*
        $mongo = new MongoDB();

        $requests = $mongo->query(array(), array('email' => "onurilk1996@icloud.com"), 'deercase.orders');

        var_dump($requests); die(); */

        /*

        $this->db->query("INSERT INTO ps_order SET
		invoice_prefix = '" . $this->db->escape($data['invoice_prefix']) . "',
		store_id = '" . (int) $data['store_id'] . "',
		store_name = '" . $this->db->escape($data['store_name']) . "',
		store_url = '" . $this->db->escape($data['store_url']) . "',
		customer_id = '" . (int) $data['customer_id'] . "',
		customer_group_id = '" . (int) $data['customer_group_id'] . "',
		firstname = '" . $this->db->escape($data['firstname']) . "',
		lastname = '" . $this->db->escape($data['lastname']) . "',
		email = '" . $this->db->escape($data['email']) . "',
		telephone = '" . $this->db->escape($data['telephone']) . "',
		fax = '" . $this->db->escape($data['fax']) . "',
		custom_field = '" . $this->db->escape(isset($data['custom_field']) ? json_encode($data['custom_field']) : '') . "',
		payment_firstname = '" . $this->db->escape($data['payment_firstname']) . "',
		payment_lastname = '" . $this->db->escape($data['payment_lastname']) . "',
		payment_company = '" . $this->db->escape($data['payment_company']) . "',
		payment_address_1 = '" . $this->db->escape($data['payment_address_1']) . "',
		payment_address_2 = '" . $this->db->escape($data['payment_address_2']) . "',
		payment_city = '" . $this->db->escape($data['payment_city']) . "',
		payment_postcode = '" . $this->db->escape($data['payment_postcode']) . "',
		payment_country = '" . $this->db->escape($data['payment_country']) . "',
		payment_country_id = '" . (int) $data['payment_country_id'] . "',
		payment_zone = '" . $this->db->escape($data['payment_zone']) . "',
		payment_zone_id = '" . (int) $data['payment_zone_id'] . "',
		payment_address_format = '" . $this->db->escape($data['payment_address_format']) . "',
		payment_custom_field = '" . $this->db->escape(isset($data['payment_custom_field']) ? json_encode($data['payment_custom_field']) : '') . "',
		payment_method = '" . $this->db->escape($data['payment_method']) . "',
		payment_code = '" . $this->db->escape($data['payment_code']) . "',
		shipping_firstname = '" . $this->db->escape($data['shipping_firstname']) . "',
		shipping_lastname = '" . $this->db->escape($data['shipping_lastname']) . "',
		shipping_company = '" . $this->db->escape($data['shipping_company']) . "',
		shipping_address_1 = '" . $this->db->escape($data['shipping_address_1']) . "',
		shipping_address_2 = '" . $this->db->escape($data['shipping_address_2']) . "',
		shipping_city = '" . $this->db->escape($data['shipping_city']) . "',
		shipping_postcode = '" . $this->db->escape($data['shipping_postcode']) . "',
		shipping_country = '" . $this->db->escape($data['shipping_country']) . "',
		shipping_country_id = '" . (int) $data['shipping_country_id'] . "',
		shipping_zone = '" . $this->db->escape($data['shipping_zone']) . "',
		shipping_zone_id = '" . (int) $data['shipping_zone_id'] . "',
		shipping_address_format = '" . $this->db->escape($data['shipping_address_format']) . "',
		shipping_custom_field = '" . $this->db->escape(isset($data['shipping_custom_field']) ? json_encode($data['shipping_custom_field']) : '') . "',
		shipping_method = '" . $this->db->escape($data['shipping_method']) . "',
		shipping_code = '" . $this->db->escape($data['shipping_code']) . "',
		comment = '" . $this->db->escape($data['comment']) . "',
		total = '" . (float) $data['total'] . "',
		affiliate_id = '" . (int) $data['affiliate_id'] . "',
		commission = '" . (float) $data['commission'] . "',
		marketing_id = '" . (int) $data['marketing_id'] . "',
		tracking = '" . $this->db->escape($data['tracking']) . "',
		language_id = '" . (int) $data['language_id'] . "',
		currency_id = '" . (int) $data['currency_id'] . "',
		currency_code = '" . $this->db->escape($data['currency_code']) . "',
		currency_value = '" . (float) $data['currency_value'] . "',
		ip = '" . $this->db->escape($data['ip']) . "',
		forwarded_ip = '" . $this->db->escape($data['forwarded_ip']) . "',
		user_agent = '" . $this->db->escape($data['user_agent']) . "',
		accept_language = '" . $this->db->escape($data['accept_language']) . "',
		date_added = NOW(),
		date_modified = NOW() ");


        $order_id = $this->db->getLastId();

        $log = new Log("orders/order_" . $order_id . '.txt');

        $log->write($data);


        // Products

        if (isset($data['products'])) {

            foreach ($data['products'] as $product) {

                $this->db->query("INSERT INTO ps_order_product SET 
                order_id = '" . (int) $order_id . "', 
                product_id = '" . (int) $product['product_id'] . "', 
                name = '" . $this->db->escape($product['name']) . "', 
                model = '" . $this->db->escape($product['model']) . "', 
                quantity = '" . (int) $product['quantity'] . "', 
                price = '" . (float) $product['price'] . "', 
                total = '" . (float) $product['total'] . "', 
                tax = '" . (float) $product['tax'] . "', 
                reward = '" . (int) $product['reward'] . "',
                case_order_image='" . $product['case_order_image'] . "',
                customer_pattern_data='" . $this->db->escape($product['customer_pattern_data']) . "',
                customcase_image='" . $product['customcase_image'] . "'");


                $order_product_id = $this->db->getLastId();

                foreach ($product['option'] as $option) {
                    $this->db->query("INSERT INTO ps_order_option SET 
                    order_id = '" . (int) $order_id . "', 
                    order_product_id = '" . (int) $order_product_id . "', 
                    product_option_id = '" . (int) $option['product_option_id'] . "', 
                    product_option_value_id = '" . (int) $option['product_option_value_id'] . "', 
                    name = '" . $this->db->escape($option['name']) . "', 
                    `value` = '" . $this->db->escape($option['value']) . "', 
                    `type` = '" . $this->db->escape($option['type']) . "' ");

                }

            }

        }



        // Totals

        if (isset($data['totals'])) {

            foreach ($data['totals'] as $total) {
                $this->db->query("INSERT INTO ps_order_total SET 
                order_id = '" . (int) $order_id . "', 
                code = '" . $this->db->escape($total['code']) . "', 
                title = '" . $this->db->escape($total['title']) . "', 
                `value` = '" . (float) $total['value'] . "', 
                sort_order = '" . (int) $total['sort_order'] . "' ");

            }

        }

        */


    }

    public function getProducsManuel()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/getProducsManuel

        /*$products = $this->db->query("SELECT p.product_id FROM ps_product p WHERE p.manufacturer_id != 13 ")->num_rows;

        var_dump($products); die();

        die(); */

        $file_name = $this->config->get('config_name') . '-' . @date("Y-m-d-His") . "-products.xls";

        $products = $this->db->query("SELECT p.product_id, pd.name, pd.description, pd.meta_title, pd.meta_description, pd.href FROM ps_product p 
        LEFT JOIN ps_product_description pd ON (p.product_id = pd.product_id) WHERE pd.language_id = 1 AND p.manufacturer_id != 13 LIMIT 120000,40000 ")->rows;

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Product ID')
            ->setCellValue('B1', 'Product Name')
            ->setCellValue('C1', 'Product Description')
            ->setCellValue('D1', 'Product Meta Title')
            ->setCellValue('E1', 'Product Meta Description')
            ->setCellValue('F1', 'Product Url');

        $row_i = 2;

        foreach ($products as $product){

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $row_i, $product['product_id'])
                ->setCellValue('B' . $row_i, $product['name'])
                ->setCellValue('C' . $row_i, $product['description'])
                ->setCellValue('D' . $row_i, $product['meta_title'])
                ->setCellValue('E' . $row_i, $product['meta_description'])
                ->setCellValue('F' . $row_i, HTTPS_SERVER . $product['href']);

            $row_i++;

        }

        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        $objPHPExcel->setActiveSheetIndex(0);


        $objWriter1 = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');


        $excel_file1_tmp = tempnam("/tmp", 'tamp_1');

        $objWriter1->save($excel_file1_tmp);


        $zip_file_tmp = tempnam("/tmp", 'tamp_12');

        $zip = new ZipArchive();

        $zip->open($zip_file_tmp, ZipArchive::OVERWRITE);

        $zip->addFile($excel_file1_tmp, $file_name);


        $zip->close();


        //download
        $download_filename = $this->config->get('config_name') . '-' . @date("Y-m-d-His") . '-products.zip';

        header("Content-Type: application/zip");
        header("Content-Length: " . filesize($zip_file_tmp));
        header("Content-Disposition: attachment; filename=\"" . $download_filename . "\"");
        readfile($zip_file_tmp);

        exit;



    }

    public function getCategorisManuel()
    {
        die();
        //https://www.deercase.com/index.php?route=tool/functions/getCategorisManuel

        $file_name = $this->config->get('config_name') . '-' . @date("Y-m-d-His") . "-products.xls";


        $categories = $this->db->query("SELECT c.category_id, cd.name, cd.href FROM ps_category c 
        LEFT JOIN ps_category_description cd ON (c.category_id = cd.category_id) WHERE cd.language_id = 1 AND cd.name NOT LIKE '%iPhone%' AND cd.name NOT LIKE '%Apple%' ")->rows;



        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Category ID')
            ->setCellValue('B1', 'Category Name')
            ->setCellValue('C1', 'Category Description')
            ->setCellValue('D1', 'Category Meta Title')
            ->setCellValue('E1', 'Category Meta Description')
            ->setCellValue('F1', 'Category Url');

        $row_i = 2;

        foreach ($categories as $category){

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $row_i, $category['category_id'])
                ->setCellValue('B' . $row_i, $category['name'])
                ->setCellValue('C' . $row_i, $category['description'])
                ->setCellValue('D' . $row_i, $category['meta_title'])
                ->setCellValue('E' . $row_i, $category['meta_description'])
                ->setCellValue('F' . $row_i, HTTPS_SERVER . $category['href']);

            $row_i++;

        }

        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        $objPHPExcel->setActiveSheetIndex(0);


        $objWriter1 = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');


        $excel_file1_tmp = tempnam("/tmp", 'tamp_1');

        $objWriter1->save($excel_file1_tmp);


        $zip_file_tmp = tempnam("/tmp", 'tamp_12');

        $zip = new ZipArchive();

        $zip->open($zip_file_tmp, ZipArchive::OVERWRITE);

        $zip->addFile($excel_file1_tmp, $file_name);


        $zip->close();


        //download
        $download_filename = $this->config->get('config_name') . '-' . @date("Y-m-d-His") . '-products.zip';

        header("Content-Type: application/zip");
        header("Content-Length: " . filesize($zip_file_tmp));
        header("Content-Disposition: attachment; filename=\"" . $download_filename . "\"");
        readfile($zip_file_tmp);

        exit;


    }

    public function getCategoriesUrlManuel()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/getCategoriesUrlManuel

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

        $categories = array();

        $language['language_id'] = 1;

        foreach ($this->model_catalog_category->getSubCategory(1662, 1) as $key1 => $c_data) {
            if ($c_data['top']) {
                $categories2_data = $this->model_catalog_category->getSubCategory($c_data['category_id'], $language['language_id']);
                foreach ($categories2_data as $key2 => $c2_data) {
                    if ($c2_data['top']) {
                        $categories3_data = $this->model_catalog_category->getSubCategory($c2_data['category_id'], $language['language_id']);
                        foreach ($categories3_data as $key3 => $c3_data) {
                            if ($c3_data['top']) {
                                $categories4_data = $this->model_catalog_category->getSubCategory($c3_data['category_id'], $language['language_id']);
                                foreach ($categories4_data as $key4 => $c4_data) {
                                    if ($c4_data['top']) {
                                        $categories[] = array(
                                            'name' => $c4_data['name'],
                                            'href' => $c4_data['href'],
                                            'category_id' => $c4_data['category_id'],
                                        );
                                    }
                                }
                                $categories[] = array(
                                    'name' => $c3_data['name'],
                                    'href' => $c3_data['href'],
                                    'category_id' => $c3_data['category_id'],
                                );
                            }
                        }
                        $categories[] = array(
                            'name' => $c2_data['name'],
                            'href' => $c2_data['href'],
                            'category_id' => $c2_data['category_id'],
                        );
                    }
                }
                $categories[] = array(
                    'name' => $c_data['name'],
                    'href' => $c_data['href'],
                    'category_id' => $c_data['category_id'],
                );

            }
        }


        $file_name = $this->config->get('config_name') . '-' . @date("Y-m-d-His") . "-xiaomi-category-info.xls";


        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Category ID')
            ->setCellValue('B1', 'Category Name')
            ->setCellValue('F1', 'Category Url');

        $row_i = 2;

        foreach ($categories as $category){

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $row_i, $category['category_id'])
                ->setCellValue('B' . $row_i, $category['name'])
                ->setCellValue('F' . $row_i, HTTPS_SERVER . $category['href']);

            $row_i++;

        }

        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        $objPHPExcel->setActiveSheetIndex(0);


        $objWriter1 = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');


        $excel_file1_tmp = tempnam("/tmp", 'tamp_1');

        $objWriter1->save($excel_file1_tmp);


        $zip_file_tmp = tempnam("/tmp", 'tamp_12');

        $zip = new ZipArchive();

        $zip->open($zip_file_tmp, ZipArchive::OVERWRITE);

        $zip->addFile($excel_file1_tmp, $file_name);


        $zip->close();


        //download
        $download_filename = $this->config->get('config_name') . '-' . @date("Y-m-d-His") . '-xiaomi-category-info.zip';

        header("Content-Type: application/zip");
        header("Content-Length: " . filesize($zip_file_tmp));
        header("Content-Disposition: attachment; filename=\"" . $download_filename . "\"");
        readfile($zip_file_tmp);

        exit;


    }

    public function catregoryList()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/catregoryList

        $categories = $this->db->query("SELECT * FROM ps_category c LEFT JOIN ps_category_description cd ON (c.category_id = cd.category_id) WHERE c.parent_id = 0 ")->rows;
        foreach ($categories as $category){
            if($category['category_id']){
                $sub_categories = $this->db->query("SELECT * FROM ps_category c LEFT JOIN ps_category_description cd ON (c.category_id = cd.category_id) WHERE parent_id = '". $category['category_id'] ."' ")->rows;
                foreach ($sub_categories as $cat){
                    //if($cat['category_id']){
                        echo $cat['category_id'] . ' - ' . $category['name'] . ' - ' . '<a href="https://www.deercase.com/index.php?route=tool/functions/catregoryListDetail&category_id='. $cat['category_id'] .'&barcode=" target="_blank">'. $cat['name'] .'</a>' . '<br>';
                   // }
                }

            }


        }

    }

    public function catregoryListDetail()
    {

        die();

        // 140166 Kırılmaz Nano Ekran Koruyucu

        if(isset($this->request->get['category_id']) AND isset($this->request->get['barcode'])){

            $category_id = $this->request->get['category_id'];
            $barcode = $this->request->get['barcode'];

            if($barcode){
                $products = $this->db->query("SELECT p.product_id, p2c.category_id FROM ps_product p LEFT JOIN ps_product_to_category p2c ON (p.product_id = p2c.product_id) WHERE p2c.category_id = '". (int)$category_id ."'  ")->rows;
                //var_dump($products); die();
                foreach ($products as $product){
                    $this->db->query("INSERT INTO ps_subproducts_to_barcode SET 
                        product_id = '". $product['product_id'] ."',
                        subproduct_id = '140166',
                        category_id = '". $category_id ."',
                        barcode = '". $barcode ."'
                         ");


                }
            }





        }

    }

    public function callProcedure()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/callProcedure
        $query = $this->db->query("CALL getOrders('2020-08-21', '2020-08-26', 10) ")->rows;

        var_dump($query); die();
        
    }

    public function barcodeTest()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/barcodeTest

        require_once(DIR_SYSTEM . 'picqer/php-barcode-generator/generate-verified-files.php');

        $generatorJPG = new Picqer\Barcode\BarcodeGeneratorPNG();

        $barkod_cargokey = $generatorJPG->getBarcode('453485743875438', $generatorJPG::TYPE_CODE_128_A);

        $barkod_cargokey = '<img src="data:image/jpeg;base64,' . base64_encode($barkod_cargokey) . '" style="transform: rotate(90deg); width: 200px; margin-right:70px; height: auto;">';

        $html = '<html>
        <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">

          <style>
            html { margin: 0; padding: 5px; }
            body { font-family: DejaVu Sans, sans-serif; margin: 0; padding: 5px;}

            .outer{
              width: 100%;
              padding: 0;
            }

            .title{
              width: 100%;
              font-size: 14px;
              border-bottom: 1px solid black;
              margin-bottom: 4px;
            }

            .inner{
              width: 80%;
              float: left;
            }

            .alt{
              width: 100%;
            }

            .altBilgi{
              width: 50%;
              float:left;
            }

            .altBarkod{
              width: 50%;
              float: right;
              padding-top: 10px;
            }

            .border-bottom{ border-bottom: 1px solid gray; }

            .barcode{
              position: absolute;
              right: 275px;
              top: 175px;
            }

            .alt-title{
              font-weight: bold;
              font-size: 11px;
            }

            .alt div{
              font-size: 10px;
            }

            .tarih{
              float: right;
              margin: 0;
              font-size: 8px;
              margin-top: 3px;
            }
          </style>

        </head>
        <body>

          <div class="outer">

            <div class="inner">
             ';

        $html .= '
                <div class="title">
                <b>Deercase - Web Servis</b> <span class="tarih">' . @date('d:m:y h:i') . '</span> <br>
               
              </div>

            <div class="alt border-bottom">
                <div class="alt-title">Alıcı Bilgileri</div>
                
              </div>
              

              <div class="alt border-bottom">
                <div class="alt-title">Tahsilat Bilgileri</div>
              
                <div>Tahsilat Türü: </div>
              </div>
              <div class="alt">
                
               
              </div>
            </div><div class="barcode">' . $barkod_cargokey . '</div>';


        $html .= '
                  </div>
                </body>
              </html>
                ';

        echo $barkod_cargokey;

    }

    public function readGoogleFeedCategory()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/readGoogleFeedCategory

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $file_path = $file_path = DIR_UPLOAD . "taxonomy-with-ids.tr-TR.xls";
        $inputFileType = PHPExcel_IOFactory::identify($file_path);

        $flag = 0;
        $valid = false;
        $types = array('Excel2007', 'Excel5');
        foreach ($types as $type) {
            $objReader = PHPExcel_IOFactory::createReader($type);
            if ($objReader->canRead($file_path)) {
                $valid = true;
                break;
            }
        }

        if (!$valid) {
            die("Bad file");
        }

        if (!isset($this->session->data['excel_file'])) {
            $objPHPExcel = new PHPExcel();
            $objReader->setReadDataOnly(true);
            $objPHPExcel = $objReader->load($file_path);
            $rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
            $array_data = array();
            foreach ($rowIterator as $row) {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                $rowIndex = $row->getRowIndex();
                $columnIndex = 0;
                foreach ($cellIterator as $cell) {
                    $this->session->data['excel_file'][$rowIndex - 1][$columnIndex++] = $cell->getCalculatedValue();
                }
                $flag++;
            }
        }

       // var_dump($this->session->data['excel_file']); die();

        foreach ($this->session->data['excel_file'] as $rows){
            //var_dump($rows); die();

            //echo $rows[0] . ' - ' . ($rows[1] ? $rows[1] : '') . ' -> ' . ($rows[2] ? $rows[2] : '') . '<br>';
            if($rows[7]){
                $name = $rows[1] . ' => ' . $rows[2] . ' => ' . $rows[3] . ' => ' . $rows[4] . ' => ' . $rows[5] . ' => ' . $rows[6] . ' => ' . $rows[7];
                $this->db->query("INSERT INTO ps_feed_category SET feed_category_id = '". (int)$rows[0] ."', name = '". $this->db->escape($name) ."' ");
            }elseif ($rows[6]){
                $name = $rows[1] . ' => ' . $rows[2] . ' => ' . $rows[3] . ' => ' . $rows[4] . ' => ' . $rows[5] . ' => ' . $rows[6];
                $this->db->query("INSERT INTO ps_feed_category SET feed_category_id = '". (int)$rows[0] ."', name = '". $this->db->escape($name) ."' ");
            }elseif ($rows[5]){
                $name = $rows[1] . ' => ' . $rows[2] . ' => ' . $rows[3] . ' => ' . $rows[4] . ' => ' . $rows[5];
                $this->db->query("INSERT INTO ps_feed_category SET feed_category_id = '". (int)$rows[0] ."', name = '". $this->db->escape($name) ."' ");
            }elseif ($rows[4]){
                $name = $rows[1] . ' => ' . $rows[2] . ' => ' . $rows[3] . ' => ' . $rows[4];
                $this->db->query("INSERT INTO ps_feed_category SET feed_category_id = '". (int)$rows[0] ."', name = '". $this->db->escape($name) ."' ");
            }elseif ($rows[3]){
                $name = $rows[1] . ' => ' . $rows[2] . ' => ' . $rows[3];
                $this->db->query("INSERT INTO ps_feed_category SET feed_category_id = '". (int)$rows[0] ."', name = '". $this->db->escape($name) ."' ");
            }elseif ($rows[2]){
                $name = $rows[1] . ' => ' . $rows[2];
                $this->db->query("INSERT INTO ps_feed_category SET feed_category_id = '". (int)$rows[0] ."', name = '". $this->db->escape($name) ."' ");
            }elseif ($rows[1]){
                $name = $rows[1];
                $this->db->query("INSERT INTO ps_feed_category SET feed_category_id = '". (int)$rows[0] ."', name = '". $this->db->escape($name) ."' ");
            }

        }

    }

    public function readExcelFile()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/readExcelFile

        //unset($this->session->data['excel_file']); die();

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $file_path = $file_path = DIR_UPLOAD . "MOBİL-ALAN-DETAYLI LİSTESİ.xlsx";
        $inputFileType = PHPExcel_IOFactory::identify($file_path);

        $flag = 0;
        $valid = false;
        $types = array('Excel2007', 'Excel5');
        foreach ($types as $type) {
            $objReader = PHPExcel_IOFactory::createReader($type);
            if ($objReader->canRead($file_path)) {
                $valid = true;
                break;
            }
        }

        if (!$valid) {
            die("Bad file");
        }

        if (!isset($this->session->data['excel_file'])) {
            $objPHPExcel = new PHPExcel();
            $objReader->setReadDataOnly(true);
            $objPHPExcel = $objReader->load($file_path);
            $rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
            $array_data = array();
            foreach ($rowIterator as $row) {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                $rowIndex = $row->getRowIndex();
                $columnIndex = 0;
                //if (!$flag) {
                foreach ($cellIterator as $cell) {
                    $this->session->data['excel_file'][$rowIndex - 1][$columnIndex++] = $cell->getCalculatedValue();
                }
                $flag++;
                //}
            }

            unset($this->session->data['excel_file'][0]);
        }

        //var_dump($this->session->data['excel_file']); die();

        echo count($this->session->data['excel_file']) . ' Adet satır kaldı!';

        foreach ($this->session->data['excel_file'] as $key => $row){ //var_dump($row); die();

            $category_id = $row[0];
            $name = $row[1];


            $old_url = explode('https://www.deercase.com/', $row[5]);
            $new_url = explode('https://www.deercase.com/', $row[7]);
            $new_url = $new_url[1];

           // var_dump($new_url); die();

            $url_find = $this->db->query("SELECT * FROM ps_url_alias WHERE query = 'category_id=". $category_id ."' ")->row;

            if($url_find){

                $this->db->query("UPDATE ps_url_alias SET keyword = '". $this->db->escape($new_url) ."' WHERE url_alias_id = '". $url_find['url_alias_id'] ."' ");

                $this->db->query("UPDATE ps_category_description SET 
                    href = '". $this->db->escape($new_url) ."'  
                    WHERE category_id = '". (int)$category_id ."' ");

            }



            unset($this->session->data['excel_file'][$key]);

           // var_dump($category_id); die();




        }

    }

    public function makeSeoUrlCheck()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/makeSeoUrlCheck

        unset($this->session->data['products_url_alias']);

        if(!isset($this->session->data['products_url_alias'])){
            $this->session->data['products_url_alias'] = $this->db->query("SELECT product_id, href FROM ps_product_description WHERE href = '' ")->rows;
        }

        echo count($this->session->data['products_url_alias']) . ' adet kaldı.'; die();

        foreach ($this->session->data['products_url_alias'] as $key => $product){

            if($product['href'] == ''){

                //var_dump("Link boş",$product);
                //unset($this->session->data['products_url_alias'][$key]); die();
            }else{
                $url_query = $this->db->query("SELECT * FROM ps_url_alias WHERE query = 'product_id=". $product['product_id'] ."' AND keyword = '". $this->db->escape($product['href']) ."'  ")->row;
                if(!$url_query){
                    $this->db->query("INSERT INTO ps_url_alias SET query = 'product_id=". $product['product_id'] ."', keyword = '". $this->db->escape($product['href']) ."', language_id = 1 ");
                }
            }



            unset($this->session->data['products_url_alias'][$key]);

        }

    }

    public function make301Url()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/make301Url

        //unset($this->session->data['excel_file']); die();

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $file_path = $file_path = DIR_UPLOAD . "deercase.com-Coverage-Drilldown-2021-05-031.xlsx";
        $inputFileType = PHPExcel_IOFactory::identify($file_path);

        $flag = 0;
        $valid = false;
        $types = array('Excel2007', 'Excel5');
        foreach ($types as $type) {
            $objReader = PHPExcel_IOFactory::createReader($type);
            if ($objReader->canRead($file_path)) {
                $valid = true;
                break;
            }
        }

        if (!$valid) {
            die("Bad file");
        }

        if (!isset($this->session->data['excel_file'])) {
            $objPHPExcel = new PHPExcel();
            $objReader->setReadDataOnly(true);
            $objPHPExcel = $objReader->load($file_path);
            $rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
            $array_data = array();
            foreach ($rowIterator as $row) {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                $rowIndex = $row->getRowIndex();
                $columnIndex = 0;
                //if (!$flag) {
                foreach ($cellIterator as $cell) {
                    $this->session->data['excel_file'][$rowIndex - 1][$columnIndex++] = $cell->getCalculatedValue();
                }
                $flag++;
                //}
            }

            unset($this->session->data['excel_file'][0]);
        }

       // var_dump($this->session->data['excel_file']); die();

        echo count($this->session->data['excel_file']) . ' Adet satır kaldı!';

        foreach ($this->session->data['excel_file'] as $key => $row){ //var_dump($row); die();


           // $url_from = explode('https://www.deercase.com/', $row[0]);
            $url_from = $row[0];
          //  $url_to = explode('https://www.deercase.com/', $row[1]);
            $url_to = $row[1];

            //var_dump($url_from, $url_to); die();


            $this->db->query("INSERT INTO ps_301redirect SET url_from = '". $this->db->escape($url_from) ."', url_to = '". $this->db->escape($url_to) ."' ");


            unset($this->session->data['excel_file'][$key]);

            //var_dump($this->db->getLastId()); die();




        }

    }

    public function urlAliasRestore()
    {
        die();

       // unset($this->session->data['url_products']);


        //https://www.deercase.com/index.php?route=tool/functions/urlAliasRestore

        if(!isset($this->session->data['url_products'])){
            //$products = $this->db->query("SELECT * FROM ps_url_alias WHERE query LIKE '%product_id%' ")->rows;
            $this->session->data['url_products'] = $this->db->query("SELECT * FROM ps_url_alias WHERE query LIKE '%product_id%' ")->rows;
        }

        echo  count($this->session->data['url_products']) . ' adet';

        foreach ($this->session->data['url_products'] as $key => $product){  //var_dump($product); die();


            $new_alias = str_replace('kiliflari', 'kilifi', $product['keyword'] );

            //var_dump($new_alias); die();

            $this->db->query("UPDATE ps_url_alias SET keyword = '". $this->db->escape($new_alias) ."' WHERE url_alias_id = '". $product['url_alias_id'] ."' ");

            //var_dump($product); die();

            $page = explode('=', $product['query']);

            if($page[0] == 'category_id'){
                $this->db->query("UPDATE ps_category_description SET href = '". $this->db->escape($product['keyword']) ."' WHERE category_id = '". (int)$page[1] ."' ");

               // var_dump($page); die();
            }else if($page[0] == 'product_id'){
                $this->db->query("UPDATE ps_product_description SET href = '". $this->db->escape($new_alias) ."' WHERE product_id = '". (int)$page[1] ."' ");

                 //var_dump($page); die();
            }

            unset($this->session->data['url_products'][$key]);


            //die();


        }


    }

    public function SM1888CouponExport()
    {
        die();

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


        //https://www.deercase.com/index.php?route=tool/functions/SM1888CouponExport&coupon=19DM100

        $this->load->model('checkout/order');

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $objPHPExcel = new PHPExcel();

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Sipariş ID')
            ->setCellValue('B1', 'Müşteri ID')
            ->setCellValue('C1', 'Müşteri Adı Soyadı')
            ->setCellValue('D1', 'Müşteri E-Posta')
            ->setCellValue('E1', 'Müşteri Telefon')
            ->setCellValue('F1', 'Fatura Adı Soyadı')
            ->setCellValue('G1', 'Fatura Adresi')
            ->setCellValue('H1', 'Fatura Şehir')
            ->setCellValue('J1', 'Sipariş Durumu')
            ->setCellValue('K1', 'Fiyat')
            ->setCellValue('L1', 'Ara Toplam')
            ->setCellValue('M1', 'Ürün')
            ->setCellValue('N1', 'Tarih');



        $orders = $this->db->query("SELECT * FROM `ps_order_total` WHERE `title` LIKE '%Kupon (".$coupon.")%' GROUP BY order_id ")->rows;



        $file_name = $this->config->get('config_name') . '-' . @date("Y-m-d-His") . "-".$coupon."ouponExport-orders.xls";

        $row_i = 2;


        foreach ($orders as $order) {

            $result_orders = $this->model_checkout_order->getOrder($order['order_id']);

            $order_products = $this->db->query("SELECT * FROM ps_order_product WHERE order_id = '". $order['order_id'] ."' ")->rows;
            $order_totals = $this->db->query("SELECT * FROM ps_order_total WHERE order_id = '". $order['order_id'] ."' ")->rows;

            $sub_total = 0;
            foreach ($order_totals as $total){
                if($total['code'] == 'sub_total'){
                    $sub_total = $total['value'];
                }
            }

            foreach ($order_products as $order_product) {

                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $row_i, $result_orders['order_id'])
                    ->setCellValue('B' . $row_i, $result_orders['customer_id'])
                    ->setCellValue('C' . $row_i, $result_orders['firstname'] . ' ' . $result_orders['lastname'])
                    ->setCellValue('D' . $row_i, $result_orders['email'])
                    ->setCellValue('E' . $row_i, $result_orders['telephone'])
                    ->setCellValue('F' . $row_i, $result_orders['payment_firstname'] . ' ' . $result_orders['payment_lastname'])
                    ->setCellValue('G' . $row_i, $result_orders['payment_address_1'])
                    ->setCellValue('H' . $row_i, $result_orders['payment_city'])
                    ->setCellValue('J' . $row_i, $result_orders['order_status'])
                    ->setCellValue('K' . $row_i, $result_orders['total'])
                    ->setCellValue('L' . $row_i, $sub_total)
                    ->setCellValue('M' . $row_i, $order_product['name'])
                    ->setCellValue('N' . $row_i, $result_orders['date_added']);

                $row_i++;

            }

        }


        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        $objPHPExcel->setActiveSheetIndex(0);


        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

        exit;

    }

    public function dayCollectionExport()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/dayCollectionExport


        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $objPHPExcel = new PHPExcel();

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Product ID')
            ->setCellValue('B1', 'Url');



        $products = $this->db->query("SELECT pd.href, p.product_id FROM ps_product p LEFT JOIN ps_product_description pd ON (p.product_id = pd.product_id) WHERE pd.language_id = 1 AND p.model LIKE '%day%'  ")->rows;



        $file_name = $this->config->get('config_name') . '-' . @date("Y-m-d-His") . "-DayCollectionExport.xls";

        $row_i = 2;


        foreach ($products as $product) {

                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $row_i, $product['product_id'])
                    ->setCellValue('B' . $row_i, $product['href']);

                $row_i++;

        }


        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        $objPHPExcel->setActiveSheetIndex(0);


        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

        exit;

    }

    public function yesilrenkal()
    {
        die();
        //https://www.deercase.com/index.php?route=tool/functions/yesilrenkal



        $query = $this->db->query("SELECT order_id FROM ps_order WHERE order_id < 131874 AND prepared_order_status = 0 ")->rows;

        var_dump($query); die();

        foreach ($query as $row){
            $this->db->query("UPDATE ps_order SET prepared_order_status = 1 WHERE order_id = '". (int)$row['order_id'] ."' ");

            $query = $this->db->query("SELECT * FROM ps_prepared_orders WHERE order_id = '". (int)$row['order_id'] ."' ")->row;
            if(!$query){
                $this->db->query("INSERT INTO ps_prepared_orders SET order_id = '". (int)$row['order_id'] ."', date_added = NOW(), status = 1 ");
                $this->db->query("UPDATE ps_order SET prepared_order_status = 1 WHERE order_id = '". (int)$row['order_id'] ."' ");
            }
        }


        /*

        $query = $this->db->query("SELECT * FROM ps_prepared_orders  ")->rows;

        foreach ($query as $row){
            $this->db->query("UPDATE ps_order SET prepared_order_status = 1 WHERE order_id = '". (int)$row['order_id'] ."' ");
        } */

    }

    public function kaziKazanCsv(){

         die();

        //https://www.deercase.com/index.php?route=tool/functions/kaziKazanCsv

        //unset($this->session->data['excel_file']); die();

        $file_path = $file_path = DIR_UPLOAD . "20000_unique_codes.csv";

        if (!isset($this->session->data['excel_file'])) {
            if (($h = fopen($file_path, "r")) !== FALSE)
            {
                while (($data = fgetcsv($h, 1000, ",")) !== FALSE)
                {
                    $this->session->data['excel_file'][] = $data[0];
                }
                fclose($h);
            }

        }

        //var_dump($this->session->data['excel_file']); die();

        $exist_count = 0;
        $notexist_count = 0;
        foreach ($this->session->data['excel_file'] as $item){  //var_dump($item); die();

            $coupon_find = $this->db->query("SELECT * FROM ps_coupon WHERE code = '". $this->db->escape($item) ."'  ")->row;
            if($coupon_find){
                $exist_count++;
                echo $coupon_find['code'] . '<br>';
                //$this->db->query("UPDATE ps_coupon SET status = 1 WHERE coupon_id = '". $coupon_find['coupon_id'] ."' ");
            }else{
                $notexist_count++;
                $this->db->query("INSERT INTO ps_coupon SET name = 'EDENRED', `code` = '". $this->db->escape($item) ."', type = 'P', discount = '15.00', date_start = '2020-01-19', date_end = '2021-01-31', uses_total = 1, uses_customer = 1, return_coupon = 0, date_added = NOW(), status = 1 ");
               // $this->db->query("INSERT INTO ps_coupon SET name = 'TurkTelekom', `code` = '". $this->db->escape($item) ."', type = 'P', discount = '20.00', date_start = '2020-08-04', date_end = '2022-07-31', uses_total = 1, uses_customer = 1, return_coupon = 0, date_added = NOW(), status = 1 ");
            }


        }

        echo $exist_count . " Kupon mevcut. <br>";
        echo $notexist_count . " Kupon mevcut değil. <br>";






    }

    public function newsadik(){

         die();

        //https://www.deercase.com/index.php?route=tool/functions/newsadik

        //unset($this->session->data['excel_file']); die();


        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $file_path = $file_path = DIR_UPLOAD . "new-SADIK.xlsx";
        $inputFileType = PHPExcel_IOFactory::identify($file_path);

        $flag = 0;
        $valid = false;
        $types = array('Excel2007', 'Excel5');
        foreach ($types as $type) {
            $objReader = PHPExcel_IOFactory::createReader($type);
            if ($objReader->canRead($file_path)) {
                $valid = true;
                break;
            }
        }

        if (!$valid) {
            die("Bad file");
        }

        if (!isset($this->session->data['excel_file'])) {
            $objPHPExcel = new PHPExcel();
            $objReader->setReadDataOnly(true);
            $objPHPExcel = $objReader->load($file_path);
            $rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
            $array_data = array();
            foreach ($rowIterator as $row) {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                $rowIndex = $row->getRowIndex();
                $columnIndex = 0;
                //if (!$flag) {
                foreach ($cellIterator as $cell) {
                    $this->session->data['excel_file'][$rowIndex - 1][$columnIndex++] = $cell->getCalculatedValue();
                }
                $flag++;
                //}
            }

            unset($this->session->data['excel_file'][0]);
        }

        //var_dump($this->session->data['excel_file']); die();

        //unset($this->session->data['excel_file'][0]);

        $exist_count = 0;
        $notexist_count = 0;
        foreach ($this->session->data['excel_file'] as $item){  //var_dump($item); die();

            $this->db->query("INSERT INTO ps_product_stock SET
            product_stock_id = '". (int)$item[0] ."',
            name = '". $this->db->escape($item[1]) ."',
            category_id = '". (int)$item[4] ."',
            category_name = '". $this->db->escape($item[5]) ."',
            collection_id = '". (int)$item[6] ."',
            collection_name = '". $this->db->escape($item[7]) ."',
            color_id = '". (int)$item[8] ."',
            color_name = '". $this->db->escape($item[9]) ."',
            quantity = '". (int)$item[10] ."',
            price = '". (float)$item[11] ."',
            price_cost = '". (int)$item[12] ."',
            date_added = NOW() ");


        }





    }

    public function kaziKazan()
    {
        die();

        //https://www.deercase.com/index.php?route=tool/functions/kaziKazan


        //unset($this->session->data['excel_file']); die();

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $file_path = $file_path = DIR_UPLOAD . "13000_unique_codes.xls";
        $inputFileType = PHPExcel_IOFactory::identify($file_path);

        $flag = 0;
        $valid = false;
        $types = array('Excel2007', 'Excel5');
        foreach ($types as $type) {
            $objReader = PHPExcel_IOFactory::createReader($type);
            if ($objReader->canRead($file_path)) {
                $valid = true;
                break;
            }
        }

        if (!$valid) {
            die("Bad file");
        }

        if (!isset($this->session->data['excel_file'])) {
            $objPHPExcel = new PHPExcel();
            $objReader->setReadDataOnly(true);
            $objPHPExcel = $objReader->load($file_path);
            $rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
            $array_data = array();
            foreach ($rowIterator as $row) {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                $rowIndex = $row->getRowIndex();
                $columnIndex = 0;
                //if (!$flag) {
                foreach ($cellIterator as $cell) {
                    $this->session->data['excel_file'][$rowIndex - 1][$columnIndex++] = $cell->getCalculatedValue();
                }
                $flag++;
                //}
            }

            //unset($this->session->data['excel_file'][0]);
        }

        var_dump($this->session->data['excel_file']); die();

        $exist_count = 0;
        $notexist_count = 0;
        foreach ($this->session->data['excel_file'] as $item){

            $coupon_find = $this->db->query("SELECT * FROM ps_coupon WHERE code = '". $this->db->escape($item[0]) ."'  ")->row;


            if($coupon_find){
                $exist_count++;

                echo $coupon_find['code'] . '<br>';

                //$this->db->query("UPDATE ps_coupon SET status = 1 WHERE coupon_id = '". $coupon_find['coupon_id'] ."' ");
            }else{
                $notexist_count++;
                $this->db->query("INSERT INTO ps_coupon SET name = 'ONLYFORYOU', `code` = '". $this->db->escape($item[0]) ."', type = 'P', discount = '10.00', date_start = '2020-08-04', date_end = '2022-07-31', uses_total = 1, uses_customer = 1, return_coupon = 0, date_added = NOW(), status = 1 ");

                //var_dump($item[0]); die();

                //die();
            }


        }

        echo $exist_count . " Kupon mevcut. <br>";
        echo $notexist_count . " Kupon mevcut değil. <br>";



    }

    public function add301()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/add301

        $products = $this->db->query("SELECT p.product_id, pd.href FROM ps_product p 
        LEFT JOIN ps_product_description pd ON (p.product_id = pd.product_id) 
        WHERE p.model IN ('kbr006', 'kbr010', 'kbr005', 'kbr007', 'kbr002', 'kbr008', 'kbr003', 'kbr004') ")->rows;

        $count = 0;
        foreach ($products as $product){
            $count++;
            if($product['href']){
                $this->db->query("INSERT INTO ps_301redirect SET url_from = '". $this->db->escape($product['href']) ."', url_to = '' ");
            }
        }
        echo $count;



    }

    public function barcodeChange()
    {
        die();

        //https://www.deercase.com/index.php?route=tool/functions/barcodeChange


        //unset($this->session->data['excel_file']); die();

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $file_path = $file_path = DIR_UPLOAD . "11.xlsx";
        $inputFileType = PHPExcel_IOFactory::identify($file_path);

        $flag = 0;
        $valid = false;
        $types = array('Excel2007', 'Excel5');
        foreach ($types as $type) {
            $objReader = PHPExcel_IOFactory::createReader($type);
            if ($objReader->canRead($file_path)) {
                $valid = true;
                break;
            }
        }

        if (!$valid) {
            die("Bad file");
        }

        if (!isset($this->session->data['excel_file'])) {
            $objPHPExcel = new PHPExcel();
            $objReader->setReadDataOnly(true);
            $objPHPExcel = $objReader->load($file_path);
            $rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
            $array_data = array();
            foreach ($rowIterator as $row) {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                $rowIndex = $row->getRowIndex();
                $columnIndex = 0;
                //if (!$flag) {
                foreach ($cellIterator as $cell) {
                    $this->session->data['excel_file'][$rowIndex - 1][$columnIndex++] = $cell->getCalculatedValue();
                }
                $flag++;
                //}
            }

            //unset($this->session->data['excel_file'][0]);
        }



        $exist_count = 0;
        $notexist_count = 0;
        foreach ($this->session->data['excel_file'] as $item){


            $ask_item = $this->db->query("SELECT * FROM ps_product_stock WHERE name = '". $this->db->escape($item[1]) ."' ")->row;

            if($ask_item){
               // $this->db->query("UPDATE ps_product_stock SET quantity = '". $item[10] ."' WHERE product_stock_id = '". $ask_item['product_stock_id'] ."' ");
            }


        }


    }

    public function barcodeChange2()
    {
        die();

        //https://www.deercase.com/index.php?route=tool/functions/barcodeChange2


        $products = $this->db->query("SELECT * FROM ps_product_stock WHERE name LIKE '%iPhone%' ")->rows;


        //var_dump($products); die();

        foreach ($products as $product){
          //  var_dump($product); die();


            $this->db->query("UPDATE ps_product_stock SET quantity = '0' WHERE product_stock_id = '". $product['product_stock_id'] ."' ");

        }




    }

    public function editOrderTotal()
    {
        die();
        //https://www.deercase.com/index.php?route=tool/functions/editOrderTotal

        $orders = $this->db->query("SELECT * FROM `ps_order_total` WHERE `code` = 'campaign_price_total' ")->rows;

        foreach ($orders as $order){
            if($order['value'] != '0.0000'){
                $value = abs($order['value']);
                //var_dump($order); die();
                //$this->db->query("UPDATE ps_order_total SET `value` = '-". $value ."', title = 'İndirim' WHERE order_total_id = '". $order['order_total_id'] ."' ");
                //var_dump($order); die();
            }else{
                //var_dump($order); die();
            }

        }

    }

    public function mr022link301()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/mr022link301

        $products = $this->db->query("SELECT p.product_id, p.model, pd.href FROM ps_product p LEFT JOIN ps_product_description pd ON (p.product_id = pd.product_id) WHERE p.model = 'mr022' ")->rows;

        foreach ($products as $product){
            //var_dump($product); die();
            $this->db->query("INSERT INTO ps_301redirect SET url_from = '". $this->db->escape($product['href']) ."', url_to = '' ");
            echo $product['href'] . '<br>';
        }

    }

    public function hopiReport()
    {


        die();
        //https://www.deercase.com/index.php?route=tool/functions/hopiReport



        $report_data = array();

        for ($i=1; $i<=12; $i++){
            $x = $i + 1;
            if(strlen($i) == 1){
                $i = 0 . $i;
            }
            if(strlen($x) == 1){
                $x = 0 . $x;
            }

            $results = $this->db->query("SELECT *, ch.date_added, o.total AS order_total, o.currency_code, o.currency_value FROM ps_coupon c 
            LEFT JOIN ps_coupon_history ch ON (c.coupon_id = ch.coupon_id) 
            LEFT JOIN ps_order o ON (ch.order_id = o.order_id)
            WHERE c.name = 'HOPI' AND (ch.date_added >= '2020-".$i."-01' AND  ch.date_added < '2020-".$x."-01') ")->rows;


            if($results){
                $useing_count = 0;
                $total = 0;
                $total_discount = 0;
                foreach ($results as $result){
                    $useing_count++;
                    $total += $result['order_total'];
                    $total_discount += abs($result['amount']);
                }

                $total = $this->currency->format($total, $result['currency_code'], $result['currency_value']);
                $total_discount = $this->currency->format($total_discount, $result['currency_code'], $result['currency_value']);

                $mounth = '';
                switch ($i){
                    case '01':
                        $mounth = 'Ocak';
                        break;
                    case '02':
                        $mounth = 'Şubat';
                        break;
                    case '03':
                        $mounth = 'Mart';
                        break;
                    case '04':
                        $mounth = 'Nisan';
                        break;
                    case '05':
                        $mounth = 'Mayıs';
                        break;
                    case '06':
                        $mounth = 'Haziran';
                        break;
                    case '07':
                        $mounth = 'Temmuz';
                        break;
                    case '08':
                        $mounth = 'Ağustos';
                        break;
                    case '09':
                        $mounth = 'Eylül';
                        break;
                    case '10':
                        $mounth = 'Ekim';
                        break;
                    case '11':
                        $mounth = 'Kasım';
                        break;
                    case '12':
                        $mounth = 'Aralık';
                        break;

                }

                $report_data[] = array(
                    'useing_count' => $useing_count,
                    'total' => $total,
                    'total_discount' => $total_discount,
                    'mounth' => $mounth,

                );


            }


        }

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $objPHPExcel = new PHPExcel();

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Ay')
            ->setCellValue('B1', 'Kullanım Adedi')
            ->setCellValue('C1', 'Ciro')
            ->setCellValue('D1', 'Kupon İndirimi');



        $file_name = $this->config->get('config_name') . '-' . @date("Y-m-d-His") . "-hopi_coupon_report.xls";

        $row_i = 2;

        foreach ($report_data as $order) {


            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $row_i, $order['mounth'])
                ->setCellValue('B' . $row_i, $order['useing_count'])
                ->setCellValue('C' . $row_i, $order['total'])
                ->setCellValue('D' . $row_i, $order['total_discount']);

            $row_i++;


        }


        $objPHPExcel->getActiveSheet()->setTitle('Simple');


        $objPHPExcel->setActiveSheetIndex(0);


        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

        exit;




        
    }

    public function deleteOrderForAdmin()	{


        die();

        //https://www.deercase.com/index.php?route=tool/functions/deleteOrderForAdmin

        $orders = $this->db->query("SELECT order_id FROM ps_order WHERE customer_id = 61 ")->rows;

        foreach ($orders as $order){

            $order_id = $order['order_id'];

            $this->db->query("DELETE FROM ps_order WHERE order_id = '" . (int)$order_id . "'");
            $this->db->query("DELETE FROM ps_order_product WHERE order_id = '" . (int)$order_id . "'");
            $this->db->query("DELETE FROM ps_order_option WHERE order_id = '" . (int)$order_id . "'");
            $this->db->query("DELETE FROM ps_order_voucher WHERE order_id = '" . (int)$order_id . "'");
            $this->db->query("DELETE FROM ps_order_total WHERE order_id = '" . (int)$order_id . "'");
            $this->db->query("DELETE FROM ps_order_history WHERE order_id = '" . (int)$order_id . "'");
            $this->db->query("DELETE `or`, ort FROM ps_order_recurring `or`, `" . DB_PREFIX . "order_recurring_transaction` `ort` WHERE order_id = '" . (int)$order_id . "' AND ort.order_recurring_id = `or`.order_recurring_id");
            $this->db->query("DELETE FROM ps_affiliate_transaction WHERE order_id = '" . (int)$order_id . "'");
            $this->db->query("DELETE FROM ps_return WHERE order_id = '" . (int)$order_id . "'");
            $this->db->query("DELETE FROM ps_order_yurticikargo WHERE order_id = '" . (int)$order_id . "'");

            // Delete voucher data as well
            $this->db->query("DELETE FROM ps_voucher WHERE order_id = '" . (int)$order_id . "'");
            $this->db->query("DELETE FROM ps_voucher_history WHERE order_id = '" . (int)$order_id . "'");

        }



    }

    public function orderChange()
    {

        //https://www.deercase.com/index.php?route=tool/functions/orderChange

        die();

        $orders = $this->db->query("SELECT order_id FROM `ps_order` WHERE `payment_company` = 'akyuzmeltem89@hotmail.com' ")->rows;

        var_dump($orders); die();

        foreach ($orders as $order){

           // $this->db->query("UPDATE ps_order SET payment_company = '', payment_company_taxno = '', payment_company_taxadmin = '' WHERE order_id = '". (int)$order['order_id'] ."' ");

        }



    }

    public function reportProductPY0053()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/reportProductPY0053

        $orders = $this->db->query("SELECT o.order_id, o.firstname, o.lastname, o.email, o.telephone, op.name, op.quantity, o.date_added FROM ps_order o LEFT JOIN ps_order_product op ON (o.order_id = op.order_id) WHERE o.order_status_id = 5 AND op.model = 'PY0053' GROUP BY o.order_id ")->rows;

        var_dump($orders); die();
        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $objPHPExcel = new PHPExcel();

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Sipariş ID')
            ->setCellValue('B1', 'Müşteri Adı Soyadı')
            ->setCellValue('C1', 'Müşteri E-Posta')
            ->setCellValue('D1', 'Müşteri Telefon')
            ->setCellValue('E1', 'Ürün')
            ->setCellValue('F1', 'Adet')
            ->setCellValue('G1', 'Tarih');


        $file_name = "PY0053-orders.xls";

        $row_i = 2;


        foreach ($orders as $order) {

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $row_i, $order['order_id'])
                ->setCellValue('B' . $row_i, $order['firstname'] . ' ' . $order['lastname'])
                ->setCellValue('C' . $row_i, $order['email'])
                ->setCellValue('D' . $row_i, $order['telephone'])
                ->setCellValue('E' . $row_i, $order['name'])
                ->setCellValue('F' . $row_i, $order['quantity'])
                ->setCellValue('G' . $row_i, $order['date_added']);

            $row_i++;

        }


        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        $objPHPExcel->setActiveSheetIndex(0);


        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

        exit;

        
    }

    public function test()
    {

        die();
        var_dump($this->session->data['cart_count_log']);

        die();
        $exclude_campaign_product_ids = explode(',', $this->config->get('promotion')['exclude_campaign_product_ids']);

        if (in_array(1847339, $exclude_campaign_product_ids)){
            echo "2";
        }else{
            echo "ff";
        }
        die();
       // echo  phpinfo();

        $before_minute = date('Y H:i:s', strtotime('-20 minutes'));

        echo $before_minute;

        die();

        //https://www.deercase.com/index.php?route=tool/functions/test

        $day = date('Y-m-d H:i:s', strtotime('10 minutes'));

        $before_minute = date('Y-m-d H:i:s', strtotime('-2 minutes'));
        $later_minute = date('Y-m-d H:i:s', strtotime('2 minutes'));

        echo $before_minute . '<br>';
        echo $later_minute . '<br>';



    }

    public function changeProductImage()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/changeProductImage

        $products = $this->db->query("SELECT product_id, image FROM ps_product WHERE model LIKE '%AL%' AND image LIKE '%GLOSSY%'  ")->rows;
        //$products = $this->db->query("SELECT product_id, image FROM ps_product WHERE model LIKE '%AL%' AND image LIKE '%GLOSSY%' AND image NOT LIKE '%POPSOCKETLI%'  ")->rows;

       // var_dump($products); die();

        $count = 0;
        foreach ($products as $product){



            $image = explode('-', $product['image']);

            //var_dump($image); die();

            if(isset($image[4])){
                if($image[4] != 'POPSOCKETSIZ'){
                    $new_image_name = $image[0] .'-'. $image[1] .'-'. $image[2] .'-'. $image[3] . '-POPSOCKETSIZ-' . $image[4];
                   // $this->db->query("UPDATE ps_product SET image = '". $this->db->escape($new_image_name) ."' WHERE product_id = '". $product['product_id'] ."' ");
                   // var_dump($new_image_name, $product); die();
                    //var_dump($product); die();
                    //$count++;
                }
            }

            $images = $this->db->query("SELECT * FROM ps_product_image WHERE product_id = '". $product['product_id'] ."' ")->rows;

            foreach ($images as $img){
                $img_expo = explode('-', $img['image']);

                if(isset($img_expo[4])){
                    if($img_expo[4] != 'POPSOCKETSIZ'){

                        $new_imae_name = $img_expo[0] .'-'. $img_expo[1] .'-'. $img_expo[2] .'-'. $img_expo[3] . '-POPSOCKETSIZ-' . $img_expo[4];
                       // $this->db->query("UPDATE ps_product_image SET image = '". $this->db->escape($new_imae_name) ."' WHERE product_image_id = '". $img['product_image_id'] ."' ");
                        //var_dump($new_imae_name, $img_expo, $img); die();

                        //$count++;

                    }
                }

                //var_dump($img_expo, $product); die();

            }

            //var_dump($images); die();

        }

        var_dump($count); die();

    }

    public function changeProductImage2()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/changeProductImage2

        $products = $this->db->query("SELECT product_id, image FROM ps_product WHERE model LIKE '%MR%' AND image LIKE '%GLOSSY%'  ")->rows;
        //$products = $this->db->query("SELECT product_id, image FROM ps_product WHERE model LIKE '%AL%' AND image LIKE '%GLOSSY%' AND image NOT LIKE '%POPSOCKETLI%'  ")->rows;

       // var_dump($products); die();

        $count = 0;
        foreach ($products as $product){



            $image = explode('-', $product['image']);

            //var_dump($image); die();

            if(isset($image[4])){
                if($image[4] != 'POPSOCKETSIZ'){
                    $new_image_name = $image[0] .'-'. $image[1] .'-'. $image[2] .'-'. $image[3] . '-POPSOCKETSIZ-' . $image[4];
                   // $this->db->query("UPDATE ps_product SET image = '". $this->db->escape($new_image_name) ."' WHERE product_id = '". $product['product_id'] ."' ");
                   // var_dump($new_image_name, $product); die();
                    //var_dump($product); die();
                    //$count++;
                }
            }

            $images = $this->db->query("SELECT * FROM ps_product_image WHERE product_id = '". $product['product_id'] ."' ")->rows;

            foreach ($images as $img){
                $img_expo = explode('-', $img['image']);

                if(isset($img_expo[4])){
                    if($img_expo[4] != 'POPSOCKETSIZ'){

                        $new_imae_name = $img_expo[0] .'-'. $img_expo[1] .'-'. $img_expo[2] .'-'. $img_expo[3] . '-POPSOCKETSIZ-' . $img_expo[4];
                       // $this->db->query("UPDATE ps_product_image SET image = '". $this->db->escape($new_imae_name) ."' WHERE product_image_id = '". $img['product_image_id'] ."' ");
                        //var_dump($new_imae_name, $img_expo, $img); die();

                        //$count++;

                    }
                }

                //var_dump($img_expo, $product); die();

            }

            //var_dump($images); die();

        }

        var_dump($count); die();

    }

    public function doubleOrderReport()
    {

        //https://www.deercase.com/index.php?route=tool/functions/doubleOrderReport

        if(isset($this->request->get['day']) AND $this->request->get['day']){
            $day = $this->request->get['day'];
        }else{
            $day = date('Y-m-d');
        }


        if(isset($this->request->get['key']) AND $this->request->get['key'] == '77l6wQrJgHD9iKPNCNY7sGSV1WcA6Utt'){

            $orders = $this->db->query("SELECT order_id, lastname, firstname  FROM ps_order WHERE date_added > '". $day ." 00:00:00' AND date_added < '". $day ." 23:59:00'  AND order_status_id NOT IN(14,22,8,24,9,7,11,10,0) AND payment_code = 'cod' ")->rows;

            $double_orders = array();
            foreach ($orders as $order){
                $ask_mail = $this->db->query("SELECT * FROM ps_order WHERE firstname = '". $this->db->escape($order['firstname']) ."' AND lastname = '". $this->db->escape($order['lastname']) ."' AND date_added > '". $day ." 00:00:00' AND date_added < '". $day ." 23:59:00'  AND order_status_id NOT IN(14,22,8,24,9,7,11,10,0) AND payment_code = 'cod' ");
                if($ask_mail->num_rows > 1){
                    foreach ($ask_mail->rows as $row){
                        $double_orders[$row['order_id']] = array(
                            'firstname' => $row['firstname'],
                            'lastname' => $row['lastname'],
                            'email' => $row['email'],
                            'order_id' => $row['order_id']
                        );
                    }
                }
            }

            require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

            $objPHPExcel = new PHPExcel();

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', 'Order ID')
                ->setCellValue('B1', 'Firstname')
                ->setCellValue('C1', 'Lastname')
                ->setCellValue('D1', 'Email');

            $file_name = $this->config->get('config_name') . '-' . $day . "-DoubleOrdersExport.xls";

            $row_i = 2;


            foreach ($double_orders as $order) {

                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $row_i, $order['order_id'])
                    ->setCellValue('B' . $row_i, $order['firstname'])
                    ->setCellValue('C' . $row_i, $order['lastname'])
                    ->setCellValue('D' . $row_i, $order['email']);

                $row_i++;

            }


            $objPHPExcel->getActiveSheet()->setTitle('Simple');

            $objPHPExcel->setActiveSheetIndex(0);

            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $file_name . '"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');

           // exit;


            /*
            $double_orders = sort($orders, function ($a, $b){
                return $a['email'] == $b['email'] ? 1 : -1;
            });

            var_dump($double_orders);

            */


        }





    }

    public function redisTest()
    {

        //https://www.deercase.com/index.php?route=tool/functions/redisTest

        $redis = new Redis();
        $redis->connect('127.0.0.1', 6379);

        $veri[] = array(
            'key' => "anahtarım"
        );

        $veri[] = array(
            'key' => "anahtarım 2"
        );

        $redis->set('deneme' , json_encode($veri, JSON_UNESCAPED_UNICODE));

        $get_order = $redis->get('deneme');
        $get_order = json_decode($get_order, true);

        var_dump($get_order); die();

    }

    public function orderSaveToRedis()
    {

        //die();

        //86400

        //https://www.deercase.com/index.php?route=tool/functions/orderSaveToRedis

        $redis = new Redis();
        $redis->connect('127.0.0.1', 6379);


        /*
        $orders = $this->db->query("SELECT order_id FROM ps_order WHERE order_status_id > 0 LIMIT 300  ")->rows;

        $order_data = array();
        foreach ($orders as $order){
            $order_row = $this->db->query("SELECT * FROM ps_order WHERE order_id = '". $order['order_id'] ."'  ")->row;
            $order_products = $this->db->query("SELECT * FROM ps_order_product WHERE order_id = '". $order['order_id'] ."'  ")->rows;

            $order_data[] = array(
                'order_row' => $order_row,
                'order_products' => $order_products,
            );

        }

        $redis->set('orders' , json_encode($order_data, JSON_UNESCAPED_UNICODE));*/



        //$get_order = $redis->get('orders');
       // $get_order = json_decode($get_order, true);
       // var_dump($get_order); die();




        $users = [1, 2, 3, 4];
        $user_values = $redis->pipeline(function ($pipe) use ($users) {
            foreach ($users as $val) {
                $pipe->get('test' . $val);
            }
        });

        var_dump($user_values); die();




        //$redis->del('orders');
        
    }

    public function getProducts()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/getProducts

        $products = $this->db->query("SELECT p.product_id, p.product_stock_id, ps.quantity FROM ps_product p LEFT JOIN ps_product_stock ps ON (p.product_stock_id = ps.product_stock_id) WHERE p.product_stock_id != '' ORDER BY p.product_stock_id ASC ")->rows;
        var_dump($products); die();
        foreach ($products as $product){
            echo $product['product_id'] . '<br>';
        }



    }

    public function createxml()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/createxml

        $domtree = new DOMDocument("1.0", "UTF-8");
        $domtree->formatOutput = true;
        $urlset = $domtree->createElementNS("http://www.sitemaps.org/schemas/sitemap/0.9", "urlset");
        $domtree->appendChild($urlset);
        $urlset->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xhtml", "http://www.w3.org/1999/xhtml");

        {
            //create the `url`
            $url = $domtree->createElement("url");
            //add the url
            $url_root = $urlset->appendChild($url);

            {
                //create the `loc`
                $loc = $domtree->createElement("loc", "http://www.example.com/english/page.html");
                $changefreq = $domtree->createElement("changefreq", "weekly");
                $lastmod = $domtree->createElement("lastmod", "1");
                $priority = $domtree->createElement("priority", "1");


                //add the loc to the url
                $url_root->appendChild($loc);
                $url_root->appendChild($changefreq);
                $url_root->appendChild($lastmod);
                $url_root->appendChild($priority);

                $image = $domtree->createElement("image:image");
                $image_loc = $domtree->createElement('image:loc', "deneme");
                $image_caption = $domtree->createElement('image:caption', '<![CDATA[ deneme ]]>');
                $image_title = $domtree->createElement('image:title', '<![CDATA[ image title ]]>');

                $image->appendChild($image_loc);
                $image->appendChild($image_caption);
                $image->appendChild($image_title);

                $url->appendChild($image);


                /*
                //create `xhtml:link`
                $xhtml_link = $domtree->createElement("xhtml:link");
                //add the `xhtml:link` to the `url`
                $url->appendChild($xhtml_link);

                {
                    //create an `rel` attribute to the `xhtml:link`
                    $dom_attribute = $domtree->createAttribute("rel");
                    $dom_attribute->value="alternate";
                    //add the attribute to the `xhtml:link`
                    $xhtml_link->appendChild($dom_attribute);

                    //create an `hreflang` attribute to the `xhtml:link`
                    $dom_attribute = $domtree->createAttribute("hreflang");
                    $dom_attribute->value="en";
                    //add the attribute to the `xhtml:link`
                    $xhtml_link->appendChild($dom_attribute);

                    //create an `href` attribute to the `xhtml:link`
                    $dom_attribute = $domtree->createAttribute("href");
                    $dom_attribute->value="https://www.deercase.com/page.html";
                    //add the attribute to the `xhtml:link`
                    $xhtml_link->appendChild($dom_attribute);



                } */
            }
        }

        $domtree->save('kisiler_new.xml');
        echo $domtree->saveHTML();


    }

    public function editFilters()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/editFilters

        /*$products = $this->db->query("SELECT * FROM ps_product_to_category WHERE category_id = 5081 ")->rows;

        //var_dump($products); die();

        foreach ($products as $product){
            $this->db->query("DELETE FROM ps_product_filter WHERE product_id = '". $product['product_id'] ."' ");
            $this->db->query("INSERT INTO ps_product_filter SET product_id = '". $product['product_id'] ."', filter_id = 76 ");
        }*/


        $products = array(552296,552303,552301,552299,552298,552297,552294,552300,552302,552293,552305,552295,552304,555349,555348,555343,555346,555347,555345,555341);
        //$products = array(555404,555405,555407,555406,555409,555408,555370,555369,555371,555372,555373,555374,555375,555376,555378,555377,555362,555360,555361,555363,555359,555357);
        //$products = array(552306,552307,552308,552309,552310,552311,552312,552313,552314,552315,552316,552317,552318,555353,555351,555355,555350,555356,555352,555354,555342);
       // $products = array(555379,555389,555390,555391,555396,555392,555397,555395,555394,555393,555366,555364,555365,555367,555368,555358,555399,555403,555401,555400,555398,555402);

        foreach ($products as $product){
           // $this->db->query("DELETE FROM ps_product_filter WHERE product_id = '". $product['product_id'] ."' ");
           // $this->db->query("INSERT INTO ps_product_filter SET product_id = '". $product['product_id'] ."', filter_id = 76 ");
            $this->db->query("UPDATE ps_product_filter SET filter_id = 74 WHERE product_id = '". $product ."' ");
        }


    }

    public function getCartInactive()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/getCartInactive

        $orders = $this->db->query("SELECT o.order_id, op.customcase_image FROM ps_order o LEFT JOIN ps_order_product op ON (o.order_id = op.order_id) WHERE o.order_status_id != 0 AND op.customcase_image != '' AND o.date_added < '2021-01-01 00:00:00' ")->rows;

        var_dump($orders); die();

    }

    public function dayCollection()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/dayCollection

        $products = $this->db->query("SELECT product_id FROM ps_product WHERE model LIKE '%day%' LIMIT 10000 ")->rows;

        foreach ($products as $product){

            //var_dump($product); die();


            $this->db->query("DELETE FROM ps_product WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_attribute WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_description WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_discount WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_filter WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_image WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_option WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_option_value WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_related WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_related WHERE related_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_reward WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_special WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_to_category WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_to_download WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_to_layout WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_to_store WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_product_recurring WHERE product_id = " . (int) $product['product_id']);
            $this->db->query("DELETE FROM ps_review WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_homepage_tab_products WHERE product_id = '" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_url_alias WHERE query = 'product_id=" . (int) $product['product_id'] . "'");
            $this->db->query("DELETE FROM ps_coupon_product WHERE product_id = '" . (int) $product['product_id'] . "'");


        }

       // var_dump($products); die();

    }

    public function getIsmOrders()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/getIsmOrders

        $orders = $this->db->query("SELECT * FROM ps_order o LEFT JOIN ps_order_product op ON (o.order_id = op.order_id) WHERE op.model LIKE '%ism%' AND o.date_added > '2021-03-15 00:00:00' ")->rows;
        foreach ($orders as $order){

            $pattern_text = json_decode($order['customer_pattern_data'], true);
            if($pattern_text['pattern_text']){
               // var_dump($pattern_text['pattern_text']); die();
                if(strlen($pattern_text['pattern_text']) > 10){
                    echo $order['order_id'] . '<br>';
                }
            }else{
                //var_dump($pattern_text['pattern_text']); die();
            }


        }


    }

    public function orderEditCity()
    {
        die();
        //https://www.deercase.com/index.php?route=tool/functions/orderEditCity

        $orders = array(
            '191416' => 'Gölbaşı',
            '191421' => 'Ataşehir',
            '191424' => 'Beylikdüzü',
            '191436' => 'Etimesgut',
            '191437' => 'Seyhan',
            '191442' => 'Başakşehir',
            '191448' => 'Bornova',
            '191455' => 'Yumurtalık',
            '191458' => 'Silopi',
            '191459' => 'Seyhan',
            '191462' => 'Mustafakemalpaşa',
            '191464' => 'Gölcük',
            '191467' => 'Keçiören',
            '191481' => 'Yeşilyurt',
            '191482' => 'Kadıköy',
            '191486' => 'Bayrampaşa',
            '191491' => 'Çankaya',
            '191496' => 'Besni',
            '191497' => 'Çankaya',
            '191499' => 'Pendik',
            '191500' => 'Tepebaşı',
            '191502' => 'Kayapınar',
            '191504' => 'Narlıdere',
            '191522' => 'Tepebaşı ',
            '191529' => 'Yenişehir',
            '191537' => 'Didim',
            '191541' => 'Kâğıthane',
            '191542' => 'Çankaya',
            '191553' => 'Başakşehir',
            '191556' => 'Kadıköy',
            '191569' => 'Kadıköy',
            '191578' => 'Bornova',
            '191583' => 'Döşemealtı',
            '191584' => 'Büyükçekmece',
            '191586' => 'Yeşilyurt',
            '191588' => 'Çerkezköy',
            '191590' => 'Çankaya',
            '191591' => 'Buca',
            '191592' => 'Soma',
            '191593' => 'Gürsu',
            '191594' => 'Çukurova',
            '191595' => 'Çankaya',
        );

        foreach ($orders as $order_id => $order){
           // var_dump($order_id, $order); die();
            $this->db->query("UPDATE ps_order SET shipping_city = '". $this->db->escape($order) ."' WHERE order_id = '". (int)$order_id ."' ");


        }

        /*
        $orders = $this->db->query("SELECT order_id, customer_id FROM `ps_order` WHERE `date_added` > '2021-03-17 00:00:00' AND `order_status_id` > 0 AND shipping_city = '' AND customer_id != 0 ")->rows;
        var_dump($orders); die();
        foreach ($orders as $order_id => $order){

            $get_adress = $this->db->query("SELECT city FROM ps_address WHERE customer_id = '". $order['customer_id'] ."' ")->row;

            if(isset($get_adress['city']) AND $get_adress['city']){
                echo "UPDATE ps_order SET shipping_city = '". $this->db->escape($get_adress['city']) ."' WHERE order_id = '". (int)$order['order_id'] ."' " . "<br>";
            //$this->db->query("UPDATE ps_order SET shipping_city = '". $this->db->escape($get_adress['city']) ."' WHERE order_id = '". (int)$order['order_id'] ."' ");
            }

          //  $this->db->query("UPDATE ps_order SET shipping_city = '". $this->db->escape($order) ."' WHERE order_id = '". (int)$order_id ."' ");

        } */

    }

    public function orderCarcoFind()
    {

        if(!isset($this->request->get['ssHkey'])){
            die();
        }

        //https://www.deercase.com/index.php?route=tool/functions/orderCarcoFind

        $orders = $this->db->query("SELECT order_id FROM ps_order WHERE order_id BETWEEN 191168 AND 191409 AND order_status_id > 0 ")->rows;

        $count = 0;
        foreach ($orders as $order){
            $cargo_info = $this->db->query("SELECT * FROM `ps_order_yurticikargo` WHERE `order_id` = '". $order['order_id'] ."' ")->row;
            if(isset($cargo_info['kargo_url']) AND $cargo_info['kargo_url']){
                $count++;
                echo "OrderId:" . $order['order_id'] . ' => ' . $cargo_info['kargo_url'] . '<br>';
                /*$order_steps = $this->db->query("SELECT * FROM `ps_order_yurticikargo_steps` WHERE yurticikargo_id = '". $cargo_info['yurticikargo_id'] ."' ")->rows;
                if($order_steps){

                    var_dump($order_steps); die();
                }*/
            }
        }

        echo 'Toplam: ' . $count;

    }

    public function getByexpressCity()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/getByexpressCity

       // $url = 'https://api.byexpresskargo.net/AdresBilgi/IlListesi';
        $url = 'https://api.byexpresskargo.net/AdresBilgi/IlceListesi';
        $send_data = array(
            'SozlesmeNumarasi' => (int)$this->config->get('byexpresskargo_contrat_no'),
            'KullaniciAdi' => $this->config->get('byexpresskargo_username'),
            'Sifre' => $this->config->get('byexpresskargo_password'),
        );

        //var_dump($send_data); die();

        $result = json_decode($this->callAPI($url, json_encode($send_data, JSON_UNESCAPED_UNICODE)), true);

        var_dump($result); die();



    }

    public function editCustomerZone()
    {

        //https://www.deercase.com/index.php?route=tool/functions/editCustomerZone

        die();
        $count = 0;
        $customers = $this->db->query("SELECT * FROM `ps_address` WHERE `zone_id` = 0 ORDER BY `address_id` DESC ")->rows;

        foreach ($customers as $customer){
            $expo = explode('-', $customer['city']);
            if(isset($expo[0]) AND isset($expo[1])){
                $zone = trim($expo[1]);
                $city = trim($expo[0]);
                $dist_ask2 = $this->db->query("SELECT * FROM ps_district d LEFT JOIN ps_zone z ON (d.zone_id = z.zone_id) 
                WHERE d.district_name = '". $this->db->escape($zone) ."' AND z.name = '". $this->db->escape($city) ."'  ")->row;
                if($dist_ask2){
                    //var_dump($dist_ask2); die();
                    $count++;
                   // $this->db->query("UPDATE ps_address SET zone_id = '". $dist_ask2['zone_id'] ."', city = '". $dist_ask2['district_id'] ."' WHERE address_id = '". $customer['address_id'] ."' ");
                }

            }


        }

        echo $count;

    }

    public function editCustomerCityCode()
    {


        die();
        //https://www.deercase.com/index.php?route=tool/functions/editCustomerCityCode

        $count = 0;
        $customers = $this->db->query("SELECT customer_id FROM ps_customer LIMIT 10000 ")->rows;

        foreach ($customers as $customer){
            $c_adress = $this->db->query("SELECT * FROM ps_address WHERE customer_id = '". $customer['customer_id'] ."' ")->rows;
            foreach ($c_adress as $c_adres){
                $city_ask = $this->db->query("SELECT * FROM ps_district WHERE district_id = '". (int)$c_adres['city'] ."' AND zone_id = '". (int)$c_adres['zone_id'] ."' ")->row;
                if(!$city_ask){

                    echo $customer['customer_id'] . ' => ' . $c_adres['city'] . '<br>';
                    $count++;

                   /* $expo = explode('-', $c_adres['city']);
                    if(isset($expo[0]) AND isset($expo[1])){
                        $dist_ask = $this->db->query("SELECT * FROM ps_district WHERE district_name = '". $this->db->escape($expo[0]) ."' AND zone_id = '". (int)$c_adres['zone_id'] ."' ")->row;
                        //echo "SELECT * FROM ps_district WHERE district_name = '". $this->db->escape($expo[0]) ."' AND zone_id = '". (int)$c_adres['zone_id'] ."' " . '<br>';
                        if($dist_ask){
                            echo $customer['customer_id'] . ' => ' . $c_adres['city'] . '<br>';
                            $count++;
                        }else{
              $dist_ask2 = $this->db->query("SELECT * FROM ps_district d LEFT JOIN ps_zone z ON (d.zone_id = z.zone_id) 
                WHERE d.district_name = '". $this->db->escape(trim($expo[0])) ."' AND z.name = '". $this->db->escape($expo[1]) ."'  ")->row;

                        if($dist_ask2){
                            var_dump($dist_ask2); die();
                        }

                        }

                    }*/

                }
            }

        }


        echo 'Toplam Müştri Sayısı: ' . count($customers) . '<br>';
        echo 'Toplam Doğru Adres Sayısı: ' . $count . '<br>';


    }

    public function ttelekomOrderReport()
    {

        //TurkTelekom

        //https://www.deercase.com/index.php?route=tool/functions/ttelekomOrderReport


    }

    public function deleteZoneAddress()
    {


        die();
      //  $log = new Log("DeleteZoneIdZero.txt");

        //https://www.deercase.com/index.php?route=tool/functions/deleteZoneAddress

        //$this->db->query("DELETE FROM ps_address WHERE zone_id = 0 ");


        $address = $this->db->query("SELECT city, customer_id FROM ps_address ")->rows;


        $count = 0;
        foreach ($address as $addres){

            $city = $this->db->query("SELECT * FROM ps_district WHERE district_id = '". $addres['city'] ."' ")->row;

            if(!$city){ //var_dump($addres); die();
                $count++;
              //  $this->db->query("DELETE FROM ps_address WHERE customer_id = '". $addres['customer_id'] ."' ");
            }



        }

        echo $count;
        
    }

    public function iyzicoLogFiles()
    {


        //die();
        //https://www.deercase.com/index.php?route=tool/functions/iyzicoLogFiles&key=4n5b345b34nmb53n4b5&order_id=438849

        if(isset($this->request->get['order_id']) AND isset($this->request->get['key'])){

            $order_id = $this->request->get['order_id'];
            if($this->request->get['key'] != '4n5b345b34nmb53n4b5'){
                echo "Key is not true" . '<br>'; die();
            }

        }else{
            echo "Key is not true" . '<br>'; die();
        }

        

        echo $order_id . '<br>';

        if ($handle = opendir(DIR_LOGS . 'iyzico')) {

            while (false !== ($entry = readdir($handle))) {

                if ($entry != "." && $entry != "..") {
                    if($entry == $order_id . '_IyzicoCallbackPostDataLogs.txt'){
                        echo "$entry\n";

                        $myfile = fopen(DIR_LOGS . "iyzico/".$order_id."_IyzicoCallbackPostDataLogs.txt", "r") or die("Unable to open file!");
                        echo fread($myfile,filesize(DIR_LOGS . "iyzico/".$order_id."_IyzicoCallbackPostDataLogs.txt"));
                        fclose($myfile);
                    }
                   // $this->session->data['customer_order_images'][] = $entry;
                    //$count++;

                }
            }

            closedir($handle);
        }

        echo "Line End <br>";

    }

    public function customer_order_images()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/customer_order_images

        $count = 0;

        //adee57d3220e73a6a1e1aba47edd9151.jpg
        /*
        $this->session->data['customer_order_images'] = array();

        if ($handle = opendir(DIR_IMAGE . 'customer_order_images')) {

            while (false !== ($entry = readdir($handle))) {

                if ($entry != "." && $entry != "..") {
                    if($entry == 'adee57d3220e73a6a1e1aba47edd9151.jpg'){
                        echo "$entry\n";
                    }
                    $this->session->data['customer_order_images'][] = $entry;
                    //$count++;

                }
            }

            closedir($handle);
        }*/

        //echo $count;

        $count = 0;
        foreach ($this->session->data['customer_order_images'] as $image){
            $find = $this->db->query("SELECT * FROM ps_order_product WHERE case_order_image LIKE '%". $this->db->escape($image) ."%' ")->row;
            if(!$find){
                $count++;
               // var_dump($image); die();
            }
        }

        echo $count;

    }

    public function getClCategories2()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/getClCategories

        $cayegories = $this->db->query("SELECT * FROM ps_category c 
            LEFT JOIN ps_category_description cd ON (c.category_id = cd.category_id) 
            LEFT JOIN ps_category_path cp ON (c.category_id = cp.category_id)
            WHERE c.status = 1 AND cd.language_id = 1 AND cp.level = 2 AND cd.name LIKE '%Renkli Silikon%' ")->rows;

        $exist_category = array();
        foreach ($cayegories as $cayegory){

            $ask_product = $this->db->query("SELECT p.product_id FROM ps_product_to_category p2c LEFT JOIN ps_product p ON (p2c.product_id = p.product_id) WHERE p.status = 1 AND p2c.category_id = '". $cayegory['category_id'] ."' ")->row;
            if($ask_product){
                $exist_category[] = $cayegory['name'];
            }
        }

        $exist_category = array_unique($exist_category);

        foreach ($exist_category as $e_category){
            echo $e_category . '<br>';
        }


    }
    
    public function getClCategories()
    {

        //https://www.deercase.com/index.php?route=tool/functions/getClCategories

        $products = $this->db->query("SELECT p.product_id, cd.name as name, c.category_id FROM ps_product p 
        LEFT JOIN ps_product_description pd ON (p.product_id = pd.product_id) 
        LEFT JOIN ps_product_to_category p2c ON (p.product_id = p2c.product_id)
        LEFT JOIN ps_category c ON (p2c.category_id = c.category_id)
        LEFT JOIN ps_category_description cd ON (c.category_id = cd.category_id)
        LEFT JOIN ps_category_path cp ON (c.category_id = cp.category_id)
        WHERE 
              cp.level = 2 AND cd.language_id = 1 AND c.status = 1 AND
              p.status = 1 AND pd.language_id = 1 AND pd.name LIKE '%Renkli Silikon%' GROUP BY p2c.category_id ")->rows;

       // var_dump($products); die();

        $exist_category = array();
        foreach ($products as $product){
            $ask_product = $this->db->query("SELECT p.product_id FROM ps_product_to_category p2c LEFT JOIN ps_product p ON (p2c.product_id = p.product_id) WHERE p.status = 1 AND p2c.category_id = '". $product['category_id'] ."' ")->row;
            if($ask_product){
                if(strpos($product['name'],'Renkli Silikon') !== false){
                    $exist_category[] = $product['name'];
                }

            }
        }

        foreach ($exist_category as $e_category){
            echo $e_category . '<br>';
        }

    }

    public function getClockOptionReport()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/getClockOptionReport

        $order_options = $this->db->query("SELECT o.order_id, oo.order_product_id, oo.value FROM ps_order_option oo LEFT JOIN ps_order o ON (oo.order_id = o.order_id) WHERE o.order_status_id = 5  AND oo.name = 'Beden' ")->rows;

        foreach ($order_options as $order_option){
            $order_quantity = $this->db->query("SELECT quantity, product_id FROM ps_order_product WHERE order_product_id = '". $order_option['order_product_id'] ."' ")->row;
        }





    }

    public function manualFilterAdd()
    {
        die();

        //https://www.deercase.com/index.php?route=tool/functions/manualFilterAdd

        $models = array(
            'hpt' => 124,
            'hpanv' => 124,
        );


        foreach ($models as $model => $key){
            $products = $this->db->query("SELECT product_id FROM ps_product WHERE model LIKE '%". $this->db->escape($model) ."%' ")->rows;
                //var_dump(count($products));
            foreach ($products as $product){
                $ask_filter = $this->db->query("SELECT * FROM ps_product_filter WHERE product_id = '". $product['product_id'] ."' AND filter_id = '". $key ."'  ")->row;
                if(!$ask_filter){
                    $this->db->query("INSERT INTO ps_product_filter SET product_id = '". $product['product_id'] ."', filter_id = '". $key ."' ");
                    //echo 'Eklendi -> ' . $product['product_id'] . ' <br>';
                }else{
                    echo "Var <br>";
                   // $this->db->query("DELETE FROM ps_product_filter WHERE product_id = '". $product['product_id'] ."' AND filter_id = '". $key ."' ");
                }

            }

        }

        
    }

    public function iyzicoMissingOrders()
    {

       // die();
        //https://www.deercase.com/index.php?route=tool/functions/iyzicoMissingOrders

        $orders = $this->db->query("SELECT order_id, total FROM ps_order WHERE order_status_id > 0 AND date_added BETWEEN '2021-04-13 17:20:00' AND '2021-04-13 22:47:00' ")->rows;

        foreach ($orders as $order){
            $order_total = $this->db->query("SELECT value FROM `ps_order_total` WHERE `order_id` = '". $order['order_id'] ."' AND code = 'total' ")->row['value'];

            $iyzico_order_detail = $this->db->query("SELECT * FROM ps_iyzico_order WHERE request_type = 'get_auth' AND note = 'callback'  AND transaction_status = 'success' AND order_id = '". $order['order_id'] ."' ")->row;

            if($iyzico_order_detail){ //var_dump($iyzico_order_detail); die();
                $api_response = json_decode($iyzico_order_detail['api_response'], true);
                if($api_response['status'] === 'success' ){

                    if($api_response['price'] == $api_response['paidPrice']){
                        $fark = ($api_response['price'] - $order_total);
                        if($fark){

                            $refund_check = $this->db->query("SELECT * FROM `ps_iyzico_order_refunds` WHERE `order_id` = '". $order['order_id'] ."' AND total_refunded != 0 ")->row;

                            if(!$refund_check){
                                $paymentTransactionId = $api_response['itemTransactions'][0]['paymentTransactionId'];
                                $basket_id = $api_response['basketId'];
                           //     echo  "OrderId:" . $order['order_id'] ." Tek çekim işlem. Fark = " . $fark . " --- " . $basket_id .'<br>';
                                //$this->iyzicoMissingOrders($fark, $paymentTransactionId);
                            }

                        }
                    }else{
                        $basket_id = $api_response['basketId'];
                         echo  "OrderId:" . $order['order_id'] . " " . $basket_id .'<br>';

                    }

                   // echo "OrderID: ". $order['order_id'] ." => Order Total: " . $order_total . ' -------- ' . " Iyzico Price: " . $api_response['price'] . " => Iyzico Paid Price: " . $api_response['paidPrice'] . "<br>";
                }
            }



        }



    }

    public function exportCustomerPhones()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/exportCustomerPhones

        $customers = $this->db->query("SELECT telephone FROM ps_customer")->rows;
           // die();
       // var_dump($customers); die();
        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $objPHPExcel = new PHPExcel();

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Telephone');


        $file_name = "exportCustomerPhones.xls";

        $row_i = 2;

        foreach ($customers as $customer) {

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $row_i, $customer['telephone']);
            $row_i++;
        }


        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        $objPHPExcel->setActiveSheetIndex(0);


        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

        exit;


    }

    public function moveCategoires()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/moveCategoires


        $categories = $this->db->query("SELECT * FROM ps_category_description WHERE name LIKE '%Girl Boss%' ")->rows;

        foreach ($categories as $key => $category){
            $cat = explode('Girl Boss', $category['name']);
            $find_same_cat = $this->db->query("SELECT * FROM ps_category_description WHERE name LIKE '". $this->db->escape($cat[0]) ."Retro Telefon Kılıfı' ")->row;

            echo $key . ' - ' .$category['name'] . ' => ' . $find_same_cat['name'] . '<br>';

            $find_products = $this->db->query("SELECT * FROM ps_product_to_category WHERE category_id = '". $category['category_id'] ."' ")->rows;

            $find_same_cat_parents = $this->db->query("SELECT * FROM ps_category_path WHERE category_id = '". $find_same_cat['category_id'] ."' ")->rows;


            if($find_products){
               // echo "var";
                foreach ($find_products as $product){
                    //var_dump($product);
                    //  var_dump($find_same_cat_parents); die();

                     $this->db->query("DELETE FROM ps_product_to_category WHERE product_id = '". $product['product_id'] ."' ");
                    echo "DELETE FROM ps_product_to_category WHERE product_id = '". $product['product_id'] ."'  Çalıştırıldı <br>";
                    foreach ($find_same_cat_parents as $cats){
                        $this->db->query("INSERT INTO ps_product_to_category SET product_id = '". $product['product_id'] ."', category_id = '". $cats['path_id'] ."' ");
                        echo "INSERT INTO ps_product_to_category SET product_id = '". $product['product_id'] ."', category_id = '". $cats['path_id'] ."' Eklendi <br>";
                    }

                }
                echo "<br>";
            }

            echo "<br>";


            flush();





        }

    }

    public function changeAndMoveImages()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/changeAndMoveImages

        //var_dump("fdfdf"); die();

        $file_names = array(
                'LMS142' => 'IMP050',
                'LMS152' => 'IMP060',
        );

        //var_dump($file_names); die();

        $count = 0;
        foreach ($file_names as $file1 => $file2){
           // var_dump(DIR_IMAGE . 'repository/impact/' . $file1, $file1); die();

            $target_path = DIR_IMAGE . 'repository/impact/' . $file2;
            if(!is_dir($target_path)){
                mkdir($target_path, 0777);
            }

           // var_dump($target_path); die();

            $file_name = DIR_IMAGE . 'repository/impact/' . $file1;
            if ($handle = opendir($file_name)) {
                while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != "..") {
                        //echo "$entry"."\n";
                        $count++;
                        $expo = explode($file1, $entry);

                        echo "Old name => " . $entry . "<br>";
                        echo "New name => " . $file2 . $expo[1]. "<br>";

                        //die();

                        copy($file_name . '/' .$entry, $target_path . '/' . $file2 . $expo[1]);
                       // die();

                    }
                }
                closedir($handle);
            }

            flush();
        }

        echo $count;

    }

    public function p2cControl()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/p2cControl


        $products = $this->db->query("SELECT product_id FROM ps_product_to_category ")->rows;

        foreach ($products as $product){
            $ask = $this->db->query("SELECT product_id FROM ps_product WHERE product_id = '". $product['product_id'] ."' ")->row;
            if(!$ask){
                echo $product['product_id'] . "<br>";
            }
        }


    }

    public function showCaseTrue()
    {

        

        //https://www.deercase.com/index.php?route=tool/functions/showCaseTrue&category_id=6146

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



        $products = $this->db->query("SELECT * FROM ps_product_to_category WHERE category_id = '". $category_id ."' ")->rows;

        foreach ($products as $product){

            $get_product = $this->db->query("SELECT product_id FROM ps_product WHERE product_id = '". $product['product_id'] ."' AND image LIKE '%SEFFAF-SEFFAF_SAYDAM%' ")->row;

            if($get_product){
                $this->db->query("UPDATE ps_product SET product_showcase = 1 WHERE product_id = '". $get_product['product_id'] ."' ");
                echo $get_product['product_id'] . '<br>';
            }

        }




    }

    public function tursabCouponCahange()
    {


        die();
        //https://www.deercase.com/index.php?route=tool/functions/tursabCouponCahange

        $coupons = $this->db->query("SELECT * FROM `ps_coupon` WHERE `name` = 'Türsab' ")->rows;
        //var_dump($coupons); die();
        foreach ($coupons as $coupon){
            $this->db->query("UPDATE ps_coupon SET date_end = '2021-11-01' WHERE coupon_id = '". $coupon['coupon_id'] ."' ");
        }


        //UPDATE `ps_coupon` SET `date_end` = '2021-11-01' WHERE `ps_coupon`.`coupon_id` = 907750;

    }

    public function ucalikiode()
    {


        die();
        //https://www.deercase.com/index.php?route=tool/functions/ucalikiode

        $orders = $this->db->query("SELECT telephone FROM `ps_order` WHERE `date_added` > '2021-07-23 23:59:00' AND order_status_id != 0 GROUP BY telephone")->rows;


        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $objPHPExcel = new PHPExcel();

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Telephone');


        $file_name = "exportOrdersPhones.xls";

        $row_i = 2;

        foreach ($orders as $order) {

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $row_i, $order['telephone']);
            $row_i++;
        }


        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        $objPHPExcel->setActiveSheetIndex(0);


        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

        exit;






    }

    public function changeImagePath()
    {

        die();
        // repository/aquaman/
        // repository/DC/aquaman/

        $search = 'repository/looney-tunes/';
        $replace = 'repository/DC/looney-tunes/';

        //https://www.deercase.com/index.php?route=tool/functions/changeImagePath

        $products = $this->db->query("SELECT product_id, image FROM ps_product WHERE image LIKE '%". $this->db->escape($search) ."%' ")->rows;

        foreach ($products as $product){

            //echo "First Image: " . $product['image'] . '<br>';
            $edit_image = str_replace($search, $replace, $product['image']);
            //echo "Edit Image: " . $edit_image . '<br>';

           // die();

            $this->db->query("UPDATE ps_product SET image = '". $this->db->escape($edit_image) ."' WHERE product_id = '". (int)$product['product_id'] ."' ");

            $product_images = $this->db->query("SELECT * FROM ps_product_image WHERE product_id = '". (int)$product['product_id'] ."' ")->rows;

            foreach ($product_images as $product_image){
                $edit_image2 = str_replace($search, $replace, $product_image['image']);

                $this->db->query("UPDATE ps_product_image SET image = '". $this->db->escape($edit_image2) ."' WHERE product_image_id = '". (int)$product_image['product_image_id'] ."' ");

            }


        }

        echo $search . '<br>';
        echo "Bitti";


    }

    public function getByExprexxCargoIngo()
    {

        //https://www.deercase.com/index.php?route=tool/functions/getByExprexxCargoIngo

        die();

        $this->getCargoInfo(241626);



    }

    public function infinityBarcodeFind()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/infinityBarcodeFind

        $results = $this->db->query("SELECT barcode FROM `ps_product_stock`")->rows;

        $barcodes = array();

        foreach ($results as $result){
            $ask_barcode = $this->db->query("SELECT barcode FROM `ps_product_stock` WHERE barcode = '". $this->db->escape($result['barcode']) ."'");
            if($ask_barcode->num_rows > 1){
                $barcodes[] = $ask_barcode->row;
            }
        }

        foreach ($barcodes as $barcode){
            echo $barcode['barcode'] . '<br>';
        }


    }

    public function productLoadTest()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/productLoadTest

        echo "Product Load Test" . '<br>';

        //$products = $this->db->query("SELECT * FROM ps_product p LEFT JOIN ps_product_description pd ON (p.product_id = pd.product_id) WHERE pd.language_id = '1' LIMIT 0,100")->rows;
        $products = $this->db->query("SELECT * FROM ps_product p LEFT JOIN ps_product_description pd ON (p.product_id = pd.product_id) WHERE pd.language_id = '1' AND pd.name LIKE '%iPhone 12 Glossy Bellatrix Telefon Kılıfı%' LIMIT 0,100")->rows;

        var_dump($products); die();

    }

    public function findChangeOrders()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/findChangeOrders

        $orders = $this->db->query("SELECT * FROM ps_order o LEFT JOIN ps_order_history oh ON (o.order_id = oh.order_id) 
        WHERE o.order_status_id IN (7,3,23) AND o.date_added > '2021-08-15 00:00:00'  ")->rows;

    }

    public function genarateCouponCode()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/genarateCouponCode

        $length = 8;

        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);

        $codes = array();

        for ($x = 1; $x<= 7500; $x++){
            $randomString = '';
            for ($i = 0; $i < $length; $i++) {
                $randomString .= $characters[rand(0, $charactersLength - 1)];
            }
            $codes[] = $randomString;
        }

        $exist_count = 0;
        $notexist_count = 0;
        foreach ($codes as $item){

            $coupon_find = $this->db->query("SELECT * FROM ps_coupon WHERE code = '". $this->db->escape($item) ."'  ")->row;

            if($coupon_find){
                $exist_count++;
                echo $coupon_find['code'] . '<br>';
            }else{
                $notexist_count++;
                $this->db->query("INSERT INTO ps_coupon SET name = 'ALLIANZ', `code` = '". $this->db->escape($item) ."', type = 'P', discount = '15.00', date_start = '2021-10-13', date_end = '2022-10-13', uses_total = 1, uses_customer = 1, return_coupon = 0, date_added = NOW(), status = 1 ");

            }

        }

        echo $exist_count . " Kupon mevcut. <br>";
        echo $notexist_count . " Kupon mevcut değil. <br>";




    }

    public function getInterlinkCpuponCodes()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/getInterlinkCpuponCodes

        $codes = $this->db->query("SELECT code FROM ps_coupon WHERE name = 'ALLIANZ' ")->rows;

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $objPHPExcel = new PHPExcel();

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Coupon Name');

        $file_name = "Allianz-coupons.xls";

        $row_i = 2;

        foreach ($codes as $code) {

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $row_i, $code['code']);
            $row_i++;
        }


        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        $objPHPExcel->setActiveSheetIndex(0);


        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

        exit;
        
    }

    public function findCategoryIds()
    {

        //die();
        //https://www.deercase.com/index.php?route=tool/functions/findCategoryIds
        $products = $this->db->query("SELECT product_id FROM ps_product_to_category WHERE category_id IN (7339, 7340,7341)")->rows;

        $ids = '';
        foreach ($products as $product){
            $ids .= $product['product_id'] . ', ';
        }

        var_dump($ids);

    }

    public function orderCampaignChange()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/orderCampaignChange
        $orders = $this->db->query("SELECT order_id FROM ps_order WHERE date_added BETWEEN '2021-08-18 00:00:00' AND '2021-10-14 19:00:00' ")->rows;

        //var_dump($orders); die();
        foreach ($orders as $order){
            $this->db->query("UPDATE ps_order SET campaign = '3al2ode' WHERE order_id = '". $order['order_id'] ."' ");
        }


    }

    public function delAttributes()
    {


        die();

        //https://www.deercase.com/index.php?route=tool/functions/delAttributes

        $products = $this->db->query("SELECT product_id FROM `ps_product` WHERE `model` LIKE '%bnd%' ORDER BY `product_id` DESC")->rows;
        //var_dump($products); die();
        foreach ($products as $product){

            $find_attribute = $this->db->query("SELECT * FROM ps_product_attribute pa LEFT JOIN ps_attribute a ON (pa.attribute_id = a.attribute_id) 
            WHERE pa.product_id = '". $product['product_id'] ."' AND a.attribute_group_id = 11 ")->row;
            //var_dump($find_attribute); die();
            if($find_attribute){
                $this->db->query("DELETE FROM ps_product_attribute WHERE product_id = '". $find_attribute['product_id'] ."' AND attribute_id = '". $find_attribute['attribute_id'] ."' ");
            }


        }

    }

    public function burakSuReport()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/functions/burakSuReport

        //Ürünlerin koleksiyon ve renk attribute satış adetleri
        // iPhone 12 Renkli Slicon - 3 Adet

        $orders = '283761,283762,283767,283769,283771,283774,283775,283777,283780,283781,283782,283783,283784,283786,283789,283790,283792,283793,283794,283795,283799,283802,283804,283805,283806,283807,283808,283809,283812,283813,283817,283824,283825,283827,283828,283830,283831,283838,283840,283842,283845,283846,283847,283848,283849,283851,283857,283858,283861,283864,283865,283866,283868,283869,283870,283871,283872,283874,283875,283876,283879,283881,283883,283885,283887,283888,283889,283892,283897,283899,283901,283902,283903,283904,283909,283915,283918,283920,283921,283922,283925,283926,283927,283928,283929,283930,283931,283935,283936,283942,283945,283946,283949,283953,283955,283958,283959,283962,283963,283965,283967,283968,283969,283971,283972,283973,283974,283976,283977,283979,283980,283982,283983,283988,283990,283993,283995,283996,283997,284001,284002,284003,284004,284005,284006,284008,284009,284011,284013,284015,284020,284021,284022,284024,284025,284026,284028,284032,284033,284037,284042,284044,284045,284046,284050,284051,284053,284054,284055,284056,284057,284062,284063,284064,284065,284066,284069,284071,284073,284074,284075,284080,284081,284083,284084,284086,284087,284088,284089,284090,284092,284093,284097,284103,284104,284105,284106,284107,284110,284111,284116,284124,284125,284127,284128,284129,284130,284131,284138,284140,284141,284143,284144,284147,284148,284150,284152,284153,284154,284155,284157,284163,284164,284165,284166,284167,284170,284172,284177,284180,284181,284183,284187,284193,284195,284196,284198,284204,284207,284208,284210,284211,284214,284216,284217,284218,284219,284220,284221,284222,284223,284224,284226,284229,284231,284232,284233,284234,284235,284236,284237,284238,284240,284242,284243,284244,284245,284246,284249,284251,284254,284259,284264,284269,284272,284274,284275,284277';

        //echo  "SELECT order_id FROM ps_order WHERE order_id IN (". $orders .") ";
        $orders = $this->db->query("SELECT order_id FROM ps_order o LEFT JOIN ps_order_product op ON (o.order_id = op.order_id) WHERE order_id IN (". $orders .") ")->rows;

        var_dump($orders); die();


    }

    public function findCouponUsed()
    {


        die();
        //https://www.deercase.com/index.php?route=tool/functions/findCouponUsed

        $id = '286402,286412,286419,286434,286438,286457,286468,286488,286512,286520,286520,286676,286741,286748,286756,286765,286767';

        $orders = $this->db->query("SELECT order_id FROM ps_order WHERE order_id IN (". $id .") ")->rows;

        foreach ($orders as $order){
            //$order_total = $this->db->query("SELECT * FROM ps_order_total WHERE order_id = '". $order['order_id'] ."' AND title LIKE '".  ."' ")->row;
            $order_total = $this->db->query("SELECT * FROM ps_order_total WHERE order_id = '". $order['order_id'] ."' AND code = 'coupon' ")->row;
            if($order_total){
                $coupon = explode('(', $order_total['title']);
                $coupon = rtrim($coupon[1], ')');
                $find_order_coupon = $this->db->query("SELECT * FROM ps_order_total WHERE title LIKE '%". $coupon ."%'  ");
                if($find_order_coupon->num_rows > 1){
                    var_dump($coupon);
                }
            }
        }


    }

    public function bunnyCDNUpload()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/bunnyCDNUpload

        $ftp_server = "storage.bunnycdn.com";
        $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
        $login = ftp_login($ftp_conn, 's6deercase', '25e69c27-fed1-442b-a8ccca402cd2-7562-4589');

        ftp_pasv($ftp_conn, true);

        $file_path =  DIR_IMAGE . 'upload/';

        if ($handle = opendir(DIR_IMAGE . 'upload')) {
            while (false !== ($entry = readdir($handle))) {
                if ($entry != "." && $entry != "..") {
                    // upload file
                    if (ftp_put($ftp_conn, $entry, $file_path . $entry, FTP_ASCII)) {
                        echo "Successfully uploaded $entry. <br>";
                        flush();
                    } else {
                        echo "Error uploading $entry.";
                        flush();
                    }
                }
            }
            closedir($handle);
        }

        // close connection
        ftp_close($ftp_conn);

        //1635552951.jpeg

        die();

        include 'bunnycdn-storage.php';



        $bunnyCDNStorage = new BunnyCDNStorage("dcstorage", "5112d947-9c8d-4fed-9aca-126cd519b2e4", "");


        $result = $bunnyCDNStorage->uploadFile($file, "/dcstorage/s7deercase/1635554761.jpg");

        var_dump($result);


        die();




        $url = "https://storage.bunnycdn.com/dcstorage/s6deercase/fff.png";

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_PUT, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        $headers = array(
            "Content-Type: application/x-www-form-urlencoded",
            'AccessKey' => '892051d9-72af-4054-8760-239ac078606d942dbcd3-8e8c-48ae-9f91-caad8d32f71a',
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        $data = "PUT request data";

        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $resp = curl_exec($curl);
        curl_close($curl);
        var_dump($resp);




    }

    public function burakSqlCahnges()
    {
       die();
        //https://www.deercase.com/index.php?route=tool/functions/burakSqlCahnges
        

        $products = $this->db->query("SELECT p.product_id, pa.attribute_id FROM ps_product p 
        LEFT JOIN ps_product_attribute pa ON (p.product_id = pa.product_id) 
        WHERE p.image LIKE '%GLOSSY_CP%' AND pa.attribute_id = 1156 ")->rows;

        var_dump($products); die();

        foreach($products as $product){
            //var_dump($product); die();
            $this->db->query("DELETE FROM ps_product_attribute WHERE product_id = '". (int)$product['product_id'] ."' AND attribute_id = '". (int)$product['attribute_id'] ."' ");
            $this->db->query("INSERT INTO ps_product_attribute SET 
            product_id = '". (int)$product['product_id'] ."',
            attribute_id = 1156,
            language_id = 1,
            text = ''
             "); 
        }





    }

    public function addOptionSomeProducts(){

        die();

        //https://www.deercase.com/index.php?route=tool/functions/addOptionSomeProducts

        //$products = $this->db->query("SELECT product_id FROM ps_product WHERE model LIKE '%WBWT%' OR model LIKE '%WTCH%' ")->rows;
        $products = $this->db->query("SELECT product_id FROM ps_product WHERE product_id  BETWEEN '2083804' AND '2084023' ")->rows;

        //echo count($products); die();
        foreach($products as $product){

            $this->db->query("INSERT INTO ps_product_option SET product_id = '" . (int)$product['product_id'] . "', option_id = '19', required = '1' ");

            $product_option_id = $this->db->getLastId();

            $product_option_values = [28, 29]; 

                foreach ($product_option_values as $product_option_value) {
                    $this->db->query("INSERT INTO ps_product_option_value SET 
                    product_option_id = '" . (int)$product_option_id . "', 
                    product_id = '" . (int)$product['product_id'] . "', 
                    option_id = '19', 
                    customer_group_id = '1',
                    option_value_id = '" . (int)$product_option_value . "', 
                    quantity = '100', 
                    subtract = '1', 
                    option_value_barcode = '', 
                    price = '0.0000', 
                    price_prefix = '+', 
                    points = '0', 
                    points_prefix = '+', 
                    weight = '0.0000', 
                    weight_prefix = '+' ");
                }

                //var_dump($product); die();


        }

    }

    public function ordersEditTotal(){

        die();
        //https://www.deercase.com/index.php?route=tool/functions/ordersEditTotal

        $orders = $this->db->query("SELECT o.order_id, ot.title, ot.value, o.total FROM ps_order o LEFT JOIN ps_order_total ot ON (o.order_id = ot.order_id)
        WHERE o.date_added > '2022-03-27 18:00:00' AND ot.code = 'total' AND o.order_status_id > 0 AND o.total != ot.value ")->rows;

        echo "Total Count: " . count($orders) . "<br>";
        foreach($orders as $order){
            echo $order['order_id'] . ' => ' . $order['title'] . ' - ' . $order['value'] . ' ---- ' . $order['total'] . '<br>';

           // $this->db->query("UPDATE ps_order SET total = '". $order['value'] ."' WHERE order_id = '". (int)$order['order_id'] ."' ");

           // die();

        }

    }

    public function iyzicoLogs()
    {
        //https://www.deercase.com/index.php?route=tool/functions/iyzicoLogs&order_id=371725

        $order_id = $this->request->get['order_id'];

        //NEbim Logs
        $file_request = DIR_LOGS . 'iyzico/' . $order_id .'_IyzicoErrorPostDataLogs.txt';
        echo $file_request . '<br>';
        
        if (file_exists($file_request)) {
            $file_content = '';
            $myfile = fopen($file_request, "r");
            $file_content = fread($myfile,filesize($file_request));
            fclose($myfile);
            echo '<pre>' . $file_content . '</pre>';
        }else{
            echo "File not Found!";
        }

        
    }

    public function deleteProduct()
    {
        # code...
    }

    public function getProductJson()
    {

        die();
        //https://www.deercase.com/index.php?route=tool/functions/getProductJson

        $product = $this->db->query("SELECT * FROM ps_product WHERE status = 1 LIMIT 1 ")->row;

        echo "<pre>" . var_dump($product) . "</pre>"; die();

        $json = '{
            "productId": '. $product['product_id'] .',
            "productStockId": '. $product['product_stock_id'] .',
            "model": "'.$product['model'].'",
            "model2": "'.$product['model2'].'",
            "slug": "'.$product['model2'].'",
        }';

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

       


    }

    public function iyzicoCallbackLog()
    {
        //die();
        //https://www.deercase.com/index.php?route=tool/functions/iyzicoCallbackLog&order_id=401080
  

        $order_id = $this->request->get['order_id'];

        $filename = DIR_LOGS . 'iyzico/' . $order_id . '_IyzicoCallbackPostDataLogs.txt';
        $fp = fopen($filename, "r");//open file in read mode    
        
        $contents = fread($fp, filesize($filename));//read file    
        
        echo "<pre>$contents</pre>";//printing data of file  
        fclose($fp);//close file     
 

    }

    public function infinityListExportExcel()
    {

        // die();

        //https://www.deercase.com/index.php?route=tool/functions/infinityListExportExcel

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $objPHPExcel = new PHPExcel();

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Barcode')
            ->setCellValue('B1', 'İsim')
            ->setCellValue('C1', 'Kategori')
            ->setCellValue('D1', 'Koleksiyon')
            ->setCellValue('E1', 'Renk')
            ->setCellValue('F1', 'Fiyat')
            ->setCellValue('G1', 'Maliyet Fiyat')
            ->setCellValue('H1', 'Kritik Stok')
            ->setCellValue('J1', 'Stok Adedi')
            ->setCellValue('K1', 'Boş');



        $products = $this->db->query("SELECT* FROM ps_product_stock ORDER BY name ASC  ")->rows;



        $file_name = $this->config->get('config_name') . '-' . @date("Y-m-d-His") . "-InfinityStockList.xls";

        $row_i = 2;


        foreach ($products as $product) {
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $row_i, $product['barcode'])
                    ->setCellValue('B' . $row_i, $product['name'])
                    ->setCellValue('C' . $row_i, $product['category_name'])
                    ->setCellValue('D' . $row_i, $product['collection_name'])
                    ->setCellValue('E' . $row_i, $product['color_name'])
                    ->setCellValue('F' . $row_i, $product['price'])
                    ->setCellValue('G' . $row_i, $product['price_cost'])
                    ->setCellValue('H' . $row_i, $product['kquantity'])
                    ->setCellValue('J' . $row_i, $product['quantity']);
                $row_i++;
        }


        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        $objPHPExcel->setActiveSheetIndex(0);


        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

        exit;

    }


   


}