<?php

namespace marketplace;


final class Pz
{

    private $registry, $db, $session, $url, $config, $log, $customer, $currency, $tax, $token, $error, $username, $password, $parameters;

    private $merchant_id;
    private $client;

    public function __construct($registry)
    {
        $this->db = $registry->get('db');
        $this->config = $registry->get('config');
        $this->session = $registry->get('session');
        $this->url = $registry->get('url');
        $this->config = $registry->get('config');
        $this->log = $registry->get('log');
        $this->customer = $registry->get('customer');
        $this->currency = $registry->get('currency');
        $this->tax = $registry->get('tax');
        $this->registry = $registry;


    }

    private function login($api_info)
    {
        $this->client = new \bluntk\Pazarama([
            'api_key' => $api_info['username'],
            'api_secret' => $api_info['password']
        ]);
    }

    public function checkApi($params)
    {

        $this->login($params);
        $token = $this->client->getAuthToken();


        return array('status' => $token->success, 'message' => $token->success ? 'Pazarama api bilgileriniz başarıyla doğrulandı' : $token->message);
    }

    public function marka($api_info, $page)
    {
        $this->login($api_info);
        return json_decode(json_encode($this->client->brands($page, 1000)), 1);
    }

    public function sell_product($product, $api_info)
    {
        $this->login($api_info);

        $result = $this->client->createProduct($product);


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


        /*
                $track_id = '13dfec81-4752-4d14-ac32-e8f182320042';
                $check = $this->check_status($track_id, $api_info);

                print_r($check);
                return;
        */


    }


    public function get_unaproved_orders($product_data, $api_info)
    {

        $this->merchant_id = $api_info['merchant_id'];
        //$url = "https://oms-external.hepsiburada.com/orders/merchantid/".$this->merchant_id;
        //$url='https://oms-external.hepsiburada.com/orders/merchantid/ad905f66-9e62-4743-9d9b-2aa121ef1db1';
        $url = $this->orderUrl . "/orders/merchantid/" . $this->merchant_id; //. "?offset=0&limit=1";

        $result = json_decode($this->clientConnect($url, 'getOrders', $this->token, 'GET', null), true);


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

            if ($result['statusCode'] == 403) {

                $message = 'Girilen Merchant ID için miryazilim_dev entegratör firması yetkili değildir! Lütfen hepsiburada satıscı destek üzerinden durumu bildiriniz. ';
            } else {

                $message = 'Girilen Mercant ID bilgisi hatalıdır. Kontrol ederek tekrar deneyiniz. ';
            }

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

        }
        {

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

        }


        //return json_decode($result->response);
    }

    public function get_orders($product_data, $api_info)
    {


        //  date_default_timezone_set('Europe/Istanbul');
        $this->login($api_info);

        try {
            $result = $this->client->orders($product_data['request_data']['start_date'], $product_data['request_data']['end_date']);
            return array('status' => true, 'message' => '', 'result' => json_decode(json_encode($result), 1));
        } catch (\Exception $exception) {
            echo $exception->getMessage();
        }


    }


    public function get_order_and_make_package($api_info)
    {
        $this->merchant_id = $api_info['merchant_id'];


        $order_url = $this->orderUrl . "/orders/merchantid/" . $this->merchant_id; //. "?offset=0&limit=1"

        $orders = json_decode($this->clientConnect($order_url, 'getOrders', $this->token, 'GET', null), true);


        if (!isset($orders['statusCode'])) {

            foreach ($orders['items'] as $item) {


                $order_url = $this->orderUrl . "/orders/merchantid/" . $this->merchant_id . "/ordernumber/" . $item['orderNumber'];

                $order_detail = json_decode($this->clientConnect($order_url, 'getOrders', $this->token, 'GET', null), true);


                $lineItemRequests = array();

                foreach ($order_detail['items'] as $product) {

                    $lineItemRequests[] = array(

                        'id' => $product['id'],
                        'quantity' => $product['quantity']

                    );

                }
                $packages = array('lineItemRequests' => $lineItemRequests);

                $data =


                $url = $this->orderUrl . "/packages/merchantid/" . $this->merchant_id;


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

                $headers = array(
                    'Authorization: Basic ' . base64_encode($this->username . ':' . $this->password),
                    "Content-Type: application/json",
                );


                curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

                $data = json_encode($packages);

                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

//for debug only!
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

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


            }


        }


    }

    public function update_basic($product_data, $api_info)
    {


        $this->merchant_id = $api_info['merchant_id'];

        $hb_data = unserialize($product_data['hb']);

        $productMainId = isset($product_data['product_setting']['hb_product_code']) ? $product_data['product_setting']['hb_product_code'] ? $product_data['product_setting']['hb_product_code'] : $product_data['model'] : $product_data['model'];
        // $barcode_ecx=isset($product_data['product_setting']['hb_barcode'])?$product_data['product_setting']['hb_barcode']?$product_data['product_setting']['hb_barcode']:$product_data['model']:$product_data['model'];
        // $barcode=isset($marketplace_data['barcode'])?$hb_data['barcode']:$barcode_ecx;

        /*print_r($hb_data);

                print_r($product_data);
                return;
*/


        //$product_data['sale_price']=999;
        if (isset($product_data['defaults']['setting_update_value'])) {
            if ($product_data['defaults']['setting_update_value'] == 2) {
                //sadece stok güncellenecek
                $product_data['sale_price'] = "";
            }
            if ($product_data['defaults']['setting_update_value'] == 1) {
                //sadece fiyat güncelllenecek
                $product_data['quantity'] = "";

            }
        }

        $shipping_time = isset($product_data['defaults']['shipping_time']) ? $product_data['defaults']['shipping_time'] : 0;

        $maximum_order = isset($product_data['defaults']['maximum_order']) ? $product_data['defaults']['maximum_order'] ? $product_data['defaults']['maximum_order'] : 0 : 0;


        $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
        $xml .= "<listings xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n";
        //print_r($product_data['variants']);
        //return ;

        /*    if(isset($product_data['variants']['message'])){
                return array('status' => false, 'message' => $product_data['variants']['message'],'result'=>array());

            }*/


        if ($product_data['variants']) {

            if ($product_data['variants']['variants']) {
                foreach ($product_data['variants']['variants'] as $variant) {


                    if ($variant['model']) {

                        $xml .= "<listing>\n";
                        //$xml .= "<HepsiburadaSku>" . $variant['hbsku'] . "</HepsiburadaSku>";
                        $xml .= "<MerchantSku>" . $variant['model'] . "</MerchantSku>\n";
                        //  $xml .= "<HepsiburadaSku>HBV000013F5FP</HepsiburadaSku>";
                        // $xml .= "<MerchantSku>4353456KIRMIZI42</MerchantSku>";
                        // $xml .= "<ProductName>" . $product_data['title'] . "</ProductName>";
                        $xml .= "<Price>" . $this->priceFormat($product_data['sale_price'] + $variant['price']) . "</Price>\n";
                        $xml .= "<AvailableStock>" . (int)$variant['quantity'] . "</AvailableStock>\n";
                        $xml .= "<DispatchTime>" . $shipping_time . "</DispatchTime>\n";
                        $xml .= "<MaximumPurchasableQuantity>" . $maximum_order . "</MaximumPurchasableQuantity>\n";

                        $xml .= "</listing>\n";


                    } /*else {

                        $xml .= "<listing>";
                        $xml .= "<HepsiburadaSku>" . $hb_data['product_id'] . "</HepsiburadaSku>\n";
                        $xml .= "<MerchantSku>" . $productMainId . $variant['prefix'] . "</MerchantSku>\n";
                        // $xml .= "<ProductName>" . $product_data['title'] . "</ProductName>\n";
                        $xml .= "<Price>" . $this->priceFormat($product_data['sale_price'] + $variant['price']) . "</Price>\n";
                        $xml .= "<AvailableStock>" . (int)$product_data['quantity'] . "</AvailableStock>\n";
                        $xml .= "<DispatchTime>" . $shipping_time . "</DispatchTime>\n";
                        $xml .= "<MaximumPurchasableQuantity>" . $maximum_order . "</MaximumPurchasableQuantity>\n";

                        $xml .= "</listing>\n";

                    }*/


                }

            } else {


                $xml .= "<listing>\n";
                // $xml .= "<HepsiburadaSku>" . $hb_data['product_id'] . "</HepsiburadaSku>\n";
                $xml .= "<MerchantSku>" . trim($productMainId) . "</MerchantSku>\n";
                //$xml .= "<ProductName>".$product_data['title']."</ProductName>\n";
                $xml .= "<Price>" . $this->priceFormat($product_data['sale_price']) . "</Price>\n";
                $xml .= "<AvailableStock>" . (int)$product_data['quantity'] . "</AvailableStock>\n";
                $xml .= "<DispatchTime>" . $shipping_time . "</DispatchTime>\n";
                $xml .= "<MaximumPurchasableQuantity>" . $maximum_order . "</MaximumPurchasableQuantity>\n";
                $xml .= "</listing>\n";

            }

        } else {


            $xml .= "<listing>\n";
            //$xml .= "<HepsiburadaSku>" . $hb_data['product_id'] . "</HepsiburadaSku>\n";
            $xml .= "<MerchantSku>" . trim($productMainId) . "</MerchantSku>\n";
            //$xml .= "<ProductName>".$product_data['title']."</ProductName>\n";
            $xml .= "<Price>" . $this->priceFormat($product_data['sale_price']) . "</Price>\n";
            $xml .= "<AvailableStock>" . (int)$product_data['quantity'] . "</AvailableStock>\n";
            $xml .= "<DispatchTime>" . $shipping_time . "</DispatchTime>\n";
            $xml .= "<MaximumPurchasableQuantity>" . $maximum_order . "</MaximumPurchasableQuantity>\n";
            $xml .= "</listing>\n";

        }


        $xml .= "</listings>";


        // print_r($product_data);
        // echo $xml;
        // return;


        $service_url = 'https://listing-external.hepsiburada.com/listings/merchantid/' . strtolower($this->merchant_id) . '/inventory-uploads';
        $curl = curl_init($service_url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $xml);
        $header = array(
            'Authorization: Basic ' . base64_encode($this->username . ':' . $this->password),
            'Content-Type: application/xml'
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $curl_response = curl_exec($curl);
        $result = $this->xmlToArray($curl_response);
        // return array('status' => true, 'message' => 'Ürün başarıyla Güncellendi', 'result' => array());

        //  print_r($result);


        //$result['Id'] ="1ed3615f-e601-4db4-8ad3-2924e2be9fce";
        //sleep(1);

        if (isset($result['id'])) {
            $chech = $this->xmlToArray($this->chechUpdate($result['id'], $api_info));
            // print_r($chech);return;

            $message = '';
            if (isset($chech['Errors']['Error'])) {

                $status = false;
                // $message=;
                if (isset($chech['Errors']['Error']['Errors']['string'])) {
                    return array('status' => false, 'message' => $this->error_means($chech['Errors']['Error']['Errors']['string']), 'result' => array());

                } else {

                    $errors = array();
                    foreach ($chech['Errors']['Error'] as $error) {

                        $errors[] = "Ürün Kodu:" . $error['MerchantSku'] . "- Hata: " . $this->error_means($error['Errors']['string']);


                    }

                    return array('status' => false, 'message' => implode(",", $errors), 'result' => array());


                }

            } else {

                $status = true;


            }
        } else {

            return array('status' => false, 'message' => 'Güncelleme hatası', 'result' => array());

        }


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

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

        } else {
            return array('status' => true, 'message' => 'Ürün başarıyla Güncellendi', 'result' => array());

        }


    }


    private function error_means($code)
    {
        $means = array(
            'MismatchingSkusSpecified' => 'Girilen HBSku ve MerchantSku bilgileri yanlış eşleştirilmiş. Web sitenizden ve hepsiburada ürünler panelinden ürün kodunuzu kontrol ediniz.',
            'ProductNotFound' => 'Girilen HBSku bilgisi kataloğumuzda yer almıyor',
            'DuplicateHepsiburadaSkuSpecified' => 'Yollanılan XML dosyası ya da yüklenen excel dosyasının içerisinde birden fazla HBSku kodu bulunuyor',
            'InvalidPrice' => 'Fiyat bilgisi decimal dışında bir değer girildiği zaman alınan hatadır. Aynı zamanda fiyat bilgisi nokta ile yazıldığında da dönülmektedir.',
            'InvalidAvailableStock' => 'Stok bilgisi tam sayı dışında bir değer girildiği zaman alınan hatadır.',
            'InvalidDispatchTime' => 'Kargoya veriliş süresi tam sayı dışında bir değer girildiği zaman alınan hatadır.',
            'DiscountedListingPriceIncrease' => 'Kontrol edildiğinde ürün güncelleme işleminde ” Girilen Fiyat indirim süresince geçerli değerden daha yüksek ” olduğundan hata alınmıştır.',
            'MerchantAlreadyListedAgainstProduct' => 'Ürün mükerrer yaratılmış gözükmektedir. Bu yüzden ürünü güncelleyemiyorsunuz. Askıda olan ürünün silinmesi gereklidir.',
            'ListingDeletedRecently' => 'Silinmiş yada listingler arasında olmayan sku için güncelleme gönderilemez.',
            'ListingFrozen' => 'Kilitli listing için güncelleme yapılamaz.',
            'MissingStandardCargoCompany' => 'Listing güncellemede CargoCompany kısmında HepsiJet tek basına tanımlanamaz, HepsiJet ile birlikte standart bir kargo firması daha CargoCompany2 alanında tanımlanması gerekir.  Kargo firması bilgisinde HepsiJet tek kargo firması olarak gönderildiğinde MissingStandardCargoCompany uyarısı alınır.',
            'OutOfPriceRange' => 'Canlı sistemde yanlış fiyatlandırmalara karşı çalışan bir mekanizma bulunmaktadır. Listelenmiş yayındaki fiyatların en düşüğü ve en yükseği hariç diğerlerinin ortalaması alınarak 0-50 tl arası 200% 50-100 tl arası 100% 100-200 tl arası 70% 200-500 tl arası 50% 500 -2000 tl arası 40% 2000 plus 30% maximum fiyat girilebilir.',
            'restrictedProductBrand' => 'Bu ürün üzerinde marka kısıtı olduğu gözükmektedir. Bu ürünü satabilmek adına alınması gereken aksiyonlar bulunmaktadır. Kategori yöneticiniz ile iletişime geçerek bu kısıtın nasıl kaldırılacağını görüşebilirsiniz.'

        );

        if (isset($means[$code])) {
            return $means[$code];
        } else {
            return $code;
        }

    }

    public function chechUpdate($product_data, $api_info)
    {
        $service_url = 'https://listing-external.hepsiburada.com/listings/merchantid/' . strtolower($this->merchant_id) . '/inventory-uploads/id/' . $product_data;
        $curl = curl_init($service_url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt($curl, CURLOPT_POST, true);
        // curl_setopt($curl, CURLOPT_POSTFIELDS, $xml);
        $header = array(
            'Authorization: Basic ' . base64_encode($this->username . ':' . $this->password),
            'Content-Type: application/xml'
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $curl_response = curl_exec($curl);

        return $curl_response;


    }


    public function close_for_sale($products, $api_info)
    {

        $this->login($api_info);


        $stock_data = array();


        foreach ($products as $product) {


            $stock_data['items'][] = array(
                'code' => $product,
                'stockCount' => 0
            );


        }


        $result_stock = $this->client->updateStock($stock_data);

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


    }

    public function delete_product($products, $api_info)
    {

        $result = array();

        $this->merchant_id = $api_info['merchant_id'];

        if ($products) {

            foreach ($products as $product) {

                $service_url = 'https://listing-external.hepsiburada.com/Listings/merchantid/069fb762-b69d-4170-a1f6-ef6e165bb905/sku/' . $product['marketplace_product_id'] . '/merchantsku/' . $product['model'];

                $curl = curl_init();
                curl_setopt_array($curl, array(
                    CURLOPT_URL => $service_url,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'DELETE',
                    CURLOPT_HTTPHEADER => array(
                        'Authorization: Basic bWlyeWF6aWxpbV9kZXY6aHVtUSMyeWxU'
                    ),
                ));

                $response = json_decode(curl_exec($curl), 1);
                curl_close($curl);

                if ($response == 1) {

                } else if (isset($response['message'])) {
                    $result[$product['model']] = $response['message'];


                }


            }
        }


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


    }


    public function update_fast($products, $api_info, $mode = true)
    {
        $this->login($api_info);


        $stock_data = array();
        $price_data = array();

        //PZ PRODUCTS
        print_r($products);

        foreach ($products as $product) {


            $stock_data['items'][] = array(
                'code' => $product['barcode'],
                'stockCount' => $product['quantity']
            );

            $price_data['items'][] = array(
                'code' => $product['barcode'],
                'listPrice' => $product['listPrice'],
                'salePrice' => $product['salePrice']
            );
        }

       $result_stock = $this->client->updateStock($stock_data);
       $result_price = $this->client->updatePrice($price_data);


       print_r($result_price);
       print_r($result_stock);



    }

    public function open_for_sale($market_product_id, $api_info)
    {


        $this->merchant_id = $api_info['merchant_id'];

        if ($market_product_id) {
            $service_url = $this->listUrl . "/listings/merchantid/" . strtolower($this->merchant_id) . "/sku/" . $market_product_id . "/activate";
            $curl = curl_init($service_url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, 'kljcklvj');
            $header = array(
                'Authorization: Basic ' . base64_encode($this->username . ':' . $this->password),
                'Content-Type: application/xml'
            );
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            $curl_response = curl_exec($curl);
            //print_r($curl_response);

        }

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


    }


    public function checkbarcode($str)
    {

        return str_replace(' ', '', $str);

    }


    public function add_product($product_data, $api_info)
    {


        $this->merchant_id = $api_info['merchant_id'];

        $this->getToken();

        $merchant = $this->merchant_id;


        $products = array();

        $description = str_replace(array('<![CDATA[', ']]>'), '', html_entity_decode($product_data['description'], ENT_QUOTES, 'UTF-8'));
        $product_data['title'] = str_replace('<', '-', $product_data['title']);
        $product_data['title'] = $product_data['manufacturer_name'] . ' ' . str_replace('>', '-', $product_data['title']);


        if ($product_data['variants']) {

            foreach ($product_data['variants'] as $variant) {


                $product = array(
                    "categoryId" => $product_data['category_id'],
                    "merchant" => $this->merchant_id,
                    "attributes" => array(
                        "merchantSku" => $variant['stock_code'],
                        "price" => $this->priceFormat($product_data['sale_price']),
                        "stock" => (string)$variant['quantity'],
                        "VaryantGroupID" => $product_data['model'],
                        "Barcode" => $this->checkbarcode($variant['barcode']),
                        "UrunAdi" => $product_data['title'],
                        "UrunAciklamasi" => $description,
                        "Marka" => $product_data['manufacturer_name'],
                        "GarantiSuresi" => 24,
                        "kg" => 1,
                        "tax_vat_rate" => (int)isset($product_data['kdv']) ? $product_data['kdv'] : 18,

                    )
                );
                foreach ($product_data['defaults']['selected_attributes'] as $attribute) {
                    $product['attributes'][$attribute['market_attribute_id']] = trim($attribute['attribute_value_name']);
                }


                foreach ($variant['variant_values'] as $attribute) {
                    $product['attributes'][$attribute['market_attribute_id']] = trim($attribute['name']);
                }


                if ($variant['image']) {
                    $product['attributes']['Image1'] = $variant['image'];
                }

                foreach ($product_data['images'] as $key => $image) {
                    if ($key <= 5) {
                        $product['attributes']['Image' . ($key + 1)] = $image;
                    }
                }


                $products[] = $product;
            }

        } else {
            $product = array(
                "categoryId" => $product_data['category_id'],
                "merchant" => $this->merchant_id,
                "attributes" => array(
                    "merchantSku" => $product_data['model'],
                    "VaryantGroupID" => $product_data['model'],
                    "Barcode" => $this->checkbarcode($product_data['barcode']),
                    "price" => $this->priceFormat($product_data['sale_price']),
                    "stock" => (string)$product_data['quantity'],
                    "UrunAdi" => $product_data['title'],
                    "UrunAciklamasi" => $description,
                    "Marka" => $product_data['manufacturer_name'],
                    "GarantiSuresi" => 24,
                    "kg" => 1,
                    "tax_vat_rate" => (int)isset($product_data['kdv']) ? $product_data['kdv'] : 18,

                )
            );

            foreach ($product_data['defaults']['selected_attributes'] as $attribute) {

                $product['attributes'][$attribute['market_attribute_id']] = $attribute['attribute_value_name'];
            }


            foreach ($product_data['images'] as $key => $image) {
                if ($key <= 5) {
                    $product['attributes']['Image' . ($key + 1)] = $image;
                }
            }

            $products[] = $product;


        }

        //print_r($products);return;
        /*
                        $track_id='f75e2995-df20-4b5f-ad3f-8678645ed394';
                        $check = $this->check_status($track_id,$api_info);
                        print_r($check);
                        return;

        */


//print_r($result);return ;
        $result = $this->product_send($this->token, json_encode($products));


        /*
                $track_id = '13dfec81-4752-4d14-ac32-e8f182320042';
                $check = $this->check_status($track_id, $api_info);

                print_r($check);
                return;
        */

        if ($result['success']) {

            $track_id = $result['data']['trackingId'];
            sleep(1);
            $check = $this->check_status($track_id, $api_info);


            if ($check['status']) {
                $check['result']['trackingId'] = $track_id;
                return $check;

            } else {

                return $check;
            }


        } else {

            return array('status' => false, 'message' => 'hesap bilgileriniz hatalıdır', 'result' => array());


        }


    }

    private function priceFormat($price)
    {

        return str_replace('.', ',', $price);
    }


    public function get_products($product_data, $api_info)
    {
        $this->login($api_info);




        $result = $this->client->products($product_data['approved'], null, 100, ($product_data['page'] + 1));


 

        return json_decode(json_encode($result), 1);


    }

    public function check_status($product_data, $api_info)
    {
        $this->merchant_id = $api_info['merchant_id'];
        $this->getToken();
        $errors = array();
        $warning = array();

        $status = false;


        if ($this->token) {
            $status = true;
            $url = $this->katalog_url . '/product/api/products/status/' . $product_data;

            $result = $this->clientConnect($url, 'getAttributes', $this->token);


            if ($result['success']) {
                if ($result['data'][0]['validationResults']) {

                    foreach ($result['data'][0]['validationResults'] as $key => $validationResult) {

                        $warning[] = $validationResult['attributeName'] . '-' . $validationResult['message'];

                    }


                    $status = true;

                }

                if ($result['data'][0]['importStatus'] == 'FAILED') {

                    foreach ($result['data'][0]['importMessages'] as $importMessage) {
                        $errors[] = $this->replace_errorrs($importMessage['message']);

                    }

                }

            }

            if (isset($result['data'][0]['taskDetails'])) {
                if ($result['data'][0]['taskDetails']) {
                    foreach ($result['data'][0]['taskDetails'] as $taskDetail) {
                        // $errors[] = 'Ürününüz Hepsiburadada Mevcut ve ürün durumu ' . $result['data'][0]['productStatus'] . ' olarak güncellenmiş. - Şu sorundan dolayı bildirim açılmış.' . $this->replace_errorrs($taskDetail['reason'] . ' Hepsiburada panelinize giriş yaparak sorunu gidermeniz gerekiyor.');
                    }

                }
            }


            if ($errors) {
                return array('status' => false, 'message' => implode('-', $errors), 'result' => array('product_status' => $result['data'][0]['productStatus'], 'errors' => $warning));

            } else {

                return array('status' => $result['success'], 'message' => $result['message'], 'result' => array('product_status' => $result['data'][0]['productStatus'], 'errors' => $warning));

            }

        } else {

            return array('status' => false, 'message' => 'hata alındı', 'result' => array());

        }
    }

    public function replace_errorrs($error)
    {

        $error_message = '';
        if ($this->findInStr($error, 'Barcode must be unique')) {

            $error_message = 'Barkod numaranız benzersiz olmalıdır, girdiğiniz barkod ile kayıtlı ürün bulunmaktadır.';

        } else if ($this->findInStr($error, 'update product in matched')) {
            $error_message = "Ürününüz hepsiburada kataloğunda mevcuttur, onaylandığında satışa açaılacaktır.";

        } else {

            $error_message = $error;
        }

        return $error_message;
    }


    public function findInStr($samanlik, $igne)
    {

        if (strpos($samanlik, $igne) === false) {

            return false;

        } else {
            return true;
        }

    }


    private function xmlToArray($xmlString)
    {

        // echo $xmlString;
        // return;
        //   $xml = simplexml_load_string($xmlString, "SimpleXMLElement", LIBXML_NOCDATA);


        //echo $xml;
        //$json = json_encode($xmlString);


        return json_decode($xmlString, TRUE);
    }


    public function getToken()
    {

        $connect = $this->clientConnect($this->katalog_url . 'api/authenticate');

        $this->token = $connect['id_token'];
        // echo 'intoken:'.time().'<br>';
    }

    public function get_all_categories()
    {
        $this->getToken();
        $url = 'https://mpop.hepsiburada.com/product/api/categories/get-all-categories?leaf=true&status=ACTIVE&available=true&page=0&size=20000&version=1';
        //  $url = $this->katalog_url . '/product/api/categories/get-all-categories?page=' . $page . '&size=' . $size . '';
        $result = $this->clientConnect($url, 'getCategories', $this->token);

        print_r($result);
    }

    public function getCategories($page, $size)
    {
        $this->getToken();

        $result = array();
        if ($this->token) {
            $url = 'https://mpop.hepsiburada.com/product/api/categories/get-all-categories?leaf=true&status=ACTIVE&available=true&page=' . $page . '&size=2000&version=1';
            //$url = $this->katalog_url . '/product/api/categories/get-all-categories?page=' . $page . '&size=' . $size . '';
            $result = $this->clientConnect($url, 'getCategories', $this->token);
            if ($result['success']) {
                $status = true;

            } else {
                $status = false;
                $this->error[] = $result['message'];
            }


        } else {
            $status = false;
            $this->error[] = 'Token Verisi Alınamadı. Tekrar Deneyiniz';
        }


        return array('status' => $status, 'message' => $this->error, 'data' => $result);

    }

    public function category_attributes($request_data, $api_info, $debug = false)

    {

        error_reporting(E_ALL);
        ini_set("display_errors", 1);
        set_time_limit(0);
        ini_set("memory_limit", '-1');
        ini_set('max_execution_time', 118000);


        $category_id = $request_data;// 703
        $this->login($api_info);
//echo $this->token;
        $result = array();
        $attributes = array();


        $status = true;
        $result = json_decode(json_encode($this->client->categoryWithAttributes($category_id)), 1);


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

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

                //if($attribute['mandatory']) {
                $attributes[] = array(
                    'id' => $attribute['id'],
                    'name' => $attribute['name'],
                    'values' => $attribute['attributeValues'],// $attribute['type'] == 'enum' ? $this->getAttributeValues($category_id, $attribute['id'], $debug)['data'] : array(),
                    'varianter' => $attribute['isVariantable'],
                    'required' => $attribute['isRequired'],
                );
                // }
            }

            $status = true;

        } else {

            $status = false;

        }


        if ($debug) {
            return;
        }

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

    }


    public function getAttributeValues($category_id = 703, $attribute_id, $debug = false)
    {


        $result = array();
        if ($this->token) {
            $status = true;
            $url = $this->katalog_url . '/product/api/categories/' . $category_id . '/attribute/' . $attribute_id . '/values/?page=0&size=1000&version=4';

            $result = $this->clientConnect($url, 'getAttributes', $this->token);


            $values = array();

            if ($result['totalPages'] > 1) {

                foreach ($result['data'] as $datum) {
                    $values[] = $datum['value'];
                }
                $totalpages = $result['totalPages'];

                for ($i = 1; $i < $totalpages; $i++) {
                    $url = $this->katalog_url . '/product/api/categories/' . $category_id . '/attribute/' . $attribute_id . '/values/?page=' . $i . '&size=1000&version=4';

                    $result = $this->clientConnect($url, 'getAttributes', $this->token);

                    //$values= array_merge($values,$result['data']);
                    foreach ($result['data'] as $datum) {
                        $values[] = $datum['value'];
                    }


                }

            } else {
                //  $values= array_merge($values,$result['data']);
                foreach ($result['data'] as $datum) {
                    $values[] = $datum['value'];
                }

            }

            if ($debug) {

                print_r($result);
            }


            if ($result['success']) {
                $status = true;

            } else {
                $status = false;
                $this->error[] = $result['message'];
            }

        } else {
            $status = false;
            $this->error[] = 'Token Verisi Alınamadı. Tekrar Deneyiniz';
        }


        return array('status' => $status, 'message' => $this->error, 'data' => $values);

    }


    public function product_send($token, $json)
    {
        $url = $this->katalog_url . 'product/api/products/import';
        $uid = uniqid();
        $cid = uniqid();

        $curlPost = "------WebKitFormBoundary$uid\r\n";
        $curlPost .= "Content-Disposition: form-data; name=\"file\"; filename=\"doc.json\"\r\n";
        $curlPost .= "Content-Type: application/json\r\n\r\n";
        $curlPost .= $json . "\r\n";
        $curlPost .= "------WebKitFormBoundary$uid--\r\n";


        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_ENCODING, "");
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        //curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER,//$churlPost
            array(//$churlPost
                'Content-Type: multipart/form-data; boundary=----WebKitFormBoundary' . $uid,
                'Authorization: Bearer ' . $token,
                'Accept: application/json',
                'Cookie: JSESSESSID=' . $cid . '; JSESSIONID=' . $cid,
                'Cache-Control: no-cache',
                'Content-Length: ' . strlen($curlPost)
            )
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $_content = curl_exec($ch);
        curl_close($ch);

        return json_decode($_content, 1);
    }


    protected function clientConnect($url, $request_type = 'login', $token = '', $method = 'POST', $content_type = 'JSON', $jsondata = '')
    {
        $login_post = [
            'username' => $this->username,
            'password' => $this->password,
            'authenticationType' => 'INTEGRATOR'
        ];


        /*   $login_post = [
               'username' => 'miryazilim1_dev',
               'password' => 'Hb12345!',
               'authenticationType' => 'INTEGRATOR'
           ];
   */
        /*  $login_post = [
                 'username' => 'egitimsetleri_dev',
                 'password' => 'IoqBXymhgAOurc!',
                 'authenticationType' => 'INTEGRATOR'
             ];*/


        $ch = curl_init($url);
        if ($method == 'POST') {
            $header = array('Content-Type: application/json', 'Authorization:Bearer ' . $token . '');
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        }

        if ($request_type == 'login') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($login_post));
        }

        if ($method == 'GET') {

            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
            curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);

        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);


        $result = curl_exec($ch);


        if ($content_type == 'JSON') {
            return json_decode($result, true);

        } else {

            return $result;

        }


    }


    public function getGuid()
    {
        if (function_exists('com_create_guid') === true) {
            return trim(com_create_guid(), '{}');
        }

        return strtolower(sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)));
    }

    public function toXml($data, $rootNodeName = 'data', $xml = null)
    {
        // turn off compatibility mode as simple xml throws a wobbly if you don't.
        if (ini_get('zend.ze1_compatibility_mode') == 1) {
            ini_set('zend.ze1_compatibility_mode', 0);
        }

        if ($xml == null) {
            $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
        }

        // loop through the data passed in.
        foreach ($data as $key => $value) {
            // no numeric keys in our xml please!


            if (is_numeric($key)) {

                // make string key...
                $key = "listing" . (string)$key;
            }

            // replace anything not alpha numeric
            $key = preg_replace('/[^a-z]/i', '', $key);

            // if there is another array found recrusively call this function
            if (is_array($value)) {
                $node = $xml->addChild($key);
                // recrusive call.
                $this->toXml($value, $rootNodeName, $node);
            } else {
                // add single node.
                $value = htmlspecialchars($value, ENT_QUOTES, "utf-8");
                $xml->addChild($key, $value);
            }

        }
        // pass back as string. or simple xml object if you want!
        return $xml->asXML();
    }


}
