<?php

namespace marketplace;
final class Ty
{

    private $registry;
    private $db;
    private $session;
    private $url;
    private $config;
    private $log;
    private $customer;
    private $currency;
    private $tax;
    private $username;
    private $password;
    private $shopId;
    private $client = null;

    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;
        // $this->username = $this->config->get('ty_api_anahtari');
        //$this->password = $this->config->get('ty_api_sifresi');
        // $this->shopId = $this->config->get('ty_satici_numarasi');

    }

    protected function login($data)
    {

        $this->username = $data['username'];
        $this->password = $data['password'];
        $this->shopId = $data['shopId'];

    }


    public function checkApi($params)
    {

        $status = true;
        $message = '';

        $result = $this->get_orders('Created', $params);

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

            $status = false;
            $message = 'Api bilgileriniz doğrulanamadı, lütfen kontrol ederel tekrar deneyiniz';
        }

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

    }

    public function shipping_templates($api_info)
    {
        $this->login($api_info);

        $url = 'https://apigw.trendyol.com/integration/product/sellers/' . $this->shopId . '/addresses';


        return $this->clientConnect(null, $url);


    }

    public function add_product($product_data, $api_info)
    {


        $this->login($api_info);

        //  print_r($product_data);return;

        $shipping_address_id = $product_data['defaults']['shipping_address'];
        $returning_address_id = $product_data['defaults']['returning_address'];
        $cargo_company_id = $product_data['defaults']['shipping_company'];
        $vergi = 18;//$product_data['kdv'];

        $trendyol_product['items'] = array();

        $list_price = $product_data['list_price'];
        $price = $product_data['sale_price'];
        $weight = $product_data['desi'] ? $product_data['desi'] : 1;

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

            $product_data['defaults']['selected_attributes'][$key] = array(
                'attributeId' => $attribute['market_attribute_id'],
                'attributeValueId' => $attribute['attribute_value_id'],

            );

        }

        if ($product_data['variants']) {


            foreach ($product_data['variants'] as $variant) {
                $attributes = $product_data['defaults']['selected_attributes'];


                foreach ($variant['variant_values'] as $variant_value) {

                    if ($variant_value['market_attribute_id'] == 47) {
                        $attributes[] = array(
                            'attributeId' => $variant_value['market_attribute_id'],
                            'customAttributeValue' => $variant_value['name'],

                        );
                    } else {

                        $attributes[] = array(
                            'attributeId' => $variant_value['market_attribute_id'],
                            'attributeValueId' => $variant_value['attribute_value_id'],

                        );
                    }

                }
                $product_data['images'][0] = array('url' => $variant['image']);

                $trendyol_product['items'][] = array(
                    'barcode' => (string)$variant['barcode'],
                    'title' => (string)$this->checkTitle($product_data['title']),
                    'productMainId' => $product_data['model'],
                    'brandId' => (int)$product_data['manufacturer_id'],
                    'categoryId' => (int)$product_data['category_id'],
                    'quantity' => (int)$variant['quantity'],
                    'stockCode' => (string)$variant['stock_code'],
                    'description' => (string)$product_data['description'],
                    'currencyType' => 'TRY',
                    'listPrice' => $this->priceControl($list_price),
                    'salePrice' => $this->priceControl($variant['sale_price']),
                    'vatRate' => $vergi,
                    "cargoCompanyId" => $cargo_company_id,
                    'shipmentAddressId' => $shipping_address_id,
                    'returningAddressId' => $returning_address_id,
                    'dimensionalWeight' => ((int)$weight ? $weight : 1),
                    'images' => $product_data['images'],
                    'attributes' => array_values($attributes)
                );


            }


        } else {

            $trendyol_product['items'][] = array(
                'barcode' => (string)$product_data['barcode'],
                'title' => (string)$this->checkTitle($product_data['title']),
                'productMainId' => $product_data['model'],
                'brandId' => (int)$product_data['manufacturer_id'],
                'categoryId' => (int)$product_data['category_id'],
                'quantity' => (int)$product_data['quantity'],
                'stockCode' => (string)$product_data['stock_code'],
                'description' => (string)$product_data['description'],
                'currencyType' => 'TRY',
                'listPrice' => $this->priceControl($list_price),
                'salePrice' => $this->priceControl($price),
                'vatRate' => $vergi,
                "cargoCompanyId" => $cargo_company_id,
                'shipmentAddressId' => $shipping_address_id,
                'returningAddressId' => $returning_address_id,
                'dimensionalWeight' => ((int)$weight ? $weight : 1),
                'images' => $product_data['images'],
                'attributes' => array_values($product_data['defaults']['selected_attributes'])
            );

        }


        $url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/v2/products';
//echo $url;


        if ($product_data['quantity'] == 0) {


            return array('status' => false, 'message' => "Ürün listeyelebilmeniz için ürün stoğunuzun 0'dan büyük olması gerekmektedir.", 'result' => false);

        }


        // print_r($trendyol_product);return;

        // echo json_encode($trendyol_product);
        //   return;


        $result = $this->clientConnect(json_encode($trendyol_product), $url);;


        // print_r($result);return;

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

        $message = '';
        $status = true;
        // $result['result']['batchRequestId']='d5a4154b-61f6-42c9-a0af-fd825c89c272-1658869628';
        // $result['status']=true;
        $checkBatch = array();
        if ($result['status'] && isset($result['result']['batchRequestId'])) {

            sleep(2);
            $checkBatch = $this->check_status($result['result']['batchRequestId'], $api_info);

            print_r($checkBatch);

            if ($checkBatch['result']['failedItemCount']) {
                foreach ($checkBatch['result']['items'][0]['failureReasons'] as $error) {
                    $message .= $error . '-';
                    $status = false;
                }
            } else {

                $message = 'Ürün Trendyol Mağazanıza Başarıyla Gönderildi. Trendyol Tarafından Onaylandıktan Sonra Satışa Açılacaktır';

            }


        } else {

            //  print_r($result);return;

            if (strpos($result['message'], '112836') > 0) {

                $message = 'Trendyol:Ürünü tekrar gönderebilmek için 10 dakika beklemelisiniz.';
            } else if (strpos($result['message'], 'tedarikçi için tekrarlı') > 0) {
                $message = 'Ürün trenyola daha önce gönderilmiş, ürünü tekrar göndermek için trenyol panelinden ürünü silip 20 dakika bekleyiniz.';

            } else if ($result['message']) {
                $message = $result['message'];
            } else {

                $message = 'Nedeni belirlenemeyen bir hata alındı!';

            }

        }

        if (!$status && !$message) {

            $message = 'Hata mesajı bulunamadı';


        } /*else if (isset($result['result']['exception'])) {
            $status = false;
            $message = "Ürün kodunda yada görsel url kısmında boşluk ve Türkçe karakter kullanmayınız. Bu alanları kontrol edip ürününüzü tekrar gönderebilirsiniz.";
        }*/

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


    }

    private function checkTitle($title)
    {

        return html_entity_decode($title);
    }

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

        $url = 'https://apigw.trendyol.com/integration/product/sellers/' . $this->shopId . '/v2/products';

        $result = $this->clientConnect(json_encode($product), $url);;
        //$result = $this->update_client($product);

        // print_r($result);return;
        $message = '';
        $status = true;

        $checkBatch = array();
        if ($result['status'] && isset($result['result']['batchRequestId'])) {


            // sleep(10);
            $checkBatch = $this->check_status($result['result']['batchRequestId'], $api_info);


            if ($checkBatch['result']['failedItemCount']) {
                foreach ($checkBatch['result']['items'][0]['failureReasons'] as $error) {
                    $message .= $error . '-';
                    $status = false;
                }
            } else {

                $message = 'Güncelleme bilgisi Trendyol Mağazanıza Başarıyla Gönderildi. Trendyol Tarafından Onaylandıktan Sonra Güncelleme aktif olacaktır.';

            }


        } else {


            if (strpos($result['message'], '112836') > 0) {
                $status = false;

                $message = 'Trendyol:Tüm Ürün özelliklerini tekrar güncelleyebilmek için 10 dakika beklemelisiniz.';
            } else if ($result['message']) {
                $message = $result['message'];
            } else {

                $message = 'Ürün açıklamalanızda url bulunmamalıdır!';

            }

        }

        if (!$status && !$message) {

            $message = 'Hata mesajı bulunamadı';


        } /*else if (isset($result['result']['exception'])) {
            $status = false;
            $message = "Ürün kodunda yada görsel url kısmında boşluk ve Türkçe karakter kullanmayınız. Bu alanları kontrol edip ürününüzü tekrar gönderebilirsiniz.";
        }*/


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


    }

    public function sell_products($products, $api_info)
    {
        $this->login($api_info);

        $url = 'https://apigw.trendyol.com/integration/product/sellers/' . $this->shopId . '/products';



        $result = $this->clientConnect(json_encode($products), $url);


        //$result = $this->update_client($product);

        $message = '';
        $status = true;

        $checkBatch = array();
        $batchItems = [];

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

            sleep(10);
            $checkBatch = $this->check_status($result['result']['batchRequestId'], $api_info);

            // batch sonucunu barcode ile map edeceğimiz dizi

            if (isset($checkBatch['result']['items']) && is_array($checkBatch['result']['items'])) {

                foreach ($checkBatch['result']['items'] as $item) {

                    // Barcode'u mümkün olan alanlardan çek
                    $barcode = null;
                    if (isset($item['requestItem']['product']['barcode'])) {
                        $barcode = $item['requestItem']['product']['barcode'];
                    } elseif (isset($item['requestItem']['product']['barcode'])) {
                        $barcode = $item['request']['barcode'];
                    } elseif (isset($item['barcode'])) {
                        $barcode = $item['barcode'];
                    }

                    // Item bazlı status & hata bilgisi
                    $itemStatus        = isset($item['status']) ? $item['status'] : null;
                    $itemFailureReason = isset($item['failureReasons']) ? $item['failureReasons'] : [];

                    // Genel status/message ayarı
                    if (!empty($itemFailureReason)) {
                        // En az bir item'da hata varsa genel status'ü false çekelim
                        $status = false;
                        foreach ($itemFailureReason as $error) {
                            $message .= $error . '-';
                        }
                    }

                    // Sonuç dizisine ekle
                    $batchItems[] = [
                        'barcode'        => $barcode,
                        'status'         => $itemStatus,
                        'failureReasons' => $itemFailureReason,
                    ];
                }
            }

            // Hiç item hatası yoksa, genel mesajı başarıya çek
            if ($status && !$message) {
                $message = 'Güncelleme bilgisi Trendyol Mağazanıza Başarıyla Gönderildi. Trendyol Tarafından Onaylandıktan Sonra Güncelleme aktif olacaktır.';
            }
        }

// Genel fallback mesajı
        if (!$status && !$message) {
            $message = 'Hata mesajı bulunamadı';
        }

// DÖNEN YAPI: barcode ile ilişkilendirilmiş batch sonucu
        return [
            'status'         => $status,
            'message'        => $message,
            'batchRequestId' => isset($checkBatch['result']['batchRequestId']) ? $checkBatch['result']['batchRequestId'] : null,
            'items'          => $batchItems,       // <<< BURADA: barcode + status + failureReasons dizisi
        ];



    }


    public function update_all($product_data, $api_info)
    {


        $this->login($api_info);
        $productMainId = isset($product_data['product_setting']['ty_product_code']) ? $product_data['product_setting']['ty_product_code'] ? $product_data['product_setting']['ty_product_code'] : $product_data['model'] : $product_data['model'];
        $barcode = isset($product_data['product_setting']['ty_barcode']) ? $product_data['product_setting']['ty_barcode'] ? $product_data['product_setting']['ty_barcode'] : $product_data['model'] : $product_data['model'];
        //$is_product_exists = $this->get_product(array('barcode' => $barcode), $api_info);

        $vergi = $product_data['kdv'];

        $trendyol_product['items'] = array();


        $weight = $product_data['weight'];

        if (isset($product_data['defaults']['shipping_company'])) {

            $cargoCompany = $product_data['defaults']['shipping_company'];

        } else {
            $cargoCompany = '';
        }


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


                        $has_color = false;
                        $tem_variant_attributes = array();
                        $attributes = array();
                        foreach ($variant['attributes'] as $attribute) {
                            //   print_r($attribute);

                            // echo $attribute['attributeId'];


                            if ($attribute['attributeId'] == 47) {
                                $has_color = true;
                                $attributes[] = array('attributeId' => 47, 'customAttributeValue' => $attribute['name']);

                            } else {

                                $attributes[] = array('attributeId' => $attribute['attributeId'], 'attributeValueId' => $attribute['attributeValueId']);


                            }
                        }


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

                            if ($item['attributeId'] == 338) {
                                unset($product_data['attributes'][$key]);

                            }
                        }

                        if ($has_color) {


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

                                if ($item['attributeId'] != 47) {
                                    $attributes[] = $item;

                                }


                            }
                        } else {

                            $attributes = array_merge($attributes, $product_data['attributes']);

                        }

                        $images = array();

                        if (isset($variant['barcode'])) {

                            $images = array();
                            if ($variant['image']) {
                                $images[] = array('url' => $variant['image']);
                            }
                            if (!$variant['image']) {

                                foreach ($product_data['images'] as $image) {
                                    $images[] = array('url' => $image);
                                }
                            }
                            foreach ($product_data['images'] as $image) {
                                $images[] = array('url' => $image);
                            }
                            $product = array(
                                'barcode' => (string)$variant['barcode'],
                                'vatRate' => (int)$vergi,
                                'dimensionalWeight' => ((int)$weight ? $weight : 1),
                                'productMainId' => (string)$productMainId,
                                'brandId' => (int)$product_data['manufacturer_id'],
                                'attributes' => $attributes,

                                "cargoCompanyId" => $cargoCompany,
                                'quantity' => (int)$variant['quantity'],
                                'stockCode' => (string)$variant['model'],
                                'categoryId' => (int)$product_data['category_id'],
                                "salePrice" => $this->priceControl($product_data['sale_price'] + $variant['price']),
                                "listPrice" => $this->priceControl($product_data['list_price'] + $variant['price']),
                                'currencyType' => 'TRY',
                                'images' => $images,
                                'description' => $product_data['description'] ? html_entity_decode($product_data['description'], ENT_QUOTES, 'UTF-8') : $product_data['title'], 'images' => $images,
                                'title' => (string)$product_data['title']
                            );


                            $trendyol_product['items'][] = $product;

                        }

                    }


                } else {


                    $images = array();

                    foreach ($product_data['images'] as $image) {
                        $images[] = array('url' => $image);
                    }

                    $product = array(
                        'barcode' => (string)$barcode,

                        'title' => (string)$product_data['title'],
                        'productMainId' => $productMainId,
                        'stockCode' => (string)$productMainId,
                        'categoryId' => (int)$product_data['category_id'],
                        "salePrice" => $this->priceControl($product_data['sale_price']),
                        "listPrice" => $this->priceControl($product_data['list_price']),
                        'description' => (string)$product_data['description'] ? html_entity_decode($product_data['description'], ENT_QUOTES, 'UTF-8') : $product_data['title'],
                        'currencyType' => 'TRY',
                        'quantity' => (int)$product_data['quantity'] > 0 ? $product_data['quantity'] : 0,
                        'brandId' => (int)$product_data['manufacturer_id'],
                        'attributes' => $product_data['attributes'],
                        "cargoCompanyId" => $cargoCompany,
                        'vatRate' => $vergi,
                        'dimensionalWeight' => ((int)$weight ? $weight : 1),
                        'images' => $images,
                    );


                    $trendyol_product['items'][] = $product;


                }
            } else {


                $images = array();

                foreach ($product_data['images'] as $image) {
                    $images[] = array('url' => $image);
                }

                $product = array(
                    'barcode' => (string)$barcode,

                    'title' => (string)$product_data['title'],
                    'productMainId' => $productMainId,
                    'stockCode' => (string)$productMainId,
                    'categoryId' => (int)$product_data['category_id'],
                    "salePrice" => $this->priceControl($product_data['sale_price']),
                    "listPrice" => $this->priceControl($product_data['list_price']),
                    'description' => (string)$product_data['description'] ? html_entity_decode($product_data['description'], ENT_QUOTES, 'UTF-8') : $product_data['title'],
                    'currencyType' => 'TRY',
                    'quantity' => (int)$product_data['quantity'] > 0 ? $product_data['quantity'] : 0,
                    'brandId' => (int)$product_data['manufacturer_id'],
                    'attributes' => $product_data['attributes'],
                    "cargoCompanyId" => $cargoCompany,
                    'vatRate' => $vergi,
                    'attributes' => $product_data['attributes'],

                    'dimensionalWeight' => ((int)$weight ? $weight : 1),
                    'images' => $images,
                );

                $trendyol_product['items'][] = $product;


            }

        } else {


            $images = array();

            foreach ($product_data['images'] as $image) {
                $images[] = array('url' => $image);
            }

            $product = array(
                'barcode' => (string)$barcode,

                'title' => (string)$product_data['title'],
                'productMainId' => $productMainId,
                'stockCode' => (string)$productMainId,
                'categoryId' => (int)$product_data['category_id'],
                "salePrice" => $this->priceControl($product_data['sale_price']),
                "listPrice" => $this->priceControl($product_data['list_price']),
                'description' => (string)$product_data['description'] ? html_entity_decode($product_data['description'], ENT_QUOTES, 'UTF-8') : $product_data['title'],
                'currencyType' => 'TRY',
                'quantity' => (int)$product_data['quantity'] > 0 ? $product_data['quantity'] : 0,
                'brandId' => (int)$product_data['manufacturer_id'],
                'attributes' => $product_data['attributes'],
                "cargoCompanyId" => $cargoCompany,
                'vatRate' => $vergi,
                'dimensionalWeight' => ((int)$weight ? $weight : 1),
                'images' => $images,
            );


            $trendyol_product['items'][] = $product;


        }


        //print_r($trendyol_product);return;

        $url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/v2/products';
//echo $url;


        //echo json_encode($trendyol_product);
        //return;


        $product = json_encode($trendyol_product);


        $result = $this->clientConnect($product, $url, 'PUT');
        //$result = $this->update_client($product);

        // print_r($result);return;
        $message = '';
        $status = true;

        $checkBatch = array();
        if ($result['status'] && isset($result['result']['batchRequestId'])) {


            sleep(4);
            $checkBatch = $this->check_status($result['result']['batchRequestId'], $api_info);

            //print_r($checkBatch);

            if ($checkBatch['result']['failedItemCount']) {
                foreach ($checkBatch['result']['items'][0]['failureReasons'] as $error) {
                    $message .= $error . '-';
                    $status = false;
                }
            } else {

                $message = 'Güncelleme bilgisi Trendyol Mağazanıza Başarıyla Gönderildi. Trendyol Tarafından Onaylandıktan Sonra Güncelleme aktif olacaktır.';

            }


        } else {


            if (strpos($result['message'], '112836') > 0) {
                $status = false;

                $message = 'Trendyol:Tüm Ürün özelliklerini tekrar güncelleyebilmek için 10 dakika beklemelisiniz.';
            } else if ($result['message']) {
                $message = $result['message'];
            } else {

                $message = 'Ürün açıklamalanızda url bulunmamalıdır!';

            }

        }

        if (!$status && !$message) {

            $message = 'Hata mesajı bulunamadı';


        } /*else if (isset($result['result']['exception'])) {
            $status = false;
            $message = "Ürün kodunda yada görsel url kısmında boşluk ve Türkçe karakter kullanmayınız. Bu alanları kontrol edip ürününüzü tekrar gönderebilirsiniz.";
        }*/


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


    }


    public function update_fast($update_list, $api_info, $mode = true)
    {


        $list = array();
        $list['items'] = $update_list;


        $username = $api_info['username'];
        $password = $api_info['password'];

        $curl = curl_init();

        $url="https://apigw.trendyol.com/integration/inventory/sellers/".$api_info['shopId']."/products/price-and-inventory";

        curl_setopt_array($curl, array(
            CURLOPT_URL => $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 => 'POST',
            CURLOPT_POSTFIELDS => json_encode($list),
            CURLOPT_HTTPHEADER => array(
                'Authorization: Basic ' . base64_encode("$username:$password"),
                'Content-Type: application/json',
                'Cookie: __cfruid=8b5d2adb208204a4811c0f78b79f05d976a1a90d-1685299400; _cfuvid=II_34tNJCaQvXfH1yMxntUGAhL7ob.ud.M3.9I8DdTI-1685299400267-0-604800000; __cflb=02DiuEkjxji3pxUywYoR8hKcjQvCpYR5XkY58QCPvGugx'
            ),
        ));

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

        curl_close($curl);


        sleep(10);

        if (isset($response['batchRequestId'])) {


            $curl = curl_init();

            $url="https://apigw.trendyol.com/integration/product/sellers/".$api_info['shopId']."/products/batch-requests/". $response['batchRequestId'];
            curl_setopt_array($curl, array(
                CURLOPT_URL => $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 => 'GET',
                CURLOPT_HTTPHEADER => array(
                    'Authorization: Basic ' . base64_encode("$username:$password"),
                    'Cookie: __cfruid=8b5d2adb208204a4811c0f78b79f05d976a1a90d-1685299400; _cfuvid=II_34tNJCaQvXfH1yMxntUGAhL7ob.ud.M3.9I8DdTI-1685299400267-0-604800000; __cflb=02DiuEkjxji3pxUywYoR8hKcjQvCpYR5XkY58QCPvGugx'
                ),
            ));

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

            curl_close($curl);


            return $response;

        }
    }


    public function update_basic($product_data, $api_info, $mode = false)
    {


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

        /*  $batch_id='3403b454-0d77-11ec-a3a3-ba1a3e590858-1630771016';

          $checkBatch = $this->check_status($batch_id, $api_info);

          print_r($checkBatch);
          return ;

  */
        if (isset($product_data['ty'])) {
            $marketplace_data = unserialize($product_data['ty']);

            /* if(!$marketplace_data['sale_status'] && $marketplace_data['approval_status'] && !$mode){
                     return array('status' => false, 'message' => 'Ürün satışa kapalı olduğu için güncelleme yapılamaz,sadece onaylanan ve satışa açık ürünleri güncelleyebilirsiniz.', 'result' => array());
                 }*/
        }

        $this->login($api_info);
        $productMainId = isset($product_data['product_setting']['ty_product_code']) ? $product_data['product_setting']['ty_product_code'] ? $product_data['product_setting']['ty_product_code'] : $product_data['model'] : $product_data['model'];
        //print_r($this->get_product(array('barcode'=>$productMainId),$api_info));
        //return;

        $barcode_ecx = false;//isset($product_data['product_setting']['ty_barcode']) ? $product_data['product_setting']['ty_barcode'] ? $product_data['product_setting']['ty_barcode'] : isset($product_data['model'])?$product_data['model'] : false:false;
        if (isset($product_data['ty'])) {
            $barcode = isset($marketplace_data['barcode']) ? $marketplace_data['barcode'] : $barcode_ecx;

        } else {
            $barcode = $barcode_ecx;
        }
        if (!$barcode) {

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

        }


        $message = array();
        $status = false;


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

                return array('status' => false, 'message' => 'Ürün seçenekleri eşleşmemiş, ürünü varyantlı olarak güncellemek istiyorsanız kategori eşleştirme ayarlarından tüm seçenekleri eşleştiriniz, varyantlı güncellemek istemiyorsanız genel ayarlardan varyantlı ürün gönderme seçeneğini deaktif ediniz, yada ürün seçeneklerini siliniz.', 'result' => array());
            }
        }


        if ($product_data['variants']) {

            $barcode = $product_data['model'];

            if ($product_data['variants']['variants']) {
                $variants = isset($product_data['variants']['variants'][0]['attributes']) ? $product_data['variants']['variants'] : $product_data['variants']['variants']['options'];

            } else {

                $variants = array();
            }


            //print_r($variants);
            //return ;

            foreach ($variants as $variant) {
                $quantity = $variant['quantity'] < 0 ? 0 : $variant['quantity'];

                $update_data['items'][] = array(
                    "barcode" => (string)isset($variant['barcode']) ? $variant['barcode'] : $barcode . $variant['prefix'],
                    "quantity" => $mode == 'close' ? 0 : $quantity,
                    "salePrice" => $mode == 'close' ? 0 : $this->priceControl($product_data['sale_price'] + $variant['price']),
                    "listPrice" => $mode == 'close' ? 0 : $this->priceControl($product_data['list_price'] + $variant['price'])
                );


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

                        $barcode_arr = explode($product_data['model_prefix'], $variant['barcode'], 2);

                        if (count($barcode_arr) == 2) {


                            $update_data['items'][] = array(
                                "barcode" => $barcode_arr[1],
                                "quantity" => $mode == 'close' ? 0 : $quantity,
                                "salePrice" => $mode == 'close' ? 0 : $this->priceControl($product_data['sale_price'] + $variant['price']),
                                "listPrice" => $mode == 'close' ? 0 : $this->priceControl($product_data['list_price'] + $variant['price'])
                            );


                        }


                    }
                }


            }


        } else {

            $quantity = $product_data['quantity'] < 0 ? 0 : $product_data['quantity'];
            $update_data['items'][] = array(
                "barcode" => (string)$barcode,
                "quantity" => $mode == 'close' ? 0 : $quantity,
                "salePrice" => $mode == 'close' ? 0 : $this->priceControl($product_data['sale_price']),
                "listPrice" => $mode == 'close' ? 0 : $this->priceControl($product_data['list_price'])
            );

        }


        // print_r($update_data);return;
        // return  array('status'=>true,'message'=>'','result'=>array());
        $url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/products/price-and-inventory';


        $result = $this->clientConnect(json_encode($update_data), $url);


        return $result; //HER ZAMA BASARILI DÖN

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

            return $result;

        }

        $batch_id = $result['result']['batchRequestId'];
        // return $batch_id;


        sleep(3);

        //$batch_id='efb114dc-1f7f-11ec-acd3-1e71a8da6f2a-1632753888';

        $batch_request = $this->check_status($batch_id, $api_info);


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

              return array('status' => true, 'message' => 'Güncelleme işlemi başarılı', 'result' => $batch_request['result']);


          }*/


        // print_r($batch_request);return ;


        foreach ($batch_request['result']['items'] as $item) {

            if ($item['status'] == 'SUCCESS') {
                $status = true;
            }

        }


        if ($batch_request['result']['failedItemCount'] > 0) {
            foreach ($batch_request['result']['items'][0]['failureReasons'] as $item) {

                if (!in_array($item, $message)) {

                    $message[] = $item;
                }
            }

        } else {

            $message = 'Ürün Trendyolda Başarıyla Güncellendi';
        }

        if ($status) {
            return array('status' => true, 'message' => 'Ürün başarıyla Güncellendi', 'result' => $batch_request['result']);

        } else {

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

        }


    }


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

    }

    public function str_search($samanlik, $igne)
    {

        if (strpos(strtolower($samanlik), strtolower($igne)) === false) {
            return false;
        } else {
            return true;
        }

    }

    public function get_orders($product_data, $api_info)
    {


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


        // $url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/orders?status=' . $product_data;
        // $hour = 12;
        // $today              = strtotime($hour . ':00:00');
        $now = date('Y-m-d H:i:s');

        $today = strtotime($now);


        $yesterday = strtotime('-1 day', $today);
        $today = strtotime('+1 day', $today);

        // $dayBeforeYesterday = strtotime('-1 day', $yesterday);
        // $url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/orders?startdate='.$today.'&enddate='.$yesterday.'&page=0&orderByDirection=DESC&size=50' ;
        //$url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/orders?orderByDirection=DESC&size=30&startdate=' . $today . '&enddate=' . $yesterday;
        // $url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/orders?orderByDirection=DESC&size=20';
        $url = "https://api.trendyol.com/sapigw/suppliers/" . $this->shopId . "/orders?size=20&orderByDirection=DESC&orderByField=PackageLastModifiedDate";

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

            $url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/orders?orderNumber=' . $product_data['order_number'];

        }

        return $this->clientConnect(null, $url);


    }

    public function get_orders2($product_data, $api_info)
    {


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

        // $url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/orders?status=' . $product_data;
        // $hour = 12;
        // $today              = strtotime($hour . ':00:00');
        $now = date('Y-m-d H:i:s');

        $today = strtotime($now);
        // echo date('Y-m-d H:i:s', $end);

        $url = "https://api.trendyol.com/sapigw/suppliers/" . $this->shopId . "/orders?size=200&orderByDirection=DESC&orderByField=PackageLastModifiedDate";


        //$url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/orders?orderByDirection=DESC&size=50';

        /*  if(isset($product_data['order_number'])){

              $url= 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/orders?orderNumber='.$product_data['order_number'];

          }*/

        return $this->clientConnect(null, $url);


    }


    public function get_products($product_data, $api_info)
    {

        $this->login($api_info);
        $url = 'https://apigw.trendyol.com/integration/product/sellers/' . $this->shopId . '/products?page=' . $product_data['page'] . '&size=' . $product_data['itemcount'];


        $url .= '&approved=true';



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

            if ($product_data['on_sale']) {
                $url .= '&onSale=true';

            } else {
                $url .= '&onSale=false';

            }
        }


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

            if ($product_data['archived']) {
                $url .= '&archived=true';

            } else {
                $url .= '&archived=false';

            }
        }

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

            if ($product_data['barcode']) {
                $url .= '&barcode='.$product_data['barcode'];

            }
        }


        return $this->clientConnect(null, $url);


    }


    public function get_product($product_data, $api_info)
    {
        $this->login($api_info);
        $url = 'https://apigw.trendyol.com/integration/product/sellers/' . $this->shopId . '/products?barcode=' . urlencode($product_data['barcode']);
        $return = $this->clientConnect(null, $url);

        return $return;


    }

    public function category_attributes($product_data, $api_info)
    {
        $this->login($api_info);
        $url="https://apigw.trendyol.com/integration/product/product-categories/".$product_data."/attributes";
        return $this->clientConnect(null, $url);

    }


    public function delete_products($barcodes, $api_info)
    {

        $this->login($api_info);


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


        foreach ($barcodes as $barcode) {


            $data['items'][] = array(
                "barcode" => $barcode,
            );
        }




        $url='https://apigw.trendyol.com/integration/product/sellers/'. $this->shopId .'/products';


        $result = $this->clientConnect(json_encode($data), $url,'DELETE');



        $batch_id = $result['result']['batchRequestId'];
        // return $batch_id;


        sleep(3);

        //$batch_id='efb114dc-1f7f-11ec-acd3-1e71a8da6f2a-1632753888';

        $batch_request = $this->check_status($batch_id, $api_info);


        print_r($batch_request);


        return $batch_request; //HER ZAMA BASARILI DÖN


    }
    public function close_for_sale($barcodes, $api_info)
    {

        $this->login($api_info);


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


        foreach ($barcodes as $barcode) {


            $data['items'][] = array(
                "barcode" => $barcode,
                "quantity" => 0,
                "salePrice" => 0,
                "listPrice" => 0
            );
        }


        $url = 'https://apigw.trendyol.com/integration/product/sellers/' . $this->shopId . '/products/price-and-inventory';

        $result = $this->clientConnect(json_encode($data), $url);


        $batch_id = $result['result']['batchRequestId'];
        // return $batch_id;


        sleep(3);

        //$batch_id='efb114dc-1f7f-11ec-acd3-1e71a8da6f2a-1632753888';

        $batch_request = $this->check_status($batch_id, $api_info);

        return $batch_request; //HER ZAMA BASARILI DÖN


    }

    public function open_for_sale($product_data, $api_info)
    {

        return $this->update_basic($product_data, $api_info, 'open');

    }


    public function get_questions($api_info)
    {
        //  date_default_timezone_set('Europe/Istanbul');
        $this->login($api_info);


        // $url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/orders?status=' . $product_data;
        // $hour = 12;
        // $today              = strtotime($hour . ':00:00');
        $now = date('Y-m-d H:i:s');

        $today = strtotime($now);


        $yesterday = strtotime('-15 day', $today);
        $today = strtotime('+1 day', $today);

        // $dayBeforeYesterday = strtotime('-1 day', $yesterday);

        $question_list = array();

        $url = 'https://apigw.trendyol.com/integration/product/sellers/' . $this->shopId . '/questions/filter?status=WAITING_FOR_ANSWER';
        $questions = $this->clientConnect(null, $url);


        if ($questions['result']['content']) {

            foreach ($questions['result']['content'] as $question) {

                $question_list[] = array('id' => $question['id'], 'url' => explode('ty-p-', $question['webUrl'])[1], 'text' => $question['text']);
            }

        }

        return $question_list;


    }


    public function get_question($product_data, $api_info)
    {
        //  date_default_timezone_set('Europe/Istanbul');
        $this->login($api_info);

        $url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/questions/' . $product_data;

        $result = $this->clientConnect(null, $url);

        return $result;

    }

    public function reply_question($product_data, $api_info)
    {
        //  date_default_timezone_set('Europe/Istanbul');
        $this->login($api_info);
        //https://api.trendyol.com/sapigw/suppliers/{supplierId}/questions/{id}/answers
        $url = 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/questions/' . $product_data['question_id'] . '/answers';;
        $result = $this->clientConnect(json_encode(array('text' => $product_data['text'])), $url, 'POST');

        return $result;

    }

    public function clientConnect2($data = null, $url)
    {


        $message = '';
        $status = false;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_USERAGENT, $this->shopId . " - SelfIntegration");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        // curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);

        curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
        //if ($data != null) {

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        // }


        //echo $data;
        //return;


        $resp = curl_exec($ch);


        /* $info = curl_getinfo($ch);
         print_r($info);
         return;*/
        curl_close($ch);
        var_dump($resp);
    }


    public function clientConnect($data = null, $url, $method = 'POST')
    {


        $message = '';
        $status = false;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_USERAGENT, $this->shopId . " - SelfIntegration");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        // curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);


        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Authorization: Basic ' . base64_encode("$this->username:$this->password"),
            'Content-Type: application/json'
        ));
        if ($data != null) {

            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        if ($method == 'PUT') {


            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

            //echo 'put';

        }
        if ($method == 'DELETE') {


            echo 'DELETE İŞLEMİ';

            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

            //echo 'put';

        }

        //  echo $data;
        //  return;


        $result = curl_exec($ch);



        // $info = curl_getinfo($ch);
        //print_r($info);
        //return;

        // print_r($result);
        // return;

        $errors = curl_exec($ch);
        /* if ( $errors) {
             print_r($errors);
         }*/

        curl_close($ch);
        $result = json_decode($result, true);




        if (isset($result['errors']) || isset($result['error'])) {
            if (isset($result['errors'])) {
                if ($result['errors'][0]) {
                    foreach ($result['errors'] as $error) {
                        $message .= $error['message'];
                    }
                } else {

                }

            } else {

                $message .= $result['status'];
            }

        } else {

            $status = true;
        }

        /*    if(isset($result['exception'])){

              $resu=$this->sendProxy('https://www.ellconline.com/index.php?route=api/server/ty',$data,$url);
              print_r($resu);

            }else {
    */
        return array('status' => $status, 'message' => $message, 'result' => $result);

        // }


    }


    public function update_client($product = array())
    {


        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.trendyol.com/sapigw/suppliers/112836/v2/products',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'PUT',
            CURLOPT_POSTFIELDS => $product,
            CURLOPT_HTTPHEADER => array(
                'Authorization: Basic ' . base64_encode("$this->username:$this->password"),
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;


    }


    private function sendProxy($url, $data, $market_url)
    {
        $send_data = array('market_url' => $market_url, 'user' => array('username' => $this->username, 'password' => $this->password), 'data' => json_decode($data, 1));

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($send_data));//.$json_data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($curl);

        print_r($result);
        curl_close($curl);
    }


    public function check_status($product_data, $api_info)
    {
        $this->login($api_info);
        $url = 'https://apigw.trendyol.com/integration/product/sellers/' . $this->shopId . '/products/batch-requests/'. $product_data;

        $result = $this->clientConnect(null, $url,'GET');


        return $result;

    }

    public function create_barcode($product_data, $api_info)
    {


        $order_info = $this->get_orders($product_data, $api_info);


        $cargoSenderNumber = isset($order_info['result']['content'][0]['cargoSenderNumber']) ? $order_info['result']['content'][0]['cargoSenderNumber'] : 0;
        $cargoTrackingNumber = isset($order_info['result']['content'][0]['cargoTrackingNumber']) ? $order_info['result']['content'][0]['cargoTrackingNumber'] : 0;


        $url = 'https://apigw.trendyol.com/integration/product/sellers/' . $this->shopId . '/common-label/' . $cargoTrackingNumber;


        // $url='https://api.trendyol.com/sapigw/suppliers/'.$this->shopId.'/common-label/'.$cargoTrackingNumber;
        $result = $this->clientConnect(null, $url);

        print_r($result);

    }


}
