<?php

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

    public function __construct($registry)
    {

        parent::__construct($registry);
        $this->load->model('entegrasyon/general');
        $this->load->model('entegrasyon/product');

        $this->token_data = $this->model_entegrasyon_general->getToken();
        $this->marketplaces = $this->model_entegrasyon_general->getActiveMarkets();

    }


    public function index()
    {

        // print_r($this->uconfig);

        $this->load->language('entegrasyon/product');
        $this->document->setTitle($this->language->get('heading_title'));
        $this->load->model('entegrasyon/product');
        $this->load->model('catalog/product');
        $this->getList();
    }


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

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

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

        if (isset($this->request->post['selected'])) {
            foreach ($this->request->post['selected'] as $product_id) {
                $this->model_entegrasyon_product->deleteProduct($product_id);
            }

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

            $url = '';

            if (isset($this->request->get['filter_model'])) {
                $url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
            }

            if (isset($this->request->get['filter_name'])) {
                $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
            }


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

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

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


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

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

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

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

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

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

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

            $this->response->redirect($this->url->link('entegrasyon/product', $this->token_data['token_link'] . $url, true));
        }

        $this->getList();
    }


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

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

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

        if (($this->request->server['REQUEST_METHOD'] == 'POST')) {


            $this->model_entegrasyon_product->addProduct($this->request->post);

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

            $url = '';

            if (isset($this->request->get['filter_name'])) {
                $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
            }

            if (isset($this->request->get['filter_model'])) {
                $url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
            }

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

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

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

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

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

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

            $this->response->redirect($this->url->link('entegrasyon/product', 'user_token=' . $this->session->data['user_token'] . $url, true));
        }

        $this->getForm();
    }

    public function edit()
    {
        $this->load->language('entegrasyon/product');
        $this->document->setTitle($this->language->get('heading_title'));
        //$this->load->model('catalog/product');
        $this->load->model('entegrasyon/product');
        $this->load->model('catalog/product');


        if (($this->request->server['REQUEST_METHOD'] == 'POST')) {


            $this->model_entegrasyon_product->editProduct($this->request->get['product_id'], $this->request->post);
            $this->session->data['success'] = $this->language->get('text_success');
            $url = '';

            if (isset($this->request->get['filter_name'])) {
                $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
            }

            if (isset($this->request->get['filter_model'])) {
                $url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
            }

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

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

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

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

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

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

            $this->response->redirect($this->url->link('entegrasyon/product', 'user_token=' . $this->session->data['user_token'] . $url, true));
        }

        $this->getForm();
    }

    protected function getForm()
    {


        $this->document->addScript('view/javascript/jquery/image-uploader.min.js');
        // $this->document->addScript('');
        $this->document->addStyle('view/javascript/jquery/image-uploader.min.css');

        $this->load->model('entegrasyon/general');
        $this->load->model('tool/image');
        $this->model_entegrasyon_general->loadPageRequired();
        $data['text_form'] = !isset($this->request->get['product_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');

        if (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
        } else {
            $data['error_warning'] = '';
        }

        if (isset($this->error['name'])) {
            $data['error_name'] = $this->error['name'];
        } else {
            $data['error_name'] = array();
        }

        if (isset($this->error['meta_title'])) {
            $data['error_meta_title'] = $this->error['meta_title'];
        } else {
            $data['error_meta_title'] = array();
        }

        if (isset($this->error['model'])) {
            $data['error_model'] = $this->error['model'];
        } else {
            $data['error_model'] = '';
        }

        if (isset($this->error['barcode'])) {
            $data['error_barcode'] = $this->error['barcode'];
        } else {
            $data['error_barcode'] = '';
        }

        $url = '';

        if (isset($this->request->get['filter_name'])) {
            $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_model'])) {
            $url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
        }

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

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

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

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

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

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

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

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

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('entegrasyon/product', 'user_token=' . $this->session->data['user_token'] . $url, true)
        );

        if (!isset($this->request->get['product_id'])) {
            $data['action'] = $this->url->link('entegrasyon/product/add', 'user_token=' . $this->session->data['user_token'] . $url, true);
        } else {
            $data['action'] = $this->url->link('entegrasyon/product/edit', 'user_token=' . $this->session->data['user_token'] . '&product_id=' . $this->request->get['product_id'] . $url, true);
        }


        $data['cancel'] = $this->url->link('entegrasyon/product', 'user_token=' . $this->session->data['user_token'] . $url, true);

        if (isset($this->request->get['product_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            $product_info = $this->model_catalog_product->getProduct($this->request->get['product_id']);
            $data['product_id']=$this->request->get['product_id'];
        }

        $data['user_token'] = $this->session->data['user_token'];

        $this->load->model('localisation/language');

        $data['languages'] = $this->model_localisation_language->getLanguages();

        if (isset($this->request->post['product_description'])) {
            $data['product_description'] = $this->request->post['product_description'];
        } elseif (isset($this->request->get['product_id'])) {
            $data['product_description'] = $this->model_catalog_product->getProductDescriptions($this->request->get['product_id']);
        } else {
            $data['product_description'] = array();
        }

        if (isset($this->request->post['model'])) {
            $data['model'] = $this->request->post['model'];
        } elseif (!empty($product_info)) {
            $data['model'] = $product_info['model'];
        } else {
            $data['model'] = '';
        }

        if (isset($this->request->post['barcode'])) {
            $data['barcode'] = $this->request->post['barcode'];
        } elseif (!empty($product_info)) {
            $data['barcode'] = $product_info['barcode'];
        } else {
            $data['barcode'] = '';
        }

        if (isset($this->request->post['stock_code'])) {
            $data['stock_code'] = $this->request->post['stock_code'];
        } elseif (!empty($product_info)) {
            $data['stock_code'] = $product_info['stock_code'];
        } else {
            $data['stock_code'] = '';
        }


        if (isset($this->request->post['shipping'])) {
            $data['shipping'] = $this->request->post['shipping'];
        } elseif (!empty($product_info)) {
            $data['shipping'] = $product_info['shipping'];
        } else {
            $data['shipping'] = 1;
        }

        if (isset($this->request->post['list_price'])) {
            $data['list_price'] = $this->request->post['list_price'];
        } elseif (!empty($product_info)) {
            $data['list_price'] = $product_info['list_price'];
        } else {
            $data['list_price'] = '';
        }

        if (isset($this->request->post['sale_price'])) {
            $data['sale_price'] = $this->request->post['sale_price'];
        } elseif (!empty($product_info)) {
            $data['sale_price'] = $product_info['sale_price'];
        } else {
            $data['sale_price'] = '';
        }
        if (isset($this->request->post['tax'])) {
            $data['tax'] = $this->request->post['tax'];
        } elseif (!empty($product_info)) {
            $data['tax'] = $product_info['tax'];
        } else {
            $data['tax'] = '';
        }


        if (isset($this->request->post['quantity'])) {
            $data['quantity'] = $this->request->post['quantity'];
        } elseif (!empty($product_info)) {
            $data['quantity'] = $product_info['quantity'];
        } else {
            $data['quantity'] = 1;
        }


        if (isset($this->request->post['sort_order'])) {
            $data['sort_order'] = $this->request->post['sort_order'];
        } elseif (!empty($product_info)) {
            $data['sort_order'] = $product_info['sort_order'];
        } else {
            $data['sort_order'] = 1;
        }


        if (isset($this->request->post['status'])) {
            $data['status'] = $this->request->post['status'];
        } elseif (!empty($product_info)) {
            $data['status'] = $product_info['status'];
        } else {
            $data['status'] = true;
        }

        if (isset($this->request->post['desi'])) {
            $data['desi'] = $this->request->post['desi'];
        } elseif (!empty($product_info)) {
            $data['desi'] = $product_info['desi'];
        } else {
            $data['desi'] = '';
        }


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

        $data['no_image'] = $this->model_tool_image->resize2('no_image.png', 100, 100);

        if (isset($this->request->get['product_id'])) {
            $this->load->model("entegrasyon/product/variant");
            $product_variants = $this->model_entegrasyon_product_variant->getProductVariants($this->request->get['product_id']);

            foreach ($product_variants as $product_variant) {



                $data['product_variants'][] = array(

                    'variant_id' => $product_variant['product_variant_id'],
                    'imagesrc' => $product_variant['image'],
                    'image' => $product_variant['image_root'],
                    'barcode' => $product_variant['barcode'],
                    'stock_code' => $product_variant['stock_code'],
                    'quantity' => $product_variant['quantity'],
                    'sale_price' => $product_variant['sale_price'],
                    'variant_values' => $product_variant['variant_values']

                );


            }
        }



        if (isset($this->request->post['manufacturer_id'])) {
            $data['manufacturer_id'] = $this->request->post['manufacturer_id'];
        } elseif (!empty($product_info)) {
            $data['manufacturer_id'] = $product_info['manufacturer_id'];
        } else {
            $data['manufacturer_id'] = 0;
        }

        if (isset($this->request->post['manufacturer'])) {
            $data['manufacturer'] = $this->request->post['manufacturer'];
        } elseif (!empty($product_info)) {

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


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

        if (isset($this->request->post['category_id'])) {
            $data['category_id'] = $this->request->post['category_id'];
        } elseif (!empty($product_info)) {
            $data['category_id'] = $product_info['category_id'];
        } else {
            $data['category_id'] = 0;
        }


        if (isset($this->request->post['category'])) {
            $data['category'] = $this->request->post['category'];
        } elseif (!empty($product_info)) {

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

        $this->load->model('tool/image');
        $data['product_images'] = array();

        // Images
        if (isset($this->request->post['product_image'])) {
            $product_images = $this->request->post['product_image'];
        } elseif (isset($this->request->get['product_id'])) {
            $product_images = $this->model_catalog_product->getProductImages($this->request->get['product_id']);
        } else {
            $product_images = array();
        }


        foreach ($product_images as $sort_order => $product_image) {
            $data['product_images'][] = array(
                'src' => $this->model_tool_image->resize($product_image['image'], 200, 200),
                'id' => $product_image['image'],
            );
        }


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

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


    public function upload_image()
    {

        $this->load->model('tool/image');
        $user_path = $this->user->getUserName();
        /* if(!file_exists(DIR_IMAGE.$user_path;)){
             mkdir(DIR_IMAGE.$user_path;, 0777, true);
         }*/
        $src = $_FILES['file']['tmp_name'];
        //$image_name=$this->model_tool_image->create_image_name($user_path.'/'.$_FILES['file']['name']);
        //$targ = DIR_IMAGE.$user_path.'/'.$image_name;


        $local_upload_file_path = $src;
        $storage_zone_path = BUNNY_STORAGE. $user_path;
        $storage_zone_file_path = $_FILES['file']['name'];//$image_name;
        $res = $this->image->Storage()->PutFile($local_upload_file_path, $storage_zone_path, $storage_zone_file_path);
        if (isset($this->request->get['width'])) {
            $width = $this->request->get['width'];
        } else {
            $width = 250;

        }

        if ($res['status']) {

            $url = BUNNY_DOMAIN . $user_path . $res['cdn_file_path'];
            echo json_encode(array('id' => $user_path . $res['cdn_file_path'], 'src' => $url . '?width=' . $width));

        }


    }


    protected function getList()
    {
        $data = $this->language->all();
        $this->document->addScript('https://cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.min.js');

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

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

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

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

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

        if (isset($this->request->get['filter_stock_prefix'])) {
            $filter_stock_prefix = html_entity_decode($this->request->get['filter_stock_prefix']);
        } else {
            $filter_stock_prefix = "";
        }


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


        /* if($filter_stock_prefix!="*" && !$filter_stock){

             $filter_stock=0;
         }*/

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

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


        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'pd.name';
        }

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

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


        $this->document->addStyle('view/stylesheet/entegrasyon/bootstrap4.css');


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

        $filter_data = array(
            'filter_category' => $filter_category,
            'filter_manufacturer' => $filter_manufacturer,
            'filter_marketplace' => $filter_marketplace,
            'filter_marketplace_do' => $filter_marketplace_do,
            'filter_name' => $filter_name,
            'filter_model' => $filter_model,
            'filter_status' => $filter_status,
            'filter_stock_prefix' => $filter_stock_prefix,
            'filter_stock' => $filter_stock,
            'sort' => $sort,
            'order' => $order,
            'start' => ($page - 1) * $this->uconfig->get('config_limit_admin'),
            'limit' => $this->uconfig->get('config_limit_admin')
        );


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

        $product_total = $this->model_entegrasyon_product->getTotalProducts($filter_data);
        $this->load->model('entegrasyon/category');

        $results = $this->model_entegrasyon_product->getProducts($filter_data);

        if (($filter_model || !$filter_status == "*" || $filter_name || $filter_marketplace || $filter_stock_prefix || $filter_stock || $filter_category || $filter_manufacturer) && (!$filter_model == "*" || !$filter_name == "*" || !$filter_marketplace == "*" || !$filter_stock_prefix == "*" || !$filter_stock == "*" || !$filter_category == "*" || !$filter_manufacturer == "*")) {
            $filter_products_id_for_bulk_action = $this->model_entegrasyon_product->getProducts($filter_data, 'for_bulk');

            $data['products_ids'] = array();
            foreach ($filter_products_id_for_bulk_action as $item) {

                $data['products_ids'][] = array(
                    'product_id' => $item['product_id']
                );

            }

        }
        $url = '';

        if (isset($this->request->get['filter_model'])) {
            $url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_name'])) {
            $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
        }


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

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

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

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

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


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

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

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

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


        foreach ($results as $result) {


            if ($result['image']) {
                $image = $this->model_tool_image->resize($result['image'], 40, 40);

                $class = "";
            } else {

                $query = $this->udb->query("select * from temp_image where product_id='" . $result['product_id'] . "' and sort_order=0");

                $image = $query->row['url'];
                $class = "small-image";
                // $image = $this->model_tool_image->resize('no_image.png', 100, 100);

            }


            // $category_info = $this->model_entegrasyon_category->getCategory();

           // $has_variant_query = $this->udb->query("select product_variant_id from product_variant where product_id='" . $result['product_id'] . "'");

            $matching_words = explode(' ', $result['name'], 3);
            array_pop($matching_words);

            $data['products'][] = array(
                'product_id' => $result['product_id'],
                'matching_words' => implode(',', $matching_words),
                'class' => $class,
                'image' => $image,
                'has_variant' => $result['varianter'],
                'n11' => json_decode($result['n11'], 1),
                'gg' => json_decode($result['gg'], 1),
                'hb' => json_decode($result['hb'], 1),
                'ty' => json_decode($result['ty'], 1),
                'eptt' => json_decode($result['eptt'], 1),
                'amz' => json_decode($result['amz'], 1),
                'cs' => json_decode($result['cs'], 1),
                'total_options' => array(),
                'name' => $result['name'],
                'manufacturer' => $result['manufacturer_name'],
                'category' => $result['category_name'],
                'manufacturer_id' => $result['manufacturer_id'],
                'model' => $result['model'],
                'sale_price' => $result['sale_price'],
                'list_price' => $result['list_price'],
                'quantity' => $result['quantity'],
                'status' => $result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled'),
                'edit' => $this->url->link('entegrasyon/product/edit', 'user_token=' . $this->session->data['user_token'] . '&product_id=' . $result['product_id'] . $url, true)

            );
        }


        $this->load->model('entegrasyon/general');
        $data['edit_button_status'] = false;

        $marketplaces = $this->model_entegrasyon_general->getMarketPlaces();


        foreach ($marketplaces as $marketplace) {

            if ($marketplace['status']) {
                $filter_data[$marketplace['code']] = true;
                $data['edit_button_status'] = true;
            }

        }
        $data['marketplaces'] = $marketplaces;

        $data['token'] = $this->token_data['token_link'];

        if (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
        } else {
            $data['error_warning'] = '';
        }

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

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


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

        $url = '';


        $data['delete'] = $this->url->link('entegrasyon/product/delete', $this->token_data['token_link'] . $url, true);
        $data['add'] = $this->url->link('entegrasyon/product/add', 'user_token=' . $this->session->data['user_token'] . $url, true);
        $data['copy'] = $this->url->link('entegrasyon/product/copy', 'user_token=' . $this->session->data['user_token'] . $url, true);
        $data['delete'] = $this->url->link('entegrasyon/product/delete', 'user_token=' . $this->session->data['user_token'] . $url, true);

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

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

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('entegrasyon/product', $this->token_data['token_link'] . $url, true)
        );

        if ($filter_manufacturer) {
            $this->load->model('catalog/manufacturer');
            $manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($filter_manufacturer);
            $data['filter_manufacturer_name'] = $manufacturer_info['name'];

        } else {

            $data['filter_manufacturer_name'] = '';

        }

        if ($filter_category) {
            $this->load->model('catalog/category');
            $category_info = $this->model_catalog_category->getCategory($filter_category);
            $data['filter_category_name'] = $category_info['name'];
        } else {

            $data['filter_category_name'] = '';

        }

        $data['list_limit'] = $this->uconfig->get('config_limit_admin') + 1;

        $pagination = new Pagination();
        $pagination->total = $product_total;
        $pagination->page = $page;
        $pagination->limit = $this->uconfig->get('config_limit_admin');
        $pagination->url = $this->url->link('entegrasyon/product', $this->token_data['token_link'] . $url . '&page={page}', true);
        $data['pagination'] = $pagination->render();
        $data['results'] = sprintf($this->language->get('text_pagination'), ($product_total) ? (($page - 1) * $this->uconfig->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($product_total - $this->config->get('config_limit_admin'))) ? $product_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $product_total, ceil($product_total / $this->config->get('config_limit_admin')));
        if ($order == 'ASC') {
            $url .= '&order=DESC';
        } else {
            $url .= '&order=ASC';
        }

        $data['sort_name'] = $this->url->link('entegrasyon/product', $this->token_data['token_link'] . '&sort=pd.name' . $url, true);
        $data['sort_price'] = $this->url->link('entegrasyon/product', $this->token_data['token_link'] . '&sort=p.price' . $url, true);
        $data['sort_data_added'] = $this->url->link('entegrasyon/product', $this->token_data['token_link'] . '&sort=p.data_added' . $url, true);
        $data['sort_quantity'] = $this->url->link('entegrasyon/product', $this->token_data['token_link'] . '&sort=p.quantity' . $url, true);
        $data['product_error'] = $this->url->link('entegrasyon/product/error_list', $this->token_data['token_link'], true);


        $data['filter_marketplace'] = $filter_marketplace;
        $data['filter_marketplace_do'] = $filter_marketplace_do;
        $data['filter_model'] = $filter_model;
        $data['filter_name'] = $filter_name;
        $data['filter_manufacturer'] = $filter_manufacturer;
        $data['filter_category'] = $filter_category;
        $data['filter_stock_prefix'] = $filter_stock_prefix;
        $data['filter_stock'] = $filter_stock;
        $data['filter_status'] = $filter_status;

        $this->model_entegrasyon_general->loadPageRequired();
        $data['token_link'] = $this->token_data['token_link'];
        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');
        $this->response->setOutput($this->load->view('entegrasyon/product_list', $data));
    }


    public function unapproved_products()
    {
        $data = $this->language->all();


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


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

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


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

        // $this->document->addStyle('https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css');
        $this->document->addScript('https://cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.min.js');


        $this->document->addStyle('view/stylesheet/entegrasyon/bootstrap4.css');

        $this->document->setTitle('Onay bekleyen ürünler');

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

        $code = 'ty';
        $filter_data = array(
            'code' => $code,
            'filter_name' => $filter_name,
            'filter_model' => $filter_model,
            'start' => ($page - 1) * $this->uconfig->get('config_limit_admin'),
            'limit' => $this->uconfig->get('config_limit_admin')
        );


        $this->load->model('entegrasyon/product');
        $product_total = $this->model_entegrasyon_product->getTotalUnApprovedProducts($filter_data);


        $results = $this->model_entegrasyon_product->getUnApprovedProducts($filter_data);


        $data['product_total'] = $product_total;
        $i = 0;
        foreach ($results as $result) {

            $i++;
            $product_info = json_decode($result[$code]);
            $data['products'][] = array(
                'product_id' => $result['product_id'],
                'model' => $result['model'],
                'error' => $product_info['message'],
                'marketplace' => strlen($code) > 1 ? $this->entegrasyon->marketPlaces[$code] : '',
                'code' => $code,
                'name' => $result['name'],
                'product_data' => json_decode($result[$code]),
                'date_modified' => $result['date_modified']
            );
        }


        $this->load->model('entegrasyon/general');

        $marketplaces = $this->model_entegrasyon_general->getMarketPlaces();
        foreach ($marketplaces as $marketplace) {

            if ($marketplace['status']) {
                $filter_data[$marketplace['code']] = true;
                $data['edit_button_status'] = true;
            }

        }
        $data['marketplaces'] = $marketplaces;

        $data['easy_visibility'] = $this->uconfig->get('easy_visibility') ? '' : 'hidden';

        $data['token'] = $this->token_data['token_link'];

        $url = '';

        if (isset($this->request->get['filter_model'])) {
            $url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_name'])) {
            $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
        }


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


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

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

        $data['breadcrumbs'][] = array(
            'text' => 'Hata Raporları',
            'href' => $this->url->link('entegrasyon/product/error_list', $this->token_data['token_link'], true)
        );


        $pagination = new Pagination();
        $pagination->total = $product_total;
        $pagination->page = $page;
        $pagination->limit = $this->uconfig->get('config_limit_admin');
        $pagination->url = $this->url->link('entegrasyon/product/error_list', $this->token_data['token_link'] . '&page={page}', true);

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

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


        $data['filter_marketplace'] = $filter_marketplace;
        $data['filter_model'] = $filter_model;
        $data['filter_name'] = $filter_name;


        $this->model_entegrasyon_general->loadPageRequired();
        $data['token_link'] = $this->token_data['token_link'];

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


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

    public function check_status()
    {


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

        $product_status = '';
        $message = '';


        $marketplace_data = $this->entegrasyon->getMarketPlaceProductForMarket($product_id, $code);

        $this->load->model('entegrasyon/general');
        $post_data['market'] = $this->model_entegrasyon_general->getMarketPlace($code);
        $debug = false;
        if ($code == 'ty') {

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

            //$debug=true;
            $post_data['request_data'] = array('itemcount' => 1, 'page' => 1, 'barcode' => $product_info['model'], 'approved' => true);


            $result = $this->entegrasyon->clientConnect($post_data, 'get_product', 'ty', $debug);


            if (isset($result['result']['content'][0])) {

                $product = $result['result']['content'][0];
                if ($product['rejected']) {

                    $rejectReason = $product['rejectReasonDetails'][0]['rejectReason'];
                    $rejectReasonDetail = $product['rejectReasonDetails'][0]['rejectReasonDetail'];
                    $product_status = 'Revize Etmeniz Gerekiyor';

                    $marketplace_data['product_status'] = $product_status;
                    $marketplace_data['message'] = $rejectReason . ':' . $rejectReasonDetail;


                } else if ($product['approved']) {

                    $marketplace_data['approval_status'] = 1;

                    //Ürünü Satışa Açık Konumuna getirebiliriz;

                } else {

                    $marketplace_data['approval_status'] = 0;
                    $product_status = 'Satışta olmayanlar';

                    $marketplace_data['product_status'] = $product_status;
                    $marketplace_data['message'] = 'Ürününüz trendyol tarafından kontol aşamasına alınmıştır..';
                }

            } else {

                $this->entegrasyon->deleteMarketplaceProduct($product_id, $code);
                echo json_encode(array('status' => 0, 'message' => 'Ürün Trendyol mağazanızda bulamadı!'));
                return;

            }


        } else if ($code == 'hb') {

            $post_data['request_data'] = $marketplace_data['request_id'];

            $debug = false;
            $result = $this->entegrasyon->clientConnect($post_data, 'check_status', $code, $debug);


            if ($result['status']) {

                if ($result['result']['product_status'] == 'Satışa Hazır') {
                    $marketplace_data['sale_status'] = 1;
                    json_decode($marketplace_data['status']);
                    $marketplace_data['approval_status'] = 1;

                } else {
                    $marketplace_data['approval_status'] = 0;
                    $product_status = $result['result']['product_status'];
                    $marketplace_data['product_status'] = $product_status;
                    $marketplace_data['message'] = implode('-', $result['result']['errors']);

                }


            }


        }

        echo json_encode(array('status' => 1, 'product_status' => $product_status, 'message' => 'Ürün Durumu:' . $marketplace_data['message']));


        $this->entegrasyon->addMarketplaceProduct($product_id, $marketplace_data, $code);


        /*
                if ($result['status']) {

                    if ($result['result']['product_status'] == 'Satışa Hazır') {
                        $marketplace_data['sale_status'] = 1;
                        json_decode($marketplace_data['status']);
                        $marketplace_data['approval_status'] = 1;
                        $this->entegrasyon->addMarketplaceProduct($product_id, $marketplace_data, 'hb');

                    } else {

                        $marketplace_data['status'] = $result['result']['product_status'];
                        $this->entegrasyon->addMarketplaceProduct($product_id, $marketplace_data, 'hb');


                    }

                    $error = '';
                    if ($result['result']['errors']) {
                        $error = implode(',', $result['result']['errors']);
                    }


                    echo json_encode(array('status' => $result['status'], 'product_status' => $result['result']['product_status'], 'message' => 'Ürün Durumu:' . $result['result']['product_status'] . ' ' . $error));


                }
        */

    }


    public function error_list()
    {
        $data = $this->language->all();


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


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

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


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

        // $this->document->addStyle('https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css');
        $this->document->addScript('https://cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.min.js');


        $this->document->addStyle('view/stylesheet/entegrasyon/bootstrap4.css');

        $this->document->setTitle('Ürün Hata Raporları');

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


        $filter_data = array(
            'filter_marketplace' => $filter_marketplace,
            'filter_name' => $filter_name,
            'filter_model' => $filter_model,
            'start' => ($page - 1) * $this->uconfig->get('config_limit_admin'),
            'limit' => $this->uconfig->get('config_limit_admin')
        );

        $this->load->model('entegrasyon/product');
        $product_total = $this->model_entegrasyon_product->getTotalProductErrors($filter_data);
        $results = $this->model_entegrasyon_product->getProductErrors($filter_data);

        $data['product_total'] = $product_total;
        $i = 0;
        foreach ($results as $result) {

            $i++;

            $data['products'][] = array(
                'product_id' => $result['product_id'],
                'model' => $result['model'],
                'name' => $result['name'],
                'code' => $result['code'],
                'marketplace' => strlen($result['code']) > 1 ? $this->entegrasyon->marketPlaces[$result['code']] : '',
                'action' => $result['type'] == 1 ? 'Ürün Ekleme' : 'Güncelleme',
                'auto_action' => $result['type'] == 1 ? 'addproduct' : 'update',
                'error' => $result['error'],
                'btn_id' => $i,
                'date_modified' => $result['date_modified']

            );
        }


        $this->load->model('entegrasyon/general');

        $marketplaces = $this->model_entegrasyon_general->getMarketPlaces();
        foreach ($marketplaces as $marketplace) {

            if ($marketplace['status']) {
                $filter_data[$marketplace['code']] = true;
                $data['edit_button_status'] = true;
            }

        }
        $data['marketplaces'] = $marketplaces;

        $data['easy_visibility'] = $this->uconfig->get('easy_visibility') ? '' : 'hidden';

        $data['token'] = $this->token_data['token_link'];

        $url = '';

        if (isset($this->request->get['filter_model'])) {
            $url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_name'])) {
            $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
        }


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


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

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

        $data['breadcrumbs'][] = array(
            'text' => 'Hata Raporları',
            'href' => $this->url->link('entegrasyon/product/error_list', $this->token_data['token_link'], true)
        );


        $pagination = new Pagination();
        $pagination->total = $product_total;
        $pagination->page = $page;
        $pagination->limit = $this->uconfig->get('config_limit_admin');
        $pagination->url = $this->url->link('entegrasyon/product/error_list', $this->token_data['token_link'] . '&page={page}', true);

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

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


        $data['filter_marketplace'] = $filter_marketplace;
        $data['filter_model'] = $filter_model;
        $data['filter_name'] = $filter_name;


        $this->model_entegrasyon_general->loadPageRequired();
        $data['token_link'] = $this->token_data['token_link'];

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


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


    protected function validateForm()
    {
        if (!$this->user->hasPermission('modify', 'catalog/product')) {
            $this->error['warning'] = $this->language->get('error_permission');
        }

        foreach ($this->request->post['product_description'] as $language_id => $value) {
            if ((utf8_strlen($value['name']) < 1) || (utf8_strlen($value['name']) > 255)) {
                $this->error['name'][$language_id] = $this->language->get('error_name');
            }

            if ((utf8_strlen($value['meta_title']) < 1) || (utf8_strlen($value['meta_title']) > 255)) {
                $this->error['meta_title'][$language_id] = $this->language->get('error_meta_title');
            }
        }

        if ((utf8_strlen($this->request->post['model']) < 1) || (utf8_strlen($this->request->post['model']) > 64)) {
            $this->error['model'] = $this->language->get('error_model');
        }

        /*   if ($this->request->post['product_seo_url']) {
               $this->load->model('design/seo_url');

               foreach ($this->request->post['product_seo_url'] as $store_id => $language) {
                   foreach ($language as $language_id => $keyword) {
                       if (!empty($keyword)) {
                           if (count(array_keys($language, $keyword)) > 1) {
                               $this->error['keyword'][$store_id][$language_id] = $this->language->get('error_unique');
                           }

                           $seo_urls = $this->model_design_seo_url->getSeoUrlsByKeyword($keyword);

                           foreach ($seo_urls as $seo_url) {
                               if (($seo_url['store_id'] == $store_id) && (!isset($this->request->get['product_id']) || (($seo_url['query'] != 'product_id=' . $this->request->get['product_id'])))) {
                                   $this->error['keyword'][$store_id][$language_id] = $this->language->get('error_keyword');

                                   break;
                               }
                           }
                       }
                   }
               }
           } */

        if ($this->error && !isset($this->error['warning'])) {
            $this->error['warning'] = $this->language->get('error_warning');
        }

        return !$this->error;
    }


    public function get_product_row()
    {
        $data = $this->language->all();

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

        $product_id = $this->request->get['product_id'];
        $data['product_id'] = $product_id;
        $data['product'] = $this->entegrasyon->getProduct($product_id);


        if (is_file(DIR_IMAGE . $data['product']['image'])) {
            $data['product']['image'] = $this->model_tool_image->resize($data['product']['image'], 40, 40);
        } else {
            $data['product']['image'] = $this->model_tool_image->resize('no_image.png', 40, 40);
        }

        $data['product']['n11'] = json_decode($data['product']['n11']);
        $data['product']['gg'] = json_decode($data['product']['gg']);
        $data['product']['ty'] = json_decode($data['product']['ty']);
        $data['product']['eptt'] = json_decode($data['product']['eptt']);
        $data['product']['hb'] = json_decode($data['product']['hb']);
        $data['product']['cs'] = json_decode($data['product']['cs']);

        $this->load->model('entegrasyon/general');
        $data['edit_button_status'] = false;

        $marketplaces = $this->model_entegrasyon_general->getMarketPlaces();


        foreach ($marketplaces as $marketplace) {

            if ($marketplace['status']) {
                $filter_data[$marketplace['code']] = true;
                $data['edit_button_status'] = true;
            }

        }

        $data['marketplaces'] = $marketplaces;
        $this->response->setOutput($this->load->view('entegrasyon/product/product_row', $data));

    }


    public function delete_error()
    {

        $product_id = $this->request->post['product_id'];
        $code = $this->request->post['code'];
        $this->entegrasyon->deleteError($product_id, $code);

        echo json_encode(array('status' => true));

    }

    public function setting()
    {

        //$data['header'] = $this->load->controller('common/header');
        //$this->model_entegrasyon_general->loadPageRequired();
        if (isset($this->request->get['category_id'])) {
            $category_id = $this->request->get['category_id'];
        } else {
            $category_id = 0;
        }

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

        $this->load->model('entegrasyon/general');
        $data['product_id'] = $product_id;
        $data['category_id'] = $category_id;
        $data['token_link'] = $this->token_data['token_link'];
        $data['code'] = $this->request->get['code'];


        $data['manufacturer'] = '';


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

    }

    public function product_setting()
    {

        $this->load->model("entegrasyon/general");
        $this->load->model("entegrasyon/product");
        $this->load->model("entegrasyon/market_product");
        $product_id = $this->request->get['product_id'];
        $code = $this->request->get['code'];
        $data = $this->model_entegrasyon_general->getSettingData($code, 'product', $product_id, $code);



        $data['marketplace_data'] = $this->model_entegrasyon_market_product->getMarketPlaceProductForMarket($product_id, $code);

        $data['product_info'] = $this->model_entegrasyon_product->getProduct($product_id, $code);

        $data['category_info'] = $this->udb->query("select * from  multimarket.oc_category c  where c.category_id ='" . $data['product_info']['category_id'] . "' ")->row;


        $data['token_link'] = $this->token_data['token_link'];


        $this->response->setOutput($this->load->view('entegrasyon/product/marketplace/' . $code, $data));
    }


    public function addproduct($product_id = null, $code = null, $bulk = false)
    {


        $product_id = $this->request->get['product_id'];
        $code = $this->request->get['code'];

        $this->load->model("entegrasyon/general");
        $this->load->model("entegrasyon/calculate");


        $this->load->model('entegrasyon/product');
        $this->load->model('entegrasyon/product/marketplace/' . $code);

        $product_info = $this->model_entegrasyon_product->getProduct($product_id, $code);

        $defaults = $this->model_entegrasyon_general->getDefaults($product_info, $code);


        $product_data=array();

        $product_data['category_id'] = $this->db->query("select $code from ".DB_PREFIX."category where category_id='".$product_info['category_id']."' ")->row[$code]; ;
        $product_data['product_id'] = $product_id;

        $product_data['quantity'] = $product_info['quantity'];

        $product_data['list_price'] = $this->model_entegrasyon_calculate->calculatePrice($product_info['list_price'], $defaults, $product_info['tax'], $code);
        $product_data['sale_price'] = $this->model_entegrasyon_calculate->calculatePrice($product_info['sale_price'], $defaults, $product_info['tax'], $code);


        $product_data['barcode'] = $product_info['barcode'];
        $product_data['model'] = $product_info['model'];
        $product_data['stock_code'] = $product_info['stock_code'];
        $product_data['title'] = $product_info['name'];
        $product_data['description'] = $product_info['description'];
        $product_data['desi'] = $product_info['desi'];
        $product_data['tag'] = $product_info['tag'];
        $product_data['manufacturer_id'] = $product_info['manufacturer_id'];
        $product_data['manufacturer_name'] = $product_info['manufacturer_name'];


        $product_data['kdv'] = $product_info['tax'];

        if (isset($product_setting['product_desciption'])) {

            $product_data['description'] = $product_setting['product_desciption'];

        }

        if (isset($product_setting['product_shipping_time'])) {

            $product_data['shipping_time'] = $product_setting['product_shipping_time'];

        }
        if (isset($product_setting['currency'])) {

            $product_data['currency'] = $product_setting['currency'];

        }

        if (isset($product_setting[$code . '_product_title'])) {

            $product_data['title'] = $product_setting['product_title'];

        }



      $this->load->model('entegrasyon/attribute');
        $check_required = $this->model_entegrasyon_attribute->check_required($defaults['selected_attributes'], $product_info, $code);

        if($check_required){

            echo 'Zorunlu ürün seçenekleri var';
            print_r($check_required);
            return;

        }




        if($product_info['varianter']){

            $product_data['variants']=$this->{"model_entegrasyon_product_marketplace_".$code}->getMarketVariants($product_info);

        }

//print_r($defaults['selected_attributes']);return;

        // $attributes = $this->entegrasyon->getSelectedAttributes($code, $product_setting, $category_setting);


        $product_data['images'] = $this->{"model_entegrasyon_product_marketplace_".$code}->getImages($product_info);

        $defaults['selected_attributes'] = $this->model_entegrasyon_attribute->attributes_without_variants($defaults['selected_attributes'],$product_info,$code);



        $product_data['defaults']=$defaults;

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


        $result = $this->{$code}->add_product($product_data, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($code));

        return;


        if (!$result['status']) {

            $error = $this->entegrasyon->getError($product_id, $code);

            if ($error) {

                $this->entegrasyon->updateError($product_id, $code, 1, $result['message']);

            } else {

                $this->entegrasyon->addError($product_id, $code, 1, $result['message']);
            }

        }


        if ($bulk) {
            return $result;
        } else {

            $json = json_encode($result);

            echo $json;
        }


    }


    public function send_to_marketplace()
    {

        $this->load->model("entegrasyon/general");

        if (!$this->model_entegrasyon_general->checkPermission()) {

            echo json_encode(array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda ürün gönderilmesine izin verilmemektedir.'));
            return;

        }

        $list = $this->request->post['list'];


        // $reference = $this->request->post['reference'];
        $product_id = $this->request->get['product_id'];
        $oc_category_id = $this->request->get['category_id'];
        $code = $this->request->get['code'];
        $current_key = array_search($product_id, $list);


        $this->load->model('entegrasyon/category');
        $category_setting = $this->model_entegrasyon_category->getMarketCategory($oc_category_id, $code);

        $message = '';
        $this->load->model('entegrasyon/product/' . $code);

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


        if (!$product_info['model']) {

            $message = 'Ürününüze tanımlı model verisi bulunamadı, model kodu olmayan ürünler listelenemez!';

        }


        ///$category_setting=$this->entegrasyon->getMarketPlaceCategory($product_id,$code);
        $manufacturer_setting = $this->entegrasyon->getMarketPlaceManufacturer($product_info['manufacturer_id'], $code);
        $product_setting = $this->entegrasyon->getSettingData($code, 'product', $product_id);

        if (!isset($product_setting[$code . '_category_id'])) {
            if ($category_setting == 2) {

                $message .= ' Ürününüz hiç bir kategori ile ilişkilendirilmemiş! Önce Ürününüzü bir kategoriye ekleyiniz. ';

            } else {

                if (!isset($category_setting[$code . '_category_id'])) {
                    $message .= 'Kategori Eşletirmesi Yapmalısınız! ';
                }

            }
        }

        // print_r($category_setting[$code . '_category_id']);
        // return;

        $product_data['defaults'] = $this->entegrasyon->getDefaults($category_setting, $manufacturer_setting, $product_setting, $code);

        if ($product_data['defaults']['additional_content']) {

            $information = $this->entegrasyon->getInformationDescriptions($product_data['defaults']['additional_content']);
            $product_info['description'] = $product_info['description'] . $information;

        }


        if ($code == 'ty' || $code == 'hb') {
            if (!$product_info['manufacturer_id']) {
                $message .= ' Ürününüz bir markaya ait olmalıdır!. Katalog->Ürünler bölümünden ürününüze bir marka ekleyin';

            } else if ($code == 'ty') {

                if (!isset($manufacturer_setting['ty_manufacturer_id'])) {
                    $message .= ' Marka Eşleştirmesi yapmalısınız!.';
                } else {

                    $product_data['manufacturer_id'] = $manufacturer_setting['ty_manufacturer_id'];

                }

            }

        }


        if ($message) {


            if ($current_key + 1 < count($list)) {


                echo json_encode(array('status' => false, 'next' => true, 'item' => $list[$current_key + 1], 'list' => $list, 'current' => $current_key + 1, 'message' => $message));


            } else {

                echo json_encode(array('status' => false, 'next' => false, 'item' => $list[$current_key], 'list' => $list, 'current' => $current_key + 1, 'message' => $message));

            }
            return;
        }


        $category_info = isset($product_setting[$code . '_category_id']) ? $product_setting[$code . '_category_id'] : $category_setting[$code . '_category_id'];


        $category_info = explode('|', $category_info);

        $product_data['category_id'] = $category_info[0];
        $product_data['product_setting'] = $product_setting;
        $product_data['category_setting'] = $category_setting;
        $product_data['product_id'] = $product_id;


        if ($this->uconfig->get($code . '_setting_barkod_place')) {

            if ($product_info[$this->uconfig->get($code . '_setting_barkod_place')]) $product_data['product_setting'][$code . '_barcode'] = $product_info[$this->uconfig->get($code . '_setting_barkod_place')];

        }
        if ($this->uconfig->get($code . '_setting_main_product_id')) {
            if ($product_info[$this->uconfig->get($code . '_setting_main_product_id')]) $product_data['product_setting'][$code . '_main_product_id'] = $product_info[$this->uconfig->get($code . '_setting_main_product_id')];
        }

        $product_data['model'] = $this->uconfig->get($code . '_setting_model_prefix') . $product_info['model'];
        $product_data['quantity'] = $product_info['quantity'];
        $product_data['special'] = $product_info['special'];

        if ($this->uconfig->get("easy_setting_price_place") && $product_info[$this->uconfig->get("easy_setting_price_place")]) {

            $product_info['price'] = $product_info[$this->uconfig->get("easy_setting_price_place")];
            $product_info['spacial'] = $product_info[$this->uconfig->get("easy_setting_price_place")];

        }

        $product_data['list_price'] = $this->entegrasyon->calculatePrice($product_info['price'], $product_data['defaults'], $product_info['tax_class_id'], $code, $product_info);
        $product_data['sale_price'] = $product_info['special'] && $product_data['defaults']['product_special'] ? $this->entegrasyon->calculatePrice($product_info['special'], $product_data['defaults'], $product_info['tax_class_id'], $code, $product_info) : $product_data['list_price'];

        $product_data['main_image'] = $product_info['image'];
        $product_data['title'] = $product_info['name'];
        $product_data['description'] = $product_info['description'];
        $product_data['weight'] = $product_info['weight'];
        $product_data['tag'] = $product_info['tag'];


        $product_data['tax_class_id'] = $product_info['tax_class_id'];
        $product_data['kdv'] = $this->entegrasyon->getKdvRange($product_info['tax_class_id']);


        $product_data['attributes'] = array();
        /* if ($reference) {
             $product_setting = $this->entegrasyon->getSettingData($code, 'product', $reference);
         }*/


        $attributes = $this->entegrasyon->getSelectedAttributes($code, $product_setting, $category_setting, true);


        $manufacturer = $this->entegrasyon->getManufacturer($product_info['manufacturer_id']);


        if (isset($manufacturer['name'])) {

            $product_data['manufacturer'] = $manufacturer['name'];

        }


        $need_select = $this->entegrasyon->checkRequiredAttributes($category_info[0], $code, $attributes, $product_id);


        if ($need_select) {

            $message = 'Girmeniz Gereken Zorunlu Özellikler:' . implode('-', $need_select);

            if ($current_key + 1 < count($list)) {


                echo json_encode(array('status' => false, 'next' => true, 'item' => $list[$current_key + 1], 'list' => $list, 'current' => $current_key + 1, 'message' => $message));


            } else {

                echo json_encode(array('status' => false, 'next' => false, 'item' => $list[$current_key], 'list' => $list, 'current' => $current_key + 1, 'message' => $message));

            }
            return;

        }


        if (isset($product_setting[$code . '_product_desciption'])) {

            $product_data['description'] = $product_setting[$code . '_product_desciption'];

        }

        if (isset($product_setting[$code . '_product_title'])) {

            $product_data['title'] = $product_setting[$code . '_product_title'];

        }

        if (isset($product_setting[$code . '_product_shipping_time'])) {

            $product_data['shipping_time'] = $product_setting[$code . '_product_shipping_time'];

        }


        if ((isset($product_setting[$code . '_product_sale_price']) || isset($product_setting[$code . '_product_sale_price']) && !isset($product_setting[$code . '_product_list_price']))) {
            $product_info['have_discount'] = false;
            $product_data['sale_price'] = $product_setting[$code . '_product_sale_price'];
            if (!isset($product_setting[$code . '_product_list_price'])) {
                $product_info['have_discount'] = false;
                $product_data['list_price'] = $product_info['sale_price'];

            }

            $product_data['list_price'] = $product_data['sale_price'];
        }
        if (isset($product_setting[$code . '_product_list_price'])) {
            if ($product_setting[$code . '_product_list_price'] > $product_setting[$code . '_product_sale_price']) {
                $product_info['have_discount'] = true;
            }
            $product_data['list_price'] = $product_setting[$code . '_product_list_price'];
        }

        $product_data['variants'] = array();

        $is_category_varianter = $this->entegrasyon->isCategoryVarianter($category_info[0]);

        if ($this->uconfig->get($code . '_setting_variant')) {

            if ($this->entegrasyon->isVarianterProduct($product_id) && ($is_category_varianter || $code == 'n11')) {
                $product_variants = $this->entegrasyon->getProductVariants($product_id);
                $market_variants = $this->entegrasyon->getMarketVariant($product_variants, $code, $category_info[0], $product_id, $product_data['model'], HTTPS_CATALOG, array('tax_class_id' => $product_info['tax_class_id'], 'defaults' => $product_data['defaults']));

                if ($code == 'ty' || $code == 'gg' || $code == 'cs' || $code == 'hb') {

                    $attributes = $this->entegrasyon->deleteIfInAttbutes($market_variants, $attributes);
                }


                if ($market_variants['status']) {
                    $product_data['variants']['variants']['options'] = $market_variants['variants'];

                } else {

                    $message = $market_variants['message'];

                    if ($current_key + 1 < count($list)) {


                        echo json_encode(array('status' => false, 'next' => true, 'item' => $list[$current_key + 1], 'list' => $list, 'current' => $current_key + 1, 'message' => $message));


                    } else {

                        echo json_encode(array('status' => false, 'next' => false, 'item' => $list[$current_key], 'list' => $list, 'current' => $current_key + 1, 'message' => $message));

                    }
                    return;

                }

                // print_r($market_variants['variants']);
            }

        }

        if ($this->uconfig->get('easy_setting_list_price') && $this->uconfig->get($code . '_setting_product_special')) {

            $product_data['list_price'] = $product_data['sale_price'];
            $product_data['special'] = false;

        }

        $product_data['images'] = $this->entegrasyon->getImagesByMarketPlace($product_id, $product_info['image'], $code, HTTPS_CATALOG);


        $debug = false;
        $product_data['attributes'] = $attributes;


        if (isset($manufacturer_setting[$code . '_manufacturer_id'])) {

            $product_data['manufacturer'] = $manufacturer_setting[$code . '_manufacturer_id'];

        }

        if ($this->uconfig->get('easy_setting_critical_stock')) {
            $product_data['quantity'] = $product_data['quantity'] <= $this->uconfig->get('easy_setting_critical_stock') ? 0 : $product_data['quantity'];
        }

        $result = $this->{"model_entegrasyon_product_" . $code}->sendProduct($product_data, $product_data['attributes'], $debug);


        if (!$result['status']) {

            $error = $this->entegrasyon->getError($product_id, $code);
            if ($error) {
                $this->entegrasyon->updateError($product_id, $code, 1, $result['message']);
            } else {
                $this->entegrasyon->addError($product_id, $code, 1, $result['message']);
            }
        }

        $logmesage = $product_info['model'] . ' Action:Add bulk Product ';;

        $logmesage .= '-Stock - :' . $product_info['quantity'] . ' - Sale Price:' . $product_info['sale_price'] . ' - List Price:' . $product_info['list_price'];

        $logmesage .= '- Result:' . $result['message'];

        $this->entegrasyon->log($code, $logmesage, true);


        if ($current_key + 1 < count($list)) {

            echo json_encode(array('status' => $result['status'], 'next' => true, 'item' => $list[$current_key + 1], 'list' => $list, 'current' => $current_key + 1, 'message' => $result['message']));

        } else {

            echo json_encode(array('status' => $result['status'], 'next' => false, 'item' => $list[$current_key], 'list' => $list, 'current' => $current_key + 1, 'message' => $result['message']));

        }


    }


    public function close_for_sale($product_id = null, $code = null, $bulk = false)
    {


        $this->load->model("entegrasyon/general");
        $this->load->model("entegrasyon/market_product");
        if (!$product_id) {
            $product_id = $this->request->post['product_id'];
        }

        if (!$code) {

            $code = $this->request->post['code'];

        }

        if (!$this->model_entegrasyon_general->checkPermission()) {

            if ($bulk) {
                return array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda ürün işlemlerine izin verilmemektedir.');
            } else {
                echo json_encode(array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda ürün gönderilmesine izin verilmemektedir.'));
            }
            return;
        }


        $product_info = $this->entegrasyon->getProduct($product_id);
        $marketplace_data = $this->model_entegrasyon_market_product->getMarketPlaceProductForMarket($product_id, $code);
        if (!$marketplace_data) {

            if ($bulk) {
                return array('status' => false, 'message' => 'Ürün mağazada bulunamadı, işlem yapabilmek için önce ürünü mağazaya göndermelisiniz.');
            } else {
                echo json_encode(array('status' => false, 'message' => 'Ürün mağazada bulunamadı, işlem yapabilmek için önce ürünü mağazaya göndermelisiniz.'));
            }
            return;

        }

        if ($code == 'hb') {

            $product_data = $this->entegrasyon->getMarketVariants($product_id, $code);

        } else {

            $product_data = $this->entegrasyon->getProductForUpdate($code, $product_info, $marketplace_data['commission'], 0);

        }


        if ($code != 'hb') {
            $post_data['request_data']['product_id'] = isset($marketplace_data['product_id']) ? $marketplace_data['product_id'] : '';
            $post_data['request_data']['model'] = $this->uconfig->get($code . '_setting_model_prefix') . $product_info['model'];
            $post_data['request_data']['quantity'] = $product_data['quantity'];
            $post_data['request_data']['list_price'] = $product_data['list_price'];
            $post_data['request_data']['sale_price'] = $product_data['sale_price'];
            $post_data['request_data']['kdv'] = $this->entegrasyon->getKdvRange($product_data['tax_class_id']);
        }


        if ($code == 'ty' || $code == 'cs' || $code == 'hb') {
            $post_data['request_data'] = $product_data;
        }

        $post_data['market'] = $this->model_entegrasyon_general->getMarketPlace($code);
        $post_data['request_data']['market'] = $marketplace_data;

        $result = $this->entegrasyon->clientConnect($post_data, 'close_for_sale', $code, false);

        if (!isset($product_data['sale_price'])) {
            $product_data = $product_data[0];

        }

        $logmesage = $product_info['model'] . ' Action: Open for sale ';;

        $logmesage .= '-Stock - :' . $product_data['quantity'] . ' - Sale Price:' . $product_data['sale_price'] . ' - List Price:' . $product_data['list_price'];

        $logmesage .= '- Result:' . $result['message'];

        $this->entegrasyon->log($code, $logmesage, $bulk);

        if ($result['status']) {
            $marketplace_data['sale_status'] = 0;
            $marketplace_data['approval_status'] = 1;
            $this->entegrasyon->addMarketplaceProduct($product_id, $marketplace_data, $code);
            $price = $this->currency->format(0, $this->uconfig->get('config_currency'));
            if ($bulk) {

                return array('status' => true, 'price' => $price, 'message' => $product_info['name'] . ' Başarıyla Satışa Kapatılmıştır.');

            } else {

                echo json_encode(array('status' => true, 'price' => $price, 'message' => 'Ürün Başarıyla Satışa Kapatılmıştır.'));

            }

        } else {

            if ($bulk) {

                return array('status' => false, 'message' => $product_info['name'] . '-' . $result['message']);

            } else {

                echo json_encode(array('status' => false, 'message' => $result['message']));

            }

        }


    }

    public function open_for_sale($product_id = null, $code = null, $bulk = false)
    {

        $this->load->model("entegrasyon/general");
        $this->load->model("entegrasyon/market_productf");


        if (!$this->model_entegrasyon_general->checkPermission()) {

            if ($bulk) {
                return array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda ürün işlemlerine izin verilmemektedir.');
            } else {
                echo json_encode(array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda ürün gönderilmesine izin verilmemektedir.'));
            }
            return;
        }


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

        }

        if (!$code) {

            $code = $this->request->post['code'];

        }


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


        if (!$product_info['quantity']) {

            if ($bulk) {
                return array('status' => false, 'message' => "Ürünü satışa açabilmeniz için ürün stoğu 0'dan büyük olmalıdır.");
            } else {
                echo json_encode(array('status' => false, 'message' => "Ürünü satışa açabilmeniz için ürün stoğu 0'dan büyük olmalıdır."));
            }
            return;
        }

        $marketplace_data =  $this->model_entegrasyon_market_product->getMarketPlaceProductForMarket($product_id, $code);


        if (!$marketplace_data) {

            if ($bulk) {
                return array('status' => false, 'message' => 'Ürün mağazada bulunamadı, işlem yapabilmek için önce ürünü mağazaya göndermelisiniz.');
            } else {
                echo json_encode(array('status' => false, 'message' => 'Ürün mağazada bulunamadı, işlem yapabilmek için önce ürünü mağazaya göndermelisiniz.'));
            }
            return;

        }


        if ($code == 'hb') {

            $product_data = $this->entegrasyon->getMarketVariants($product_id, $code);

        } else {

            $product_data = $this->entegrasyon->getProductForUpdate($code, $product_info, $marketplace_data['commission'], 0);

        }

        if ($code != 'hb') {
            $post_data['request_data']['kdv'] = $this->entegrasyon->getKdvRange($product_data['tax_class_id']);
            $post_data['request_data']['product_id'] = isset($marketplace_data['product_id']) ? $marketplace_data['product_id'] : '';
            $post_data['request_data']['model'] = $this->uconfig->get($code . '_setting_model_prefix') . $product_info['model'];
            $post_data['request_data']['quantity'] = $product_data['quantity'];
            $post_data['request_data']['list_price'] = $product_data['list_price'];
            $post_data['request_data']['sale_price'] = $product_data['sale_price'];
        }
        if ($code == 'ty' || $code == 'cs' || $code == 'hb') {
            $post_data['request_data'] = $product_data;
        }
        $post_data['market'] = $this->model_entegrasyon_general->getMarketPlace($code);
        $post_data['request_data']['market'] = $marketplace_data;

        if ($code == "gg") $this->update($product_id, $code, true);

        $result = $this->entegrasyon->clientConnect($post_data, 'open_for_sale', $code, false);


        if (!isset($product_data['quantity'])) {
            $product_data = $product_data[0];
        }
        $logmesage = $product_info['model'] . ' Action: Close for sale ';;

        $logmesage .= '-Stock - :' . $product_data['quantity'] . ' - Sale Price:' . $product_data['sale_price'] . ' - List Price:' . $product_data['list_price'];

        $logmesage .= '- Result:' . $result['message'];

        $this->entegrasyon->log($code, $logmesage, $bulk);

        if ($result['status']) {

            if ($code == 'n11') {

                $marketplace_data['sale_status'] = 2;
                $marketplace_data['approval_status'] = 1;

            } else {

                $marketplace_data['sale_status'] = 1;

            }
            // $marketplace_data['approval_status'] = 1;

            $marketplace_data['price'] = $product_data['list_price'];
            $marketplace_data['sale_price'] = $product_data['sale_price'];


            //print_r($marketplace_data);return;
            $this->entegrasyon->addMarketplaceProduct($product_id, $marketplace_data, $code);

            $price = $this->currency->format($product_data['sale_price'], $this->uconfig->get('config_currency'));

            if ($bulk) {

                return array('status' => true, 'price' => $price, 'message' => $product_info['name'] . ' Başarıyla Satışa Açılmıştır.');

            } else {

                echo json_encode(array('status' => true, 'price' => $price, 'message' => 'Ürün Başarıyla Satışa Açılmıştır.'));

            }


        } else {


            if ($bulk) {

                return array('status' => false, 'message' => $result['message']);

            } else {

                echo json_encode(array('status' => false, 'message' => $product_info['name'] . '-' . $result['message']));

            }

        }


    }

    public function deleteproduct($product_id = null, $code = null, $bulk = false)
    {

        if (!$this->model_entegrasyon_general->checkPermission()) {

            if ($bulk) {
                return array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda ürün işlemlerine izin verilmemektedir.');
            } else {
                echo json_encode(array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda ürün gönderilmesine izin verilmemektedir.'));
            }
            return;
        }


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

        }

        if (!$code) {

            $code = $this->request->post['code'];

        }

        $this->load->model('entegrasyon/general');
        $marketPlace = $this->model_entegrasyon_general->getMarketPlace($code);

        if ($code == 'ty' || $code == 'hb' || $code == 'cs') {

            $this->entegrasyon->deleteMarketplaceProduct($product_id, $code);

            $result = array('status' => true, 'type' => 1, 'message' => $marketPlace["name"] . ' Pazaryerinde ürün silme özelliği mevcut değildir! Ürününüz henüz oyanlanmadıysa ürünü ' . $marketPlace['name'] . ' panelinizden silebilirsiniz. Ürünü tekrar göndermek için ' . $marketPlace['name'] . ' panelinizden silmeniz gerekmektedir.  Ürün Entegrasyon\'dan silindi!');

            if ($bulk) {
                return $result;

            } else {

                echo json_encode($result);

            }
            return;
        }


        if ($code == 'eptt') {

            echo json_encode(array('status' => false, 'type' => 1, 'message' => $marketPlace['name'] . ' Pazaryerinde ürün silme özelliği mevcut değildir! Ancak ürün stoğunu sıfırlayarak satışa kapatabilirsiniz. Stoğu sıfıramak ve satışa kapatmak istermisiniz ?'));
            return;
        }

        $this->load->model('entegrasyon/product/' . $code);
        $result = $this->{"model_entegrasyon_product_" . $code}->deleteProduct($product_id);


        $logmesage = $product_id . ' Action: Delete Product ';;


        $logmesage .= '- Result:' . $result['message'];

        $this->entegrasyon->log($code, $logmesage, $bulk);


        if ($bulk) {
            return $result;

        } else {

            echo json_encode($result);

        }


    }

    public function reset_stock()
    {

        $product_id = $this->request->post['product_id'];
        $code = $this->request->post['code'];
        $product_info = $this->entegrasyon->getProduct($product_id);
        $this->load->model('entegrasyon/product/' . $code);
        $result = $this->{"model_entegrasyon_product_" . $code}->reset_stock($product_info);


        echo json_encode($result);
    }


    public function update_quantity()
    {
        $quantity = $this->request->post['quantity'];
        $product_id = $this->request->post['product_id'];
        $product_info = $this->entegrasyon->getProduct($product_id);

        $this->db->query("update " . DB_PREFIX . "product SET quantity='" . $quantity . "' where product_id='" . $product_id . "'");

        $logmesage = 'By ' . $this->user->getUserName() . ' Product and options stock ' . $product_info['quantity'] . ' to ' . $quantity . ' updated on your OC catalog. Product Model:' . $product_info['model'];
        $this->entegrasyon->log('All', $logmesage, false);
        echo json_encode(array('status', 'result' => $quantity));

    }

    public function update_products_after_modified_page()
    {

        $data['product_id'] = $this->request->get['product_id'];
        $data['token_link'] = $this->token_data['token_link'];
        $this->response->setOutput($this->load->view('entegrasyon/product/update_after_modified', $data));

    }

    public function update_products_after_modified()
    {

        $products[] = $this->request->post['product_id'];
        $results = $this->entegrasyon->updateMarketplaceProdutcsAfterOrder($products, HTTP_CATALOG);
        $json = array();

        foreach ($results as $products) {
            foreach ($products as $code => $result) {

                $json[] = array('status' => $result['status'], 'marketplace' => $this->entegrasyon->marketPlaces[$code], 'message' => $result['status'] ? 'Başarıyla Güncellendi' : $result['message']);

            }


        }

        echo json_encode($json);
    }

    public function update_price()
    {

        $price = $this->request->post['value'];
        $product_id = $this->request->post['pk'];
        $code = $this->request->post['name'];
        $this->load->controller('entegrasyon/genel/save_setting', array('code' => $code, 'primary_id' => $product_id, 'name' => $code . '_product_sale_price', 'value' => $price, 'controller' => 'product'));
        $result = $this->update($product_id, $code, true, $price);
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($result));


    }


    public function update($product_id = null, $code = null, $bulk = false, $price = false)
    {

        error_reporting(E_ALL);
        ini_set('display_errors', 0);
        $this->load->model("entegrasyon/general");
        $this->load->model("entegrasyon/market_product");

        if (!$this->model_entegrasyon_general->checkPermission()) {

            if ($bulk) {
                return array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda ürün işlemlerine izin verilmemektedir.');
            } else {
                echo json_encode(array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda ürün gönderilmesine izin verilmemektedir.'));
            }
            return;
        }

        //$code='gg';
        //$product_id=15943;


        if (!$product_id) {

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

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

            }


        }


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

        } else {
            $mode = '';
        }


        if (!$code) {

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


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

        }


        $marketplace_data =  $this->model_entegrasyon_market_product->getMarketPlaceProductForMarket($product_id, $code);


        if (!$marketplace_data) {

            if ($bulk) {
                return array('status' => false, 'message' => 'Ürün mağazada bulunamadı, işlem yapabilmek için önce ürünü mağazaya göndermelisiniz.');
            } else {
                echo json_encode(array('status' => false, 'message' => 'Ürün mağazada bulunamadı, işlem yapabilmek için önce ürünü mağazaya göndermelisiniz.'));
            }
            return;

        }


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


        if (!$product_info) {
            if ($bulk) {
                return array('status' => false, 'message' => 'Ürün Kataloğunuzda bulunamadı!');
            } else {
                echo json_encode(array('status' => false, 'message' => 'Ürün Kataloğunuzda bulunamadı'));
            }
            return;

        }

        $category_setting = $this->entegrasyon->getMarketPlaceCategory($product_id, $code);
        $manufacturer_setting = $this->entegrasyon->getMarketPlaceManufacturer($product_info['manufacturer_id'], $code);
        $product_setting = $this->entegrasyon->getSettingData($code, 'product', $product_id);


        /*  if (!$marketplace_data['sale_status'] && $code != 'hb') {

              $json['status'] = false;
              $json['message'] = $product_info['name'] . ' - Satışa kapalı olduğu için güncellenmedi! ';

              if ($bulk) {
                  return $json;

              } else {

                  echo json_encode($json);

              }

              return;

          }
  */


        $defaults = $this->entegrasyon->getDefaults($category_setting, $manufacturer_setting, $product_setting, $code);
        $commission = $defaults['commission'];
        $product_info = $this->entegrasyon->getProductForUpdate($code, $this->entegrasyon->getProduct($product_id), $commission, $mode, HTTPS_CATALOG);


        //print_r($product_info);return;

        if ($price) {

            $product_info['sale_price'] = $price;
        }

        $product_info['model'] = $this->uconfig->get($code . '_setting_model_prefix') . $product_info['model'];;
        $this->load->model('entegrasyon/product/' . $code);
        $product_info = $this->{"model_entegrasyon_product_" . $code}->getExtraData($product_info);


        $post_data['request_data'] = $product_info;
        $post_data['market'] = $this->model_entegrasyon_general->getMarketPlace($code);

        if ($product_info['quantity'] <= 0) {
            $product_info['quantity'] = 0;
            $post_data['request_data']['quantity'] = 0;
            if ($code == "n11") {
                $this->close_for_sale($product_id, $code, false);
                return;
            }
        }

        //ana ürün başka alandan kodu seçilmiş ise
        if ($this->uconfig->get($code . '_setting_main_product_id')) {

            if ($product_info[$this->uconfig->get($code . '_setting_main_product_id')]) $product_data['product_setting'][$code . '_main_product_id'] = $product_info[$this->uconfig->get($code . '_setting_main_product_id')];

        }


        if ($mode) {
            $result = $this->entegrasyon->clientConnect($post_data, 'update_all', $code, $debug, false);


        } else {
            $result = $this->entegrasyon->clientConnect($post_data, 'update_basic', $code, $debug, false);

        }


        //  print_r($marketplace_data);return;


        if ($result['status']) {


            if ($product_info['quantity'] && $product_info['sale_price'] && $marketplace_data['approval_status']) {

                //$marketplace_data['sale_status'] = 1;

            } else {


                $marketplace_data['sale_status'] = 0;
                $marketplace_data['price'] = $product_info['sale_price'];

            }

            $marketplace_data['price'] = $product_info['sale_price'];
            $marketplace_data['commission'] = $commission;
            $this->entegrasyon->addMarketplaceProduct($product_info['product_id'], $marketplace_data, $code);

            $json['status'] = true;
            if ($mode) {
                $json['message'] = $product_info['name'] . ' tüm özellikleri güncellendi';
            } else {
                $json['message'] = $product_info['name'] . ' stok ve fiyatı güncellendi';

            }

        } else {

            /*  if($result['message']=='Fiyat stok güncellemesi için ürün bulunamadı'){

                  $this->entegrasyon->deleteMarketplaceProduct($product_id,$code);
              }*/

            $error = $this->entegrasyon->getError($product_info['product_id'], $code);
            if ($error) {
                $this->entegrasyon->updateError($product_info['product_id'], $code, 2, $result['message']);
            } else {
                $this->entegrasyon->addError($product_info['product_id'], $code, 2, $result['message']);
            }
            $json['status'] = false;
            $json['message'] = $product_info['name'] . ' - ' . $result['message'];

        }
        $this->load->model('entegrasyon/market_product');
        $data['marketplace_data'] =  $this->model_entegrasyon_market_product->getMarketPlaceProductForMarket($product_id, $code);

        $json['price'] = $this->currency->format($product_info['sale_price'], $this->uconfig->get('config_currency'));

        $logmesage = $product_info['model'] . ' Action:Update';;
        if ($mode) {
            $logmesage .= ' - Update content:' . 'Tüm Özellikler';
        } else {
            $logmesage .= ' - Update content:' . 'Stok & Fiyat';
        }
        $logmesage .= '-Stock - :' . $product_info['quantity'] . ' - Sale Price:' . $product_info['sale_price'] . ' - List Price:' . $product_info['list_price'];

        $logmesage .= '- Result:' . $json['message'];

        $this->entegrasyon->log($code, $logmesage, $bulk);

        if ($bulk) {
            return $json;

        } else {

            echo json_encode($json);

        }
    }

    public function view_product()
    {
        $product_id = $this->request->post['product_id'];
        $code = $this->request->post['code'];
        $marketplace_data = $this->model_entegrasyon_product->getMarketPlaceProductForMarket($product_id, $code);

        if ($marketplace_data['url']) {

            echo json_encode(array('status' => true, 'url' => $marketplace_data['url'], 'action' => true));

        } else {

            echo json_encode(array('status' => false, 'message' => 'Ürün pazaryerinde onayladıktan sonra görüntülenebilir. Ürününüz onaylandıya, Ayarlar sayfasından ürünlerinizi senkronize ettiğinizde ürün görüntüleme linki oluşacaktır.'));

        }


    }


    public function get_buttons()
    {
        $code = $this->request->get['code'];
        $product_id = $this->request->get['product_id'];
        $data['code'] = $code;
        $data['deletetable'] = true;//$code=='n11'|| $code=='gg' ? false:true;
        $this->load->model('entegrasyon/market_product');
        $data['product_id'] = $product_id;
        $data['marketplace_data'] = $this->model_entegrasyon_market_product->getMarketPlaceProductForMarket($product_id, $code);


        $data['token_link'] = $this->token_data['token_link'];

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


    }


    public function send_bulk()
    {
        $this->document->addStyle('view/stylesheet/entegrasyon/bootstrap4.css');
        $code = $this->request->get['code'];

        $this->load->model('entegrasyon/general');
        $marketPlaces = $this->model_entegrasyon_general->getMarketPlace($code);
        $data['code'] = $code;
        $data['market_name'] = $marketPlaces['name'];

        $data['token_link'] = $this->token_data['token_link'];

        $this->language->load('catalog/product');
        $this->document->setTitle($this->language->get('heading_title'));
        $this->load->model('entegrasyon/product');
        $this->load->model('entegrasyon/general');
        $this->model_entegrasyon_general->loadPageRequired();


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

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

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

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

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

        if (isset($this->request->get['filter_stock'])) {
            $filter_stock = $this->request->get['filter_stock'];
        } else {
            $filter_stock = '';
        }
        if (isset($this->request->get['filter_price_prefix'])) {
            $filter_price_prefix = html_entity_decode($this->request->get['filter_price_prefix']);
        } else {
            $filter_price_prefix = '';
        }

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

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


        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'pd.name';
        }

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

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

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

        $url = '';


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

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

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

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

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

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('catalog/product', $this->token_data['token_link'] . $url, 'SSL')
        );


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

        $filter_data = array(

            'filter_category' => $filter_category,
            'filter_name' => $filter_name,
            'filter_in_notname' => $filter_in_notname,
            'filter_manufacturer_id' => $filter_manufacturer,
            'filter_except' => $code,
            'filter_sub_category' => true,
            'filter_stock_prefix' => $filter_stock_prefix,
            'filter_price_prefix' => $filter_price_prefix,
            'filter_stock' => $filter_stock,
            'filter_price' => $filter_price,
            'filter_status' => $filter_status,
            'sort' => $sort,
            'order' => $order,
            'start' => 0,
            'limit' => 100000
        );

        if ($this->uconfig->get('easy_setting_invisible_image_for_bulk')) {
            $data['is_hidden_image'] = "hidden";

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

        $product_total = 0;//$this->model_entegrasyon_product->getTotalProducts($filter_data);

        $results = $this->model_entegrasyon_product->getProducts2($filter_data);


        $data['filter_category'] = $filter_category;

        $data['category_name'] = '';

        if ($filter_category) {
            $matched_category = $this->entegrasyon->getMatchedCategory($filter_category, $code);

            if (isset($matched_category[$code . '_category_id'])) {


                $category_info = explode('|', $matched_category[$code . '_category_id']);
                $category_id = $category_info[0];
                $category_name = $category_info[1];

                $data['category_id'] = $category_id;
                $data['oc_category_id'] = $filter_category;
                $data['category_name'] = $category_name;

                if ($filter_manufacturer) {
                    $this->load->model('catalog/manufacturer');
                    $manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($filter_manufacturer);
                    $data['filter_manufacturer_name'] = $manufacturer_info['name'];

                } else {

                    $data['filter_manufacturer_name'] = '';

                }

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

                $attributes = $this->model_entegrasyon_category->getAttributes($category_id, $code);


                unset($attributes['required_attributes']);


                foreach ($results as $result) {

                    //  $getOptionsNames = $this->entegrasyon->getOptionNames($result['product_id']);
                    $special = false;

                    $product_specials = $this->model_entegrasyon_product->getProductSpecials($result['product_id']);

                    foreach ($product_specials as $product_special) {
                        if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
                            $special = $this->currency->format($product_special['price'], $this->uconfig->get('config_currency'));

                            break;
                        }
                    }
                    if ($this->uconfig->get('easy_setting_invisible_image_for_bulk')) {
                        $image = "";

                    } else {

                        if (is_file(DIR_IMAGE . $result['image'])) {
                            $image = $this->model_tool_image->resize($result['image'], 40, 40);
                        } else {
                            $image = $this->model_tool_image->resize('no_image.png', 40, 40);
                        }
                    }

                    if ($result['image']) {


                        $data['products'][] = array(
                            'name' => $result['name'],
                            'product_id' => $result['product_id'],
                            'manufacturer' => $result['manufacturer'],
                            'image' => $image,
                            //'specs' => $attributes,
                            'model' => $result['model'],
                            'price' => $this->currency->format($result['price'], $this->uconfig->get('config_currency')),
                            'special' => $special,
                            'quantity' => $result['quantity'],
                            // 'options' => $getOptionsNames
                        );
                    }
                }
            }

        }

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

        $results = $this->model_catalog_category->getCategories(array('sort' => 'name'));

        foreach ($results as $result) {
            if ($result['name']) {
                $data['categories'][] = array(
                    'category_id' => $result['category_id'],
                    'name' => $result['name'],
                );
            }
        }

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

        $results = $this->model_catalog_manufacturer->getManufacturers();

        foreach ($results as $result) {
            $data['manufacturers'][] = array(
                'manufacturer_id' => $result['manufacturer_id'],
                'name' => $result['name'],
            );
        }

        $data['product_total'] = count($data['products']);

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

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

        $data['text_enabled'] = $this->language->get('text_enabled');
        $data['text_disabled'] = $this->language->get('text_disabled');
        $data['text_no_results'] = $this->language->get('text_no_results');
        $data['text_confirm'] = $this->language->get('text_confirm');

        $data['column_image'] = $this->language->get('column_image');
        $data['column_name'] = $this->language->get('column_name');
        $data['column_model'] = $this->language->get('column_model');
        $data['column_price'] = $this->language->get('column_price');
        $data['column_quantity'] = $this->language->get('column_quantity');
        $data['column_status'] = $this->language->get('column_status');
        $data['column_action'] = $this->language->get('column_action');

        $data['entry_name'] = $this->language->get('entry_name');
        $data['entry_model'] = $this->language->get('entry_model');
        $data['entry_price'] = $this->language->get('entry_price');
        $data['entry_quantity'] = $this->language->get('entry_quantity');
        $data['entry_status'] = $this->language->get('entry_status');

        $data['button_copy'] = $this->language->get('button_copy');
        $data['button_add'] = $this->language->get('button_add');
        $data['button_edit'] = $this->language->get('button_edit');
        $data['button_delete'] = $this->language->get('button_delete');
        $data['button_filter'] = $this->language->get('button_filter');


        if (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
        } else {
            $data['error_warning'] = '';
        }

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

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

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

        $url = '';


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


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

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

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


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

        if ($order == 'ASC') {
            $url .= '&order=DESC';
        } else {
            $url .= '&order=ASC';
        }

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

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


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

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

        $pagination = new Pagination();
        $pagination->total = $product_total;
        $pagination->page = $page;
        $pagination->limit = $limit;
        $pagination->url = $this->url->link('entegrasyon/product/send_bulk', $this->token_data['token_link'] . $url . '&code=' . $code . '&page={page}', 'SSL');

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

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

        $data['filter_category'] = $filter_category;
        $data['filter_manufacturer'] = $filter_manufacturer;
        $data['filter_name'] = $filter_name;
        $data['filter_in_notname'] = $filter_in_notname;
        $data['filter_stock_prefix'] = $filter_stock_prefix;
        $data['filter_stock'] = $filter_stock;
        $data['filter_price_prefix'] = $filter_price_prefix;
        $data['filter_price'] = $filter_price;
        $data['filter_status'] = $filter_status;


        $data['code'] = $code;
        $data['sort'] = $sort;
        $data['order'] = $order;

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


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


    public function bulk_actions()
    {


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


        $product_total = $this->model_entegrasyon_product->getTotalProductsNoFilter();
        $code = $this->request->get['marketplace'];
        //$products = $this->input->get['product_list'];
        $list_type = $this->request->get['list_type'];


        if ($list_type == 'all_filter') {

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

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

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

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

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

            if (isset($this->request->get['filter_stock_prefix'])) {
                $filter_stock_prefix = html_entity_decode($this->request->get['filter_stock_prefix']);
            } else {
                $filter_stock_prefix = "";
            }


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


            /* if($filter_stock_prefix!="*" && !$filter_stock){

                 $filter_stock=0;
             }*/

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

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

            /*   $data['filters'] = isset($this->request->get['filters']) ? $this->request->get['filters'] : '';
               $data_filters = explode(',', $data['filters']);
               // if ($data_filters[0] ||$data_filters[1] ||$data_filters[2] ||$data_filters[3] ||$data_filters[4] ||$data_filters[5] ||$data_filters[6] ||$data_filters[7] ){

               if(isset($data_filters['6'])){
                   $data_filters['6'] = str_replace('&gt;', '>', $data_filters['6']);
                   $data_filters['6'] = str_replace('&lt;', '<', $data_filters['6']);
               }
   */

            $filter_data = array(
                'filter_category' => $filter_category,
                'filter_manufacturer' => $filter_manufacturer,
                'filter_marketplace' => $filter_marketplace,
                'filter_marketplace_do' => $filter_marketplace_do,
                'filter_name' => $filter_name,
                'filter_model' => $filter_model,
                'filter_status' => $filter_status,
                'filter_stock_prefix' => $filter_stock_prefix,
                'filter_stock' => $filter_stock,
                'sort' => "pd.name",
                'order' => "ASC"
            );


            $data['filter_marketplace'] = $filter_marketplace;
            $data['filter_marketplace_do'] = $filter_marketplace_do;
            $data['filter_model'] = $filter_model;
            $data['filter_name'] = $filter_name;
            $data['filter_manufacturer'] = $filter_manufacturer;
            $data['filter_category'] = $filter_category;
            $data['filter_stock_prefix'] = $filter_stock_prefix;
            $data['filter_stock'] = $filter_stock;
            $data['filter_status'] = $filter_status;

            //$data['filter_data'] = serialize($filter_data);
            $product_total = count($this->model_entegrasyon_product->getProducts($filter_data, "for_bulk"));
            $data['product_list'] = $this->model_entegrasyon_product->getProducts($filter_data, "for_bulk");
            /*  }else{
                  $data['filter_data']=false;
                  $product_total = 0;
              }*/


            $data['total_active'] = $product_total;
            $data['total_passive'] = $product_total;
            $data['total_close'] = $product_total;

            $data['total'] = $product_total;
            $data['product_list'] = '';


        } else if ($list_type == 'selected') {
            $product_list = explode(',', $this->request->get['product_list']);

            $data['product_list'] = isset($this->request->get['product_list']) ? $this->request->get['product_list'] : '';

            $data['total'] = substr_count($data['product_list'], ",") + 1;

            $data['total_active'] = $data['total'];
            $data['total_passive'] = $data['total'];
            $data['total_close'] = $data['total'];


        } else {
            $data['total'] = $product_total;

            $product_list = $this->model_entegrasyon_product->getMarketPlaceProducts($code);
            $product_passive = $this->model_entegrasyon_product->getPassiveProducts($code);
            $product_close = $this->model_entegrasyon_product->getCloseMarketPlaceProducts($code);
            $data['product_list'] = '';
            $data['total_passive'] = $product_total - (count($product_list) + count($product_close));
            $data['total_close'] = count($product_close);
            $data['total_active'] = $product_list ? count($product_list) : 0;

        }


        $marketPlace = $this->model_entegrasyon_general->getMarketPlace($code);
        $data['marketplace'] = $marketPlace['name'];
        $data['list_type'] = $list_type;
        $data['code'] = $code;
        $data['delete_permission'] = $code == 'n11' || $code == 'gg' ? true : false;
        $data['commission'] = '';
        $data['value'] = '';
        $data['token_link'] = $this->token_data['token_link'];

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

    }


    public function bulk_action_progress()
    {


        ini_set('display_errors', 0);
        ini_set('display_startup_errors', 0);
        error_reporting(0);

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

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

        $url = '';


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

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

        $product_list = array();
        $action = $this->request->get['action'];

        $is_filter = 0;
        $filter_data = 0;

        if ($this->request->get['list_type'] == "all_filter") {
            if (isset($this->request->get['filter_category'])) {
                $filter_category = $this->request->get['filter_category'];
            } else {
                $filter_category = '';
            }

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

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

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

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

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

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

            if (isset($this->request->get['filter_stock_prefix'])) {
                $filter_stock_prefix = html_entity_decode($this->request->get['filter_stock_prefix']);
            } else {
                $filter_stock_prefix = "";
            }


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


            $filter_data = array(
                'filter_category' => $filter_category,
                'filter_manufacturer' => $filter_manufacturer,
                'filter_marketplace' => $filter_marketplace,
                'filter_marketplace_do' => $filter_marketplace_do,
                'filter_name' => $filter_name,
                'filter_model' => $filter_model,
                'filter_status' => $filter_status,
                'filter_stock_prefix' => $filter_stock_prefix,
                'filter_stock' => $filter_stock,
                'sort' => "pd.name",
                'order' => "ASC"
            );


            $data['filter_marketplace'] = $filter_marketplace;
            $data['filter_marketplace_do'] = $filter_marketplace_do;
            $data['filter_model'] = $filter_model;
            $data['filter_name'] = $filter_name;
            $data['filter_manufacturer'] = $filter_manufacturer;
            $data['filter_category'] = $filter_category;
            $data['filter_stock_prefix'] = $filter_stock_prefix;
            $data['filter_stock'] = $filter_stock;
            $data['filter_status'] = $filter_status;

            $url_prefix = 'filter_marketplace=' . $filter_marketplace . '&filter_marketplace_do=' . $filter_marketplace_do . '&filter_model=' . $filter_model . '&filter_name=' . $filter_name . '&filter_manufacturer=' . $filter_manufacturer . '&filter_category=' . $filter_category . '&filter_stock_prefix=' . $filter_stock_prefix . '&filter_stock=' . $filter_stock . '&filter_status=' . $filter_status;

            $is_filter = 1;

        }

        $code = $this->request->get['code'];
        $list_type = $this->request->get['list_type'];


        if ($list_type == 'selected') {
            $product_list = explode(',', $this->request->get['product_list']);

            $data['product_list'] = $this->request->get['product_list'];
            $json['total'] = count($product_list);


        } else if ($is_filter) {

            $product_list = $this->model_entegrasyon_product->getProducts($filter_data);


        } else {
            if ($action == 'addproduct') {

                $product_list = $this->model_entegrasyon_product->getPassiveProducts($code);


            } elseif ($action == 'open_for_sale') {

                $product_list = $this->model_entegrasyon_product->getCloseMarketPlaceProducts($code);

            } else {

                $product_list = $this->model_entegrasyon_product->getMarketPlaceProducts($code);


            }
            $data['product_list'] = '';
            $json['total'] = count($this->model_entegrasyon_product->getProducts($filter_data));

        }


        //return;

        if ($list_type == 'selected') {

            // print_r($product_list);
            $product_id = $product_list[$page - 1];

        } else {

            if ($action == 'open_for_sale' || $action == 'close_for_sale' || $action == 'addproduct') {

                if ($is_filter) {

                    $product_id = $product_list[$bypass]['product_id'];


                } else {

                    $product_id = $product_list[$bypass]['product_id'];

                }

            } else {

                $product_id = $product_list[$page - 1]['product_id'];

            }


        }


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


        $result = $this->{$action}($product_id, $code, true);
        // $result=array('status'=>true,'message'=>$product_id);


        if (!$result['status']) {
            $bypass++;
        }

        $json['update_status'] = $result['status'];
        if (isset($product_info['name'])) {
            $json['message'] = $page . '-' . $product_id . '-' . $product_info['name'] . ' - ' . $result['message'];
        } else {
            $json['message'] = $page . '-' . $product_id . '-' . $result['message'];

        }
        //toplu işlem bilgi kısmı ürün adı -1 bul-..
        $total = $is_filter ? $total_for_progress : count($product_list);

        $page++;
        if ($is_filter) {
            if (!isset($data['product_list'])) {
                $data['product_list'] = '';
            }

            $url = 'index.php?route=entegrasyon/product/bulk_action_progress&code=' . $code . '&page=' . $page . '&list_type=' . $list_type . '&action=' . $action . '&product_list=' . $data['product_list'] . '&bypass=' . $bypass . '&' . $this->token_data['token_link'] . '&total_for_progress=' . $total_for_progress;

        } else if ($list_type == 'selected') {

            $url = 'index.php?route=entegrasyon/product/bulk_action_progress&code=' . $code . '&page=' . $page . '&list_type=' . $list_type . '&action=' . $action . '&product_list=' . $data['product_list'] . '&' . $this->token_data['token_link'] . '&bypass=' . $bypass . '&total_for_progress=' . $total_for_progress;

        } else {
            $url = 'index.php?route=entegrasyon/product/bulk_action_progress&code=' . $code . '&page=' . $page . '&list_type=' . $list_type . '&action=' . $action . '&product_list=&bypass=' . $bypass . '&' . $this->token_data['token_link'] . '&total_for_progress=' . $total_for_progress;

        }

        if ($is_filter) {
            $url = $url . '&' . $url_prefix;
        }


        $json['total_for_progress'] = $total_for_progress;


        $json['current'] = $page - 1;
        $json['bypass'] = $bypass;


        if ($page <= $total_for_progress) {

            $json['status'] = true;
            $json['next'] = $url;

        } else {
            $json['status'] = false;
            //$json['message']='Tamamlandı';
        }


        echo json_encode($json);
    }


    public function update_bulk()
    {

        $marketPlaces = $this->entegrasyon->getMarkets();

        $code = $this->request->get['code'];
        $commission = $this->request->get['commission'];
        $controller = $this->request->get['controller'];
        $value = $this->request->get[$controller];
        $total = $this->request->get['total'];

        //$this->load->model('entegrasyon/product');
        /*$filter_data= array(
             'filter_marketplace'=>$code,
             'filter_'.$controller=>$value
         );


         $getProducts=$this->model_entegrasyon_product->getProducts($filter_data);
        */


        $data['marketplace'] = $marketPlaces[$code];
        $data['page_type'] = $controller == 'category' ? 'Kategori' : 'Marka';
        $data['controller'] = $controller;
        $data['code'] = $code;
        $data['commission'] = $commission;
        $data['value'] = $value;
        $data['total'] = $total;
        $data['token_link'] = $this->token_data['token_link'];

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

    }

    public function update_bulk_price()
    {

        $this->load->model('entegrasyon/general');

        if (!$this->model_entegrasyon_general->checkPermission()) {

            echo json_encode(array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda fiyat güncellemesine izin verilmemektedir.'));
            return;

        }

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


        $code = $this->request->get['code'];
        $controller = $this->request->get['controller'];
        $value = $this->request->get[$controller];
        $commission = $this->request->get['commission'];
        $total = $this->request->get['total'];

        $this->load->model('entegrasyon/product');
        $filter_data = array(
            'filter_marketplace' => $code,
            'filter_' . $controller => $value,
            'start' => ($page - 1),
            'limit' => 1
        );

        $product = $this->model_entegrasyon_product->getProducts($filter_data)[0];
        $product_info = $this->entegrasyon->getProductForUpdate($code, $this->entegrasyon->getProduct($product['product_id']), $commission);

        $product_info['model'] = $this->uconfig->get($code . '_setting_model_prefix') . $product_info['model'];
        //  $result= $this->{$code}->updateBasic($product_info);
        $post_data['request_data'] = $product_info;
        $post_data['market'] = $this->model_entegrasyon_general->getMarketPlace('ty');
        $result = $this->entegrasyon->clientConnect($post_data, 'update_basic', $code);

        if ($result['status']) {
            $marketplace_data = json_decode($product_info[$code]);
            if (isset($marketplace_data['url'])) {
                $url = $marketplace_data['url'];
            } else {
                $url = '';
            }
            //$data=array('commission'=>$commission,'product_id'=>$marketplace_data['product_id'],'price'=>$product_info['sale_price'],'url'=>$url);

            $marketplace_data = $this->entegrasyon->getMarketPlaceProductForMarket($product_info['product_id'], $code);

            $marketplace_data['price'] = $product_info['sale_price'];
            $marketplace_data['commission'] = $commission;
            $this->entegrasyon->addMarketplaceProduct($product_info['product_id'], $marketplace_data, $code);

            $json['update_status'] = true;
            $json['message'] = $product['name'] . ' güncellendi';

        } else {
            $error = $this->entegrasyon->getError($product_info['product_id'], $code);
            if ($error) {
                $this->entegrasyon->updateError($product_info['product_id'], $code, 2, $result['message']);
            } else {
                $this->entegrasyon->addError($product_info['product_id'], $code, 2, $result['message']);
            }

            $json['update_status'] = false;
            $json['message'] = $product['name'] . ' - ' . $result['message'];
        }

        $logmesage = $product_info['model'] . ' Action:Update bulk price';;

        $logmesage .= '-Stock - :' . $product_info['quantity'] . ' - Sale Price:' . $product_info['sale_price'] . ' - List Price:' . $product_info['list_price'];

        $logmesage .= '- Result:' . $json['message'];

        $this->entegrasyon->log($code, $logmesage, true);


        $page++;
        $url = 'index.php?route=entegrasyon/product/update_bulk_price&page=' . $page . '&total=' . $total . '&code=' . $code . '&commission=' . $commission . '&controller=' . $controller . '&' . $controller . '=' . $value . '&' . $this->token_data['token_link'];

        $json['current'] = $page - 1;

        if ($page <= $total) {

            $json['status'] = true;
            $json['next'] = $url;

        } else {
            $json['status'] = false;
            //$json['message']='Tamamlandı';
        }

        echo json_encode($json);

    }


    public function download_product_bulk()
    {


        error_reporting(0);

        $this->load->model('entegrasyon/general');

        if (!$this->model_entegrasyon_general->checkPermission()) {

            echo json_encode(array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda ürün aktarılmasına izin verilmemektedir.'));
            return;

        }


        // if(!isset($this->request->post['product_id']))return;
        $code = $this->request->get['code'];


        $list = $this->request->post['list'];


        $product_id = $this->request->get['product_id'];
        $current_key = array_search($product_id, $list);
        $category_id = isset($this->request->get['category_id']) ? $this->request->get['category_id'] : 0;
        $manufacturer_id = isset($this->request->get['manufacturer_id']) ? $this->request->get['manufacturer_id'] : 0;


        $this->load->model('entegrasyon/product/' . $code);


        $marketplace_product_info = $this->{"model_entegrasyon_product_" . $code}->getMarketPlaceProduct($product_id, $category_id, $manufacturer_id);


        if (!$marketplace_product_info['status']) {
            echo json_encode($marketplace_product_info);
            return;
        }

        $product_info = $this->entegrasyon->getProductByModel($marketplace_product_info['product_data']['model'], $marketplace_product_info['product_data']['model']);

        if ($product_info) {

            $model = $this->startsWith($this->uconfig->get($code . '_setting_model_prefix'), $product_info['model']);
            $product_info['model'] = $model;

        }


        if (!$product_info) {


            $product_id = $this->entegrasyon->addProduct($marketplace_product_info['product_data']);

            if ($product_id) {

                $this->entegrasyon->addMarketplaceProduct($product_id, $marketplace_product_info['marketplace_product_data'], $code);
            }
            if ($current_key + 1 < count($list)) {


                echo json_encode(array('status' => true, 'next' => true, 'item' => $list[$current_key + 1], 'list' => $list, 'current' => $current_key + 1, 'message' => "Ürün Başarıyla Mağazanıza Eklendi"));


            } else {

                echo json_encode(array('status' => true, 'next' => false, 'item' => $list[$current_key], 'list' => $list, 'current' => $current_key + 1, 'message' => "Ürün Başarıyla Mağazanıza Eklendi!"));

            }

        } else {

            if ($current_key + 1 < count($list)) {


                echo json_encode(array('status' => false, 'next' => true, 'item' => $list[$current_key + 1], 'list' => $list, 'current' => $current_key + 1, 'message' => "Ürün Mazağanızda Olduğu İçin Eklenemedi."));


            } else {

                echo json_encode(array('status' => false, 'next' => false, 'item' => $list[$current_key], 'list' => $list, 'current' => $current_key + 1, 'message' => "Ürün Mazağanızda Olduğu İçin Eklenemedi."));

            }

        }


    }




    private function startsWith($string, $startString)
    {
        $len = strlen($startString);
        $result = (substr($string, 0, $len) === $startString);
        if ($result) {

            $cut = explode($startString, $string);
            return $cut[1];

        } else {

            return $string;
        }
    }

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

        if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model'])) {
            $this->load->model('entegrasyon/product');
            $this->load->model('catalog/option');

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

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

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

            $filter_data = array(
                'filter_name' => $filter_name,
                'filter_model' => $filter_model,
                'start' => 0,
                'limit' => $limit
            );

            $results = $this->model_entegrasyon_product->getProducts($filter_data);

            foreach ($results as $result) {
                $option_data = array();

                $json[] = array(
                    'product_id' => $result['product_id'],
                    'name' => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
                    'model' => $result['model'],
                    'option' => $option_data,
                    'sale_price' => $result['sale_price']
                );
            }
        }


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


    public function variants()
    {
        $product_id = $this->request->get['product_id'];

        $this->load->model('entegrasyon/product/variant');
        $this->load->model('tool/image');
        $product_variants = $this->model_entegrasyon_product_variant->getProductVariants($product_id);
        $query = $this->udb->query("select name from product_description where product_id='" . $product_id . "' and language_id=1");


        if ($product_variants) {

            foreach ($product_variants as $product_variant) {

                $matching_words = explode(' ', $query->row['name'], 3);
                array_pop($matching_words);

                if ($product_variant['image']) {
                    $image = $this->model_tool_image->resize($product_variant['image'], 70, 70);
                } else {
                    $image = $this->model_tool_image->resize2('no_image.png', 70, 70);
                }


                foreach ($product_variant['variant_values'] as $value) {

                    $query->row['name'] .= ' ' . $value['name'];
                    $matching_words[] = $value['name'];
                }


                $data['product_variants'][] = array(

                    'variant_id' => $product_variant['product_variant_id'],
                    'imagesrc' => $image,
                    'product_name' => $query->row['name'],
                    'matching_words' => implode(',', $matching_words),
                    'image' => $product_variant['image'],
                    'barcode' => $product_variant['barcode'],
                    'stock_code' => $product_variant['stock_code'],
                    'quantity' => $product_variant['quantity'],
                    'sale_price' => $product_variant['sale_price'],
                    'variant_values' => $product_variant['variant_values'],
                    'n11' => $product_variant['n11'],
                    'gg' => $product_variant['gg'],
                    'hb' => $product_variant['hb'],
                    'ty' => $product_variant['ty'],
                    'cs' => $product_variant['cs'],
                    'etsy' => $product_variant['etsy'],
                    'amz' => $product_variant['amz'],
                    'amzeu' => $product_variant['amzeu'],
                    'amzus' => $product_variant['amzus'],
                    'eptt' => $product_variant['eptt'],

                );;
            }
        }

        $marketplaces = $this->model_entegrasyon_general->getMarketPlaces();


        foreach ($marketplaces as $marketplace) {

            if ($marketplace['status']) {
                $filter_data[$marketplace['code']] = true;
                $data['edit_button_status'] = true;
            }

        }
        $data['marketplaces'] = $marketplaces;
        $data['product_id'] = $product_id;
        $data['token_link'] = $this->token_data['token_link'];
        $this->response->setOutput($this->load->view('entegrasyon/product/variant_list', $data));

    }

}
