<?php

namespace marketplace;
final class N11
{


    private $product_stock_service = 'https://api.n11.com/ws/ProductStockService.wsdl';
    private $product_service = 'https://api.n11.com/ws/ProductService.wsdl';
    private $catalog_service= 'https://api.n11.com/ws/CatalogService.wsdl';
    private $product_selling_service = 'https://api.n11.com/ws/ProductSellingService.wsdl';
    private $city_service = 'https://api.n11.com/ws/CityService.wsdl';
    private $category_service = 'https://api.n11.com/ws/CategoryService.wsdl';
    private $order_service = 'https://api.n11.com/ws/OrderService.wsdl';
    private $shipment_service = 'https://api.n11.com/ws/ShipmentService.wsdl';



    protected function clientConnect($url, $function)
    {



        $proxy_response=$this->proxy($url,$function);;
        return $proxy_response;

        try {






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

                return array(
                    'status' => $result['result']['status'] == 'success' ? true : false,
                    'message' => $result['result']['status'] == 'failure' ? $result['result']['errorMessage'] : '',
                    'result' => $result

                ); }else {

                return $result;

            }


        } catch (\SoapFault $exception) {

            // print_r($exception);

            //return array('status' => false, 'message' => $exception->getMessage(),'result'=>null);


            $proxy_response=$this->proxy($url,$function);;
            return $proxy_response;
            print_r($proxy_response);
            return ;

            if($proxy_response['status']){

                return $proxy_response;

            }else {

                return array('status' => false, 'message' => '','result'=>null);


            }


        }

    }


    protected function proxy($url,$service)
    {



        $json_data = json_encode(array('code' => 'n11','url'=>$url,'service'=>$service, 'params'=>$this->parameters));
        //return addslashes($json_data);

        $url = 'https://www.ellconline.com/index.php?route=api/easyentegre/proxy/n11';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
        //curl_setopt($curl, CURLOPT_TIMEOUT_MS, 5000);
        // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($curl);

        

        return json_decode($result,1);


    }



    public function checkApi($params)
    {
        $this->parameters['auth'] = $params;
        $result = $this->clientConnect($this->category_service, 'GetTopLevelCategories');


        return $result;

    }

    public function shipping_templates($api_info)
    {

        $this->parameters['auth'] = $api_info;
        $get_templates = $this->clientConnect($this->shipment_service, 'GetShipmentTemplateList');
        $sablonlar = array();
        $i = 0;
        if ($get_templates['status']) {

            if (isset($get_templates['result']['shipmentTemplates']['shipmentTemplate']['templateName'])) {
                $sablon=$get_templates['result']['shipmentTemplates']['shipmentTemplate'];
                $sablonlar[$sablon['templateName']] = $sablon['templateName'];


            }else {
                if(isset($get_templates['result']['shipmentTemplates']['shipmentTemplate'])){
                    foreach ($get_templates['result']['shipmentTemplates']['shipmentTemplate'] as $sablon) {
                        $sablonlar[$sablon['templateName']] = $sablon['templateName'];
                        $i++;
                    }
                }

            }
        }



        return array('status'=>$get_templates['status'],'message'=>$get_templates['message'],'result'=>$sablonlar);
    }


    public function sell_product($product,$api_info)
    {
        $this->parameters['auth'] = $api_info;
        $this->parameters['product'] = $product;

        $result = $this->clientConnect( $this->product_service, 'SaveProduct');


        return $result;
    }

    private function priceControl($price)
    {
        return str_replace(',', '.', $price);

    }

    public function add_product($product_data, $api_info)
    {


        $this->parameters['auth'] = $api_info;
        $defaults = $product_data['defaults'];


        $attributes = array();
        $is_manufacturer_exists=false;

        foreach ($product_data['attributes'] as $attribute) {

            /*  if(strtolower($attribute['name'])=='marka'){
                  $is_manufacturer_exists=true;
              }*/

            $attributes[] = array(
                'name' => $attribute['name'],
                'value' => str_replace('x_x', "''", $attribute['value'])
            );
        }

        $title=array();
        if($product_data['manufacturer']){
            // $title[]=$product_data['manufacturer'];
        }
        if($product_data['attributes']){

            foreach ( $product_data['attributes'] as $item) {

                if($item['name']=='Cinsiyet'){

                    $title[]=$item['value'];

                }
            }

        }


        /*if(isset($product_data['manufacturer'])) {
                 if (!$is_manufacturer_exists && $product_data['manufacturer']) {

                     $attributes[] = array(
                         'name' => 'Marka',
                         'value' => $product_data['manufacturer']
                     );

                 }
             }*/



        $productMainId=isset($product_data['product_setting']['n11_product_code'])?$product_data['product_setting']['n11_product_code']?$product_data['product_setting']['n11_product_code']:$product_data['model']:$product_data['model'];
        $barcode=isset($product_data['product_setting']['n11_barcode'])?$product_data['product_setting']['n11_barcode']?$product_data['product_setting']['n11_barcode']:$product_data['model']:$product_data['model'];


        if(isset($defaults['domestic'])){

            if($defaults['domestic']=='Yerli'){
                $domestic=true;

            }else if($defaults['domestic']=='Yabancı') {

                $domestic=false;

            }else {

                $domestic =$defaults['domestic']?true:false;
            }



        }else {

            $domestic=true;
        }


        $images=array();

        foreach ($product_data['images']['image'] as $image) {

            if(count($images) <= 11){
                $images[]=$image;
            }
        }

        if($title){
            $product_data['title']=implode(' ',$title).' '.$product_data['title'];
        }
        $description =$product_data['description'] ? $product_data['description'] : $product_data['title'];

        $subtitle=$defaults['subtitle'] ?  mb_substr($defaults['subtitle'], 0, 65) : mb_substr($product_data['title'], 0, 65);
        $product_data['title'] = str_replace('<', '-', $product_data['title']);
        $product_data['title'] = str_replace('>', '-', $product_data['title']);
        // $product_data['model']='34543ffd';
        $send_product_data = array(

            'productSellerCode' => $product_data['model'],
            'sellerNote' => "",
            'title' => strlen($product_data['title'])>65 ? mb_substr($product_data['title'], 0, 65):$product_data['title'],
            'maxPurchaseQuantity'=>isset($defaults['maximum_order'])?$defaults['maximum_order']?$defaults['maximum_order']:10:10,
            'subtitle' =>html_entity_decode($subtitle) ,
            'attributes' => $attributes,
            'approvalStatus' => 1,
            'specialProductInfoList' => array(),
            'saleStatus' => 'On_Sale',
            'groupAttribute' => '',
            'groupItemCode' => '',
            'itemName' => '',
            'description' => isset($product_data['product_setting']['n11_catalog_id'])?isset($product_data['product_setting']['n11_product_desciption'])?strip_tags(html_entity_decode($product_data['product_setting']['n11_product_desciption'], ENT_QUOTES, 'UTF-8')):strip_tags(html_entity_decode($product_data['title'])) : html_entity_decode($description),
            'category' => array('id' => $product_data['category_id']),
            'price' => $this->priceControl($product_data['list_price']),
            'currencyType' => 1,
            'images' => array('image'=>$images),
            'saleStartDate' => '',
            'domestic' => $domestic,
            'saleEndDate' => '',
            'unitInfo' => '',
            'productionDate' => '2',
            'expirationDate' => '',
            'productCondition' => '1',
            'preparingDay' => $defaults['shipping_time'] ? $defaults['shipping_time'] : 3,
            'shipmentTemplate' => $defaults['shipping_template'],
            'stockItems' => array(
                'stockItem' => array(
                    // 'bundle'=>null,
                    // 'mpn' =>null,
                    'n11CatalogId' => (string)isset($product_data['product_setting']['n11_catalog_id'])?$product_data['product_setting']['n11_catalog_id']:'',
                    'gtin'=>isset($product_data['product_setting']['n11_barcode'])?$product_data['product_setting']['n11_barcode']:'',
                    'quantity' => $product_data['quantity'] < 0 ? 0:$product_data['quantity'] ,
                    'sellerStockCode' => $product_data['model'],
                    'attributes' => array(),
                    'optionPrice' => ''//$this->priceControl($product_data['list_price'])
                )


            ));

        if ($product_data['sale_price']<$product_data['list_price']) {

            $discount['type'] = 3;
            $discount['value'] = (double)$this->priceControl($product_data['sale_price']);
            $discount['startDate'] = (string)'';
            $discount['endDate'] = (string)'';

        } else {

            $discount['type'] = '';
            $discount['value'] = (double)'';
            $discount['startDate'] = (string)'';
            $discount['endDate'] = (string)'';

        }

        if(isset($product_data['variants']['variants']['options'])){

            $variants=$this->getVariants($product_data['variants']['variants'],$product_data['model'],$product_data['list_price'],false,$product_data['kdv'],$product_data['product_setting'],true);
            $send_product_data['stockItems'] = $variants;

        }

        $send_product_data['discount'] = $discount;
        $this->parameters['product'] = $send_product_data;


        //print_r($send_product_data);return;


        $result = $this->clientConnect($this->product_service, 'SaveProduct');




        if(!$result['status']){
            if($result['message']=='Kategori güncelleme özelliğiniz hesabınızda aktif değildir,lütfen kategori yöneticinize başvurunuz.')   {

                $n11_product=$this->get_product($product_data['model'],$api_info);
                if($n11_product['status']){

                    return $n11_product;

                }


            }else if($result['message']=='Resource Not Found !'){

                if(isset($result['result']['result']['errorCode'])){

                    $errorCode=$result['result']['result']['errorCode'];
                    if($errorCode=='GTIN.n11CatalogIdNotUnique'){
                        $result['message']='N11:Girilen Katalog ID Numarası Benzersiz değil ';
                    }else {
                        $result['message'] = $result['result']['result']['errorCode'];
                    }

                }

            }

        }else {

            $result['message'] = 'Ürün başarıyla listelenmiştir.';

        }

        return $result;

    }


    private function getVariants($variant_list,$model,$price,$forUodate=false,$tax=false,$product_setting=false,$mode=false)
    {

        $saved_variants=array();
        if(isset($variant_list['options'])){
            if($variant_list['options']){
                $variant_list =$variant_list['options'];
            }
        }

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

        if(isset($variant_list['saved_variants'])){

            $saved_variants=$variant_list['saved_variants'];
            unset($variant_list['saved_variants']);

        }

        foreach ($variant_list as $options) {


            $attribute = array();

            foreach ($options['attributes'] as $option) {
                $attribute[] = array(
                    'name' => $option['name'],
                    'value' => str_replace('/','',$option['value']),

                );

            }

            if($options['price'] && $tax){
                $option_price= $tax ? $options['price'] + (($options['price']*$tax)/100):$options['price'];

            }else {

                $option_price=$options['price'];

            }

            $stockItem = array(

                'quantity' => $options['quantity']>0 ? $options['quantity']:0,
                'sellerStockCode' => $mode ? $model.$options['prefix']:$options['model'],
                'optionPrice' => $price+$option_price ,
            );


            if($forUodate){

                $stockItem['id']=null;

            }else {


                $stockItem['n11CatalogId']='';
                $stockItem['gtin']='';
                $stockItem['attributes'] = array('attribute' => $attribute);
                $stockItem['currencyAmount'] = $price+$option_price;


            }


            $data['stockItem'][] =$stockItem;

        }




        return $data;


    }


    public function findBarcode($prefix,$model,$variants)
    {



        foreach ($variants as $variant) {


            $prefix_arr=explode($model,$variant['model']);


            if($prefix_arr[1]== $prefix){


                return $variant['barcode'];
            }

        }

        return false;

    }

    public function delete_product($product_data, $api_info)
    {


        $this->parameters['auth'] = $api_info;
        $this->parameters['productSellerCode'] = $product_data;
        return $this->clientConnect($this->product_service, 'DeleteProductBySellerCode');

    }

    public function close_for_sale($product_data, $api_info)
    {
        $this->parameters['auth'] = $api_info;
        if(isset($product_data['market']['barcode']) && $product_data['market']['barcode']){
            $this->parameters['productSellerCode'] = $product_data['market']['barcode'];

        }else{
            $this->parameters['productSellerCode'] = $product_data['model'];

        }
        $result = $this->clientConnect($this->product_selling_service, 'StopSellingProductBySellerCode');

        if($result['status']){

            $result['message']='Ürün başarıyla Satışa Kapanmıştır.';
        }

        return $result;

    }
    public function open_for_sale($product_data, $api_info)
    {

        $this->parameters['auth'] = $api_info;
        if(isset($product_data['market']['barcode']) && $product_data['market']['barcode']){
            $this->parameters['productSellerCode'] = $product_data['market']['barcode'];

        }else{
            $this->parameters['productSellerCode'] = $product_data['model'];

        }
        $result = $this->clientConnect($this->product_selling_service, 'StartSellingProductBySellerCode');

        if($result['status']){

            $result['message']='Ürün başarıyla Satışa Açılmıştır.';
        }

        return $result;

    }

    private $attributes = array();


    public function get_all_api()
    {
        $auths=array();
        $query=$this->db->query("select * from ".DB_PREFIX."marketplace_user_api where code='n11'");

        foreach ($query->rows as $row) {

            $auths[]=unserialize($row['info']);

        }

        return $auths;

    }

    public function category_attributes($request_data, $api_info)
    {

        ini_set('max_execution_time', 0); //0=NOLIMIT
        ini_set('set_time_limit', 0); //0=NOLIMIT


        $api_info=array('appKey'=>'5c641417-58c2-4e14-92a9-1f8fde99ffcc','appSecret'=>'A9O6QHjxwmrnvuCD');

        $total_page = 1;
        $attributes_data = array();

        //$api_infos=$this->get_all_api();
        $this->parameters['auth'] = $api_info;



        $category_id=isset($request_data['category_id'])?$request_data['category_id']:$request_data;

        $get_attributes_info = $this->getAttr($category_id, 1);




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

        } else {
            $total_page = $get_attributes_info['result']['category']['metadata']['pageCount'];

            // echo $total_page;
            if ($total_page > 1) {
                $this->renderAttributes($get_attributes_info['result']['category']['attributeList']);

                for ($i = 2; $i <= $total_page; $i++) {

                    $attributes_info = $this->getAttr($category_id, $i);

                    if (isset($attributes_info['result']['category']['attributeList'])) {

                        $this->renderAttributes($attributes_info['result']['category']['attributeList']);
                    }

                    if ($i > 14)break;

                }
            } else {

                $this->renderAttributes($get_attributes_info['result']['category']['attributeList']);
            }
        }


        return array('status' => $get_attributes_info['status'], 'message' => $get_attributes_info['message'], 'result' => $this->attributes);

    }

    public function renderAttributes($attributes)
    {

        ini_set('max_execution_time', 0); //0=NOLIMIT
        ini_set('set_time_limit', 0); //0=NOLIMIT
        $attribute_list = array();
        if (isset($attributes['attribute']['id'])) {
            $attribute = $attributes['attribute'];
            if (!isset($this->attributes[$attribute['id']])) {

                $values=array();
                if(isset($attribute['valueList']['value']['id'])){
                    $values[]=$attribute['valueList']['value'];
                }else {
                    $values=$attribute['valueList']['value'];

                }
                $this->attributes[$attribute['id']] = array(
                    'attribute_id' => $attribute['id'],
                    'name' => $attribute['name'],
                    'required' => (int)$attribute['mandatory'],
                   // 'multiple' => (int)$attribute['multipleSelect'],
                    'values' => $values
                );
            }else {

                foreach ($attribute['valueList']['value'] as $value) {

                    $this->attributes[$attribute['id']]['values'][] = $value;

                }
            }


        } else {



            foreach ($attributes['attribute'] as $attribute) {

                if (!isset($this->attributes[$attribute['id']])) {

                    $values=array();
                    if(isset($attribute['valueList']['value']['id'])){
                        $values[]=$attribute['valueList']['value'];
                    }else {
                        $values=$attribute['valueList']['value'];

                    }

                    $this->attributes[$attribute['id']] = array(
                        'attribute_id' => $attribute['id'],
                        'name' => $attribute['name'],
                        'required' => (int)$attribute['mandatory'],
                       // 'multiple' => (int)$attribute['multipleSelect'],
                        'values' => $values

                    );
                } else {

                    foreach ($attribute['valueList']['value'] as $value) {

                        $this->attributes[$attribute['id']]['values'][] = $value;

                    }
                }
            }

        }

        //return $attribute_list;
    }

    public function getAttr($category_id, $page)
    {
        $this->parameters['categoryId'] = $category_id;
        $this->parameters['pagingData'] = array('currentPage' => $page-1, 'pageSize' => 100);
        return $this->clientConnect($this->category_service, 'GetCategoryAttributes');
    }

    public function category_attribute_values($page = 0, $attribute_id)
    {

        self::$_parameters['categoryProductAttributeId'] = $attribute_id;
        $this->parameters['pagingData'] = array('currentPage' => $page, 'pageSize' => 100);
        $result = $this->clientConnect($this->category_service, 'GetCategoryAttributeValue');

    }


    public function get_product($product_data, $api_info)
    {
        $this->parameters['auth'] = $api_info;

        if(isset($product_data['product_id'])){
            $this->parameters['productId'] = $product_data['product_id'];

            return $this->clientConnect($this->product_service, 'GetProductByProductId');

        }else {

            $this->parameters['sellerCode'] = $product_data;

            return $this->clientConnect($this->product_service, 'GetProductBySellerCode');
        }

    }


    public function update_fast($products, $api_info, $mode = false)
    {



        $this->parameters['auth'] = $api_info;
        $result=array();


        foreach ($products as $product) {

            $stockItems = array();


            $stockItems[] = array(
                'id' => $product['marketplace_product_id'],
                'sellerStockCode' => $product['barcode'],
                'quantity' => $product['quantity'] > 0 ? $product['quantity']:0,
                'optionPrice' => $this->priceControl($product['listPrice'])
            );

            $discount = array();
            if (isset($product['sale_price'])) {

                $discount['discountType'] = 3;
                $discount['discountValue'] = (double)$this->priceControl($product['salePrice']);
                $discount['discountStartDate'] = (string)'';
                $discount['discountEndDate'] = (string)'';

            } else {

                $discount['discountType'] = 1;
                $discount['discountValue'] = (double)'';
                $discount['discountStartDate'] = (string)'';
                $discount['discountEndDate'] = (string)'';


            }
            $update_data = array(
                'productId' =>$product['marketplace_product_id'],
                'productSellerCode' => $product['barcode'],
                'currencyType' => 1,
                'title'=>'',//$product_info['title'],
                'price' => (double)$this->priceControl($product['listPrice']),
                'productDiscount' => $discount,
                'stockItems' => $stockItems,
                'description' => (string)'',//html_entity_decode($product_info['description']),
                'images' => array()//$product_info['images']
            );


            //print_r($product);
             //print_r($update_data);return;

            $this->parameters = array_merge($this->parameters, $update_data);


            $res = $this->clientConnect($this->product_service, 'UpdateProductBasic');


            if($res['status']){

                // $result['message']='Ürün başarıyla güncellenmiştir';

            }else {

                $result[$product['stock_code']] = $res['message'];

            }


        }


        return array('status'=>true,'message'=>'','result'=>$result);
    }


    public function update_all($product_info, $api_info)
    {

        $this->parameters['auth'] = $api_info;

        $product_data= unserialize($product_info['n11']);

        $productMainId=isset($product_data['product_setting']['n11_product_code'])?$product_data['product_setting']['n11_product_code']?$product_data['product_setting']['n11_product_code']:$product_info['model']:$product_info['model'];

        $defaults = isset($product_data['defaults'])?$product_data['defaults']:array();
        $stockItems = array();



        $stockItems[] = array(
            'id' => isset($product_data['stock_id'])?$product_data['stock_id']?$product_data['stock_id']:null:null,
            'sellerStockCode' => (String)isset($product_data['stock_id'])?$product_data['stock_id']?$product_data['stock_id']:$productMainId:$productMainId,
            'quantity' => $product_info['quantity'] > 0 ? $product_info['quantity']:0,
            'optionPrice' => $this->priceControl($product_info['list_price'])
        );


        $discount = array();
        if ($product_info['sale_price'] < $product_info['list_price']) {

            $discount['discountType'] = 3;
            $discount['discountValue'] = (double)$this->priceControl($product_info['sale_price']);
            $discount['discountStartDate'] = (string)'';
            $discount['discountEndDate'] = (string)'';

        } else {

            $discount['discountType'] = 1;
            $discount['discountValue'] = (double)'';
            $discount['discountStartDate'] = (string)'';
            $discount['discountEndDate'] = (string)'';


        }

        if(isset($product_info['product_setting']['n11_product_title'])){

            $product_info['title']=  $product_info['product_setting']['n11_product_title'];
        }
        if(isset($product_info['product_setting']['n11_product_subtitle'])){

            $product_info['subtitle']=  $product_info['product_setting']['n11_product_subtitle'];
        }else {

            $product_info['subtitle']=  $product_info['title'];
        }

        $title=array();

        if(isset($product_data['attributes'])){


            if($product_data['attributes']){

                foreach ( $product_data['attributes'] as $item) {

                    if($item['name']=='Cinsiyet'){
                        $title[]=$item['value'];
                    }
                }

            }  }

        if($title){
            $product_info['title']=implode(' ',$title).' '.$product_info['title'];
        }


        $description =$product_info['description'] ? $product_info['description'] : $product_info['title'];



        $subtitle=isset($product_info['product_setting']['n11_product_subtitle']) ?  mb_substr($product_info['product_setting']['n11_product_subtitle'], 0, 65) : mb_substr($product_info['title'], 0, 65);
        $product_info['title'] = str_replace('<', '-', $product_info['title']);
        $product_info['title'] = str_replace('>', '-', $product_info['title']);
        // $product_data['model']='34543ffd';

        $update_data = array(
            'productId' =>isset($product_data['product_id'])? $product_data['product_id']:null,
            'productSellerCode' => (string)isset($product_data['product_id'])?'':$productMainId,
            'currencyType' => 1,
            'title'=>$product_info['title'],
            'subtitle' =>html_entity_decode($subtitle) ,
            'price' => (double)$this->priceControl($product_info['list_price']),
            'productDiscount' => $discount,
            'stockItems' => $stockItems,
            'description' => (string)html_entity_decode($description),
            'images' => $product_info['images']
        );




        if(isset($product_info['variants']['variants'])) {


            if ($product_info['variants']) {

                $variants=$this->getVariants($product_info['variants']['variants'],$productMainId,$product_info['list_price'],true);
                $update_data['stockItems'] = $variants;


            }

        }



        //print_r($update_data); return;
        $this->parameters = array_merge($this->parameters, $update_data);

        return $this->clientConnect($this->product_service, 'UpdateProductBasic');

    }

    public function update_basic($product_info, $api_info)
    {


        $this->parameters['auth'] = $api_info;

        $product_data= unserialize($product_info['n11']);

        $productMainId=isset($product_data['product_setting']['n11_product_code'])?$product_data['product_setting']['n11_product_code']?$product_data['product_setting']['n11_product_code']:$product_info['model']:$product_info['model'];


        $stockItems = array();



        $stockItems[] = array(
            'id' => isset($product_data['stock_id'])?$product_data['stock_id']?$product_data['stock_id']:null:null,
            'sellerStockCode' => (String)isset($product_data['stock_id'])?$product_data['stock_id']?$product_data['stock_id']:$productMainId:$productMainId,
            'quantity' => $product_info['quantity'] > 0 ? $product_info['quantity']:0,
            'optionPrice' => $this->priceControl($product_info['list_price'])
        );


        $discount = array();
        if ($product_info['sale_price'] < $product_info['list_price']) {

            $discount['discountType'] = 3;
            $discount['discountValue'] = (double)$this->priceControl($product_info['sale_price']);
            $discount['discountStartDate'] = (string)'';
            $discount['discountEndDate'] = (string)'';

        } else {

            $discount['discountType'] = 1;
            $discount['discountValue'] = (double)'';
            $discount['discountStartDate'] = (string)'';
            $discount['discountEndDate'] = (string)'';


        }





        $update_data = array(
            'productId' =>isset($product_data['product_id'])? $product_data['product_id']:null,
            'productSellerCode' => (string)isset($product_data['product_id'])?'':$productMainId,
            'currencyType' => 1,
            'title'=>'',//$product_info['title'],
            'price' => (double)$this->priceControl($product_info['list_price']),
            'productDiscount' => $discount,
            'stockItems' => $stockItems,
            'description' => (string)'',//html_entity_decode($product_info['description']),
            'images' => array()//$product_info['images']
        );




        if(isset($product_info['variants']['variants'])) {


            if ($product_info['variants']) {

                $variants=$this->getVariants($product_info['variants']['variants'],$productMainId,$product_info['list_price'],true);
                $update_data['stockItems'] = $variants;


            }

        }




        $this->parameters = array_merge($this->parameters, $update_data);


        $result = $this->clientConnect($this->product_service, 'UpdateProductBasic');

        if($result['status']){

            $result['message']='Ürün başarıyla güncellenmiştir';
        }

        return  $result;



    }


    public function update_stock($product_info, $api_info)
    {

        echo 'OK!';
        print_r($product_info);

    }

    public function updateProductStock($data)
    {
        $this->parameters['stockItems'] = $data;
        return $this->clientConnect($this->product_stock_service, 'UpdateStockByStockSellerCode');

    }


    public function updateProductPrice($stockItems)
    {
        $this->parameters['stockItems'] = $stockItems;
        return $this->clientConnect($this->product_stock_service, 'UpdateStockByStockSellerCode');

    }


    public function get_products($product_info, $api_info)
    {

        $this->parameters['auth'] = $api_info;
        $this->parameters['pagingData'] = array('itemsPerPage' => $product_info['itemcount'], 'currentPage' => $product_info['page']);
        $result = $this->clientConnect($this->product_service, 'GetProductList',true);
        // return $result;

        // $result['result']['products']['product'][$index]['images']=$images;
        $products=array();

        //print_r($result['result']['products']['product']);return;

        foreach ($result['result']['products']['product'] as $index => $product) {
            //$this->parameters['productId'] = $product['id'];
            $images=array();
            // $getProductInfo=$this->clientConnect($this->product_service, 'GetProductByProductId');

            //  $image=$getProductInfo['result']['product']['images'];

            /*  if(isset($image['image']['url'])){
                  $images[]=$image['image']['url'];
              }else {
                  foreach ($image['image'] as $image) {

                      $images[]=$image['url'];

                  }
            */

            $images[]='';
            $result['result']['products']['product'][$index]['images']=$images;

        }


        //}


        return $result;

    }

    public function get_orders($data, $api_info)
    {



        $order_list = array();
        $this->parameters['auth'] = $api_info;
        $this->parameters['searchData'] = $data['filter_data'];
        $this->parameters['searchData']['sortForUpdateDate'] = false;
        $this->parameters['pagingData'] = $data['paging_data'];


        $result = $this->clientConnect($this->order_service, 'OrderList');



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

            if($result['result']['pagingData']['totalCount']>1){
                foreach ($result['result']['orderList']['order'] as $item) {


                    $order = $this->getOrderInfo($item['id']);


                    $order_list[] = $order['result']['orderDetail'];

                }
            }else if($result['result']['pagingData']['totalCount']==1){


                $item=$result['result']['orderList']['order'];

                $order = $this->getOrderInfo($item['id']);
                $order_list[] = $order['result']['orderDetail'];


            }

        }

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

    }


    public function getOrderInfo($order_id)
    {
        $this->parameters['orderRequest'] = array('id' => $order_id);
        return $this->clientConnect($this->order_service, 'OrderDetail');

    }
    public function search_catalog($request_data, $api_info)
    {
        $this->parameters['auth'] = $api_info;
        $this->parameters['productTitles'] = "Filli Boya İndeko-Home Küf Önleyici İç Cephe Boyası";
        $this->parameters['categoryId'] = 1000001832;
        $this->parameters['uscs'] = "";
        $this->parameters['brandName'] = "";
        $this->parameters['catalogIds'] = "";
        $this->parameters['currentPage'] = 0;



        $result = $this->clientConnect($this->catalog_service, 'SearchCatalog');

        return array('status' => true, 'message' => '', 'result' => $result);


    }

    public function get_questions($product_data, $api_info)
    {


        $this->parameters['auth'] = $api_info;
        $status='OPEN';
        $searchData=array(
            'productId'=>null,
            'buyerEmail'=>'',
            'subject'=>'',
            'status'=>$status,
            'questionDate'=>'',
            'startDate'=>'',
            'endDate'=>''
        );
        $pagingData = array(
            'currentPage'=>0,
            'pageSize'=>rand(10,99),
            'totalCount'=>100,
            'pageCount'=>null
        );


        $this->parameters['productQuestionSearch'] =$searchData;
        $this->parameters['pagingData'] = $pagingData;

        // return;

        $result = $this->clientConnect($this->product_service, 'GetProductQuestionList');

        return array('status' => true, 'message' => '', 'result' => $result);

    }

    public function get_question($product_data, $api_info)
    {

        $this->parameters['auth'] = $api_info;



        $this->parameters['productQuestionId'] = $product_data;

        $result = $this->clientConnect($this->product_service, 'GetProductQuestionDetail');


        $result_data=array(
            'status'=>$result['productQuestion']['status'],
            'productTitle'=>$result['productQuestion']['productTitle'],
            'userName'=>'',
            'text'=>$result['productQuestion']['question'],
            'creationDate'=>$result['productQuestion']['questionDate'],
        );

        if(isset($result['productQuestion']['answer'])){

            $answered_data=array(
                'text'=>$result['productQuestion']['answer']
            );

            $result_data['answer']=$answered_data;

        }


        return array('status' => true, 'message' => '', 'result' => $result_data);

    }
    public function reply_question($product_data, $api_info)
    {

        $this->parameters['auth'] = $api_info;
        $this->parameters['productQuestionId'] = $product_data['question_id'];
        $this->parameters['answer'] = $product_data['text'];

        $result = $this->clientConnect($this->product_service, 'SaveProductAnswer');

        return array('status' => true, 'message' => '', 'result' => $result);

    }






}