<?php

namespace marketplace;


final class Hb
{

    private $registry, $db, $session, $url, $config, $log, $customer, $currency, $tax, $token, $error, $username, $password, $parameters;
    private $katalog__test_url = 'https://mpop-sit.hepsiburada.com/';
    private $katalog_url = 'https://mpop.hepsiburada.com/';
    private $listUrl = 'https://listing-external.hepsiburada.com';
    private $orderUrl = 'https://oms-external.hepsiburada.com/';
    private $merchant_id;
    private $service_key;

    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 = 'miryazilim_dev';
        $this->password = 'humQ#2ylT';

    }

    public function checkApi($params)
    {
        return $this->get_orders(null, $params);
    }

    public function get_unaproved_orders($product_data, $api_info)
    {

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

        //$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)
    {

        $this->merchant_id = $api_info['merchant_id'];
        $this->service_key = $api_info['service_key'];
        //$url = "https://oms-external.hepsiburada.com/orders/merchantid/".$this->merchant_id;
        //$url='https://oms-external.hepsiburada.com/orders/merchantid/ad905f66-9e62-4743-9d9b-2aa121ef1db1';


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

            if ($product_data['auto_approve']) {
                $this->get_order_and_make_package($api_info);


            }

        }

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


//echo $package_url;
//return;

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


        //print_r($packages);
        //return ;

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

            if ($packages['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' => $packages);

        } else {

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

        }


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


    private function update_shipping($products,$api_info)
    {

        //print_r($api_info);

        $update_data = array();
        foreach ($products as $product) {

            $update_data[] = array(
                //"hepsiburadaSku" => $product['marketplace_product_id'],
                "merchantSku" => $product['barcode'],
                "dispatchTime" => 2

            );

        }



        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://listing-external.hepsiburada.com/listings/merchantid/'.$this->merchant_id.'/shipping-info-uploads',
            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($update_data),
            CURLOPT_HTTPHEADER => array(
                'Authorization: Basic ' . base64_encode($this->merchant_id . ':' . $this->service_key),

                'User-Agent: miryazilim_dev',
                'Content-Type: application/json',
                'Accept: application/json',
            ),
        ));

        $response = curl_exec($curl);



        curl_close($curl);
      //  echo $response;

        //  echo "------shipping günceleme başlanıç";
       // print_r($update_data);



        //print_r($chech);
     //   echo "------shipping günceleme sonu";




    }


    public function get_questions($api_info)
    {


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

        $question_list = array();
        //echo $this->merchant_id;
        $url = 'https://api-asktoseller-merchant.hepsiburada.com/api/v1.0/issues?status=1&page=1&size=125&sortBy=1&desc=true';
        $result = json_decode($this->clientConnect($url, 'question', $this->token, 'GET', null), true);


        foreach ($result['data'] as $question) {


            $question_list[] = array(
                'id' => $question['issueNumber'],
                'text' => $question['lastContent'],
                'url' => $question['product']['sku']

            );
        }

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


    }


    public function get_question($product_data, $api_info)
    {
        //  date_default_timezone_set('Europe/Istanbul');
        $this->merchant_id = $api_info['merchant_id'];
        $this->service_key = $api_info['service_key'];

        //echo $this->merchant_id;
        $url = 'https://api-asktoseller-merchant.hepsiburada.com/api/v1.0/issues/' . $product_data;
        $result = json_decode($this->clientConnect($url, 'getQuestions', $this->token, 'GET', null), true);

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

    public function reply_question($product_data, $api_info)
    {
        //  date_default_timezone_set('Europe/Istanbul');
        $this->merchant_id = $api_info['merchant_id'];
        $this->service_key = $api_info['service_key'];


        $url = "https://api-asktoseller-merchant.hepsiburada.com/api/v1.0/issues/" . $product_data['question_id'] . "/answer";

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

        $headers = array(
            "merchantId: " . $this->merchant_id,
            'User-Agent: miryazilim_dev'
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_USERPWD, $this->merchant_id . ":" . $this->service_key);

        $data = "answer=" . $product_data['text'];

        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

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

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


        print_r($resp);

        $status = true;

        $message = array();


        if ($resp['code'] == 4000) {

            $status = false;

            foreach ($resp['errors'] as $error) {

                $message[] = $error['message'];
            }
        }

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

    }


    public function check_buybox($api_info,$skulist)
    {
        $this->merchant_id = $api_info['merchant_id'];
        $this->service_key = $api_info['service_key'];


        $url = "https://listing-external.hepsiburada.com/buybox-orders/merchantid/" . $this->merchant_id."?skuList=".implode(",",$skulist); //. "?offset=0&limit=1"

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

        foreach ($results['variants'] as $variant) {
            if(count($variant['buyboxOrders'])>1){

                echo $variant['sku']. 'buyboxta';

            }
            
}

    }




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


        $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'];
        $this->service_key = $api_info['service_key'];

        $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->merchant_id . ':' . $this->service_key),
            'Content-Type: application/xml',
            'User-Agent: miryazilim_dev'
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $curl_response = curl_exec($curl);

        return $curl_response;


    }


    public function close_for_sale($market_product_id, $api_info)
    {

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

        if ($market_product_id) {
            $service_url = $this->listUrl . "/listings/merchantid/" . strtolower($this->merchant_id) . "/sku/" . $market_product_id . "/deactivate";

            // echo $service_url;return;
            $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 delete_product($products, $api_info)
    {
        $result = array();

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

        if ($products) {
            foreach ($products as $product) {

                // HepsiburadaSku ve MerchantSku kontrolü
                if (empty($product['marketplace_product_id']) || empty($product['model'])) {
                    $result[isset($product['model']) ? $product['model'] : ''] = 'HepsiburadaSku (marketplace_product_id) veya MerchantSku (model) eksik.';
                    continue;
                }

                // Dokümandaki endpoint:
                // https://listing-external-sit.hepsiburada.com/listings/merchantid/{merchantId}/sku/{sku}/merchantsku/{merchantSku}
                // Canlıda "-sit" kaldırılarak kullanılır.
                $service_url = rtrim($this->listUrl, '/') .
                    '/listings/merchantid/' . strtolower($this->merchant_id) .
                    '/sku/' . rawurlencode($product['marketplace_product_id']) .
                    '/merchantsku/' . rawurlencode($product['model']);

                $curl = curl_init();
                curl_setopt_array($curl, array(
                    CURLOPT_URL            => $service_url,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING       => '',
                    CURLOPT_MAXREDIRS      => 10,
                    CURLOPT_TIMEOUT        => 30,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST  => 'DELETE',
                    CURLOPT_HTTPHEADER     => array(
                        // Listing dokümanında belirtildiği gibi Basic Auth
                        'Authorization: Basic ' . base64_encode($this->merchant_id . ':' . $this->service_key),
                        'User-Agent: miryazilim_dev',
                        'Accept: application/json',
                    ),
                ));

                $responseBody = curl_exec($curl);
                $httpCode     = curl_getinfo($curl, CURLINFO_HTTP_CODE);
                $curlError    = curl_error($curl);
                curl_close($curl);

                // cURL seviyesinde hata
                if ($curlError) {
                    $result[$product['model']] = 'cURL error: ' . $curlError;
                    continue;
                }

                // 2xx dönüyorsa başarı kabul ediyoruz, result’a bir şey yazmıyoruz (diğer fast metodlarla uyumlu)
                if ($httpCode >= 200 && $httpCode < 300) {
                    continue;
                }

                // Hata durumunda mümkünse response içinden mesaj çek
                $decoded = json_decode($responseBody, true);

                if (is_array($decoded)) {

                    if (isset($decoded['message'])) {
                        $result[$product['model']] = $decoded['message'];

                    } elseif (isset($decoded['errors'])) {
                        if (is_array($decoded['errors'])) {
                            $result[$product['model']] = implode(', ', $decoded['errors']);
                        } else {
                            $result[$product['model']] = $decoded['errors'];
                        }

                    } else {
                        $result[$product['model']] = 'Silme isteği başarısız. HttpCode: ' . $httpCode;
                    }

                } else {
                    // JSON değilse ham body ile logla
                    $result[$product['model']] = 'Silme isteği başarısız. HttpCode: ' . $httpCode . ' Response: ' . $responseBody;
                }
            }
        }

        // Diğer fast metodlar gibi status true bırakıp sku=>hata mesajı map’i result altında döndürüyoruz
        return array(
            'status'  => true,
            'message' => '',
            'result'  => $result
        );
    }

    public function open_fast($products, $api_info)
    {

        


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

        $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";


        foreach ($products as $product) {

            $shipping_time = isset($product['shipping_time']) ? $product['shipping_time'] : 2;
            $maximum_order = isset($product['maximum_order']) ? $product['maximum_order'] : 1;
            $quantity = 4;

            $xml .= "<listing>\n";
           // $xml .= "<HepsiburadaSku>" . (string)$product['marketplace_product_id'] . "</HepsiburadaSku>\n";
            $xml .= "<MerchantSku>" . (string)$product['stock_code'] . "</MerchantSku>\n";
            //  $xml .= "<HepsiburadaSku>HBV000013F5FP</HepsiburadaSku>";
            // $xml .= "<MerchantSku>4353456KIRMIZI42</MerchantSku>";
            // $xml .= "<ProductName>" . $product_data['title'] . "</ProductName>";
            $xml .= "<Price>" . $this->priceFormat(isset($product['sale_price']) ? $product['sale_price'] : $product['list_price']) . "</Price>\n";
            $xml .= "<AvailableStock>" . (int)$quantity . "</AvailableStock>\n";
            $xml .= "<DispatchTime>" . $shipping_time . "</DispatchTime>\n";
            $xml .= "<MaximumPurchasableQuantity>" . $maximum_order . "</MaximumPurchasableQuantity>\n";

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

        }
        $xml .= "</listings>";


        $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->merchant_id . ':' . $this->service_key),
            'Content-Type: application/xml',
            'User-Agent:miryazilim_dev'
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $curl_response = curl_exec($curl);
        $result = $this->xmlToArray($curl_response);



        sleep(1);
        /*   if ($mode) {
               foreach ($products as $product) {

                   if ($product['quantity']) {

                       $res = $this->open_for_sale($product['marketplace_product_id'], $api_info);
                       //print_r($res);echo $product['marketplace_product_id'].' açıldı';


                   } else {
                       // echo $product['marketplace_product_id'].' stok 0';
                   }

               }
           }*/

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

        //  sleep(10);


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


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


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



           // print_r($check_batch);

            $result = array();

            foreach ((array)$check_batch['errors'] as $error) {

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


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

        }


    }

    public function close_fast($products, $api_info)
    {



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

        $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";



        foreach ($products as $product) {

            $shipping_time = isset($product['shipping_time']) ? $product['shipping_time'] : 2;
            $maximum_order = isset($product['maximum_order']) ? $product['maximum_order'] : 1;
            $quantity = 0;

            $xml .= "<listing>\n";
            // $xml .= "<HepsiburadaSku>" . (string)$product['marketplace_product_id'] . "</HepsiburadaSku>\n";
            $xml .= "<MerchantSku>" . (string)$product['model'] . "</MerchantSku>\n";
            //  $xml .= "<HepsiburadaSku>HBV000013F5FP</HepsiburadaSku>";
            // $xml .= "<MerchantSku>4353456KIRMIZI42</MerchantSku>";
            // $xml .= "<ProductName>" . $product_data['title'] . "</ProductName>";
            $xml .= "<Price>" . $this->priceFormat(isset($product['sale_price']) ? $product['sale_price'] : $product['list_price']) . "</Price>\n";
            $xml .= "<AvailableStock>" . (int)$quantity . "</AvailableStock>\n";
            $xml .= "<DispatchTime>" . $shipping_time . "</DispatchTime>\n";
            $xml .= "<MaximumPurchasableQuantity>" . $maximum_order . "</MaximumPurchasableQuantity>\n";

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

        }
        $xml .= "</listings>";




        $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->merchant_id . ':' . $this->service_key),
            'Content-Type: application/xml',
            'User-Agent:miryazilim_dev'
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $curl_response = curl_exec($curl);
        $result = $this->xmlToArray($curl_response);



        sleep(5);
        /*   if ($mode) {
               foreach ($products as $product) {

                   if ($product['quantity']) {

                       $res = $this->open_for_sale($product['marketplace_product_id'], $api_info);
                       //print_r($res);echo $product['marketplace_product_id'].' açıldı';


                   } else {
                       // echo $product['marketplace_product_id'].' stok 0';
                   }

               }
           }*/

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

        //  sleep(10);


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


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



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



             //print_r($check_batch);

             //echo "yes";

            $result = array();

            foreach ((array)$check_batch['errors'] as $error) {

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


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

        }


    }

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



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

        $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";


        $this->update_shipping($products,$api_info);



        foreach ($products as $product) {

            $shipping_time = isset($product['shipping_time']) ? $product['shipping_time'] : 2;
            $maximum_order = isset($product['maximum_order']) ? $product['maximum_order'] : 1;
            $quantity = $mode ? $product['quantity'] : 0;

            $xml .= "<listing>\n";
           // $xml .= "<HepsiburadaSku>" . (string)$product['marketplace_product_id'] . "</HepsiburadaSku>\n";
            $xml .= "<MerchantSku>" . (string)$product['stockCode'] . "</MerchantSku>\n";
            //  $xml .= "<HepsiburadaSku>HBV000013F5FP</HepsiburadaSku>";
            // $xml .= "<MerchantSku>4353456KIRMIZI42</MerchantSku>";
            // $xml .= "<ProductName>" . $product_data['title'] . "</ProductName>";
            $xml .= "<Price>" . $this->priceFormat(isset($product['salePrice']) ? $product['salePrice'] : $product['listPrice']) . "</Price>\n";
            $xml .= "<AvailableStock>" . (int)$quantity . "</AvailableStock>\n";
            $xml .= "<DispatchTime>" . $shipping_time . "</DispatchTime>\n";
            $xml .= "<MaximumPurchasableQuantity>" . $maximum_order . "</MaximumPurchasableQuantity>\n";

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

        }
        $xml .= "</listings>";


        $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->merchant_id . ':' . $this->service_key),
            'Content-Type: application/xml',
            'User-Agent:miryazilim_dev'
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $curl_response = curl_exec($curl);
        $result = $this->xmlToArray($curl_response);
        //return array('status' => true, 'message' => '', 'result' => $result);


      //  sleep(5);
        /*   if ($mode) {
               foreach ($products as $product) {

                   if ($product['quantity']) {

                       $res = $this->open_for_sale($product['marketplace_product_id'], $api_info);
                       //print_r($res);echo $product['marketplace_product_id'].' açıldı';


                   } else {
                       // echo $product['marketplace_product_id'].' stok 0';
                   }

               }
           }*/

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

         // sleep(10);


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


        //$result['Id'] ="3e7d2176-74b7-4819-9cf6-40820b5f94f7";
        //sleep(35);


        if (isset($result['id'])) {
           // sleep(20);
            $check_batch = $this->xmlToArray($this->chechUpdate($result['id'], $api_info));

            echo "Update fast result";
            print_r($check_batch);

            $result = array();

            foreach ((array)$check_batch['errors'] as $error) {

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


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

        }


    }

    private function priceFormat($price)
    {

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

    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);

        $this->merchant_id = $api_info['merchant_id'];
        $this->service_key = $api_info['service_key'];
        $category_id = $request_data;// 703
        //$this->getToken();
//echo $this->token;
        $result = array();
        $attributes = array();

        if (true) {
            $status = true;
            $url = $this->katalog_url . '/product/api/categories/' . $category_id . '/attributes';

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


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

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

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

            }


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

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

                    //  if ($attribute['type'] == 'enum') {
                    $attributes[] = array(
                        'id' => $attribute['id'],
                        'name' => $attribute['name'],
                        'values' => $this->getAttributeValues($category_id, $attribute['id'])['data'],
                        'type' => $attribute['type'],
                        'varianter' => true,
                        'multiple' => $attribute['multiValue'],
                        'required' => $attribute['mandatory'],
                    );
                }
                //  }

            }


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

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

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


        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 (true) {
            $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);

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

                print_r($result);
                echo 'hatalı işlem';
                return ;

            }

            $values = array();

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

                foreach ($result['data'] as $datum) {
                    $values[] = array('id' => $datum['value'], 'value' => $datum['value']);
                }
                $totalpages = $result['totalPages'] > 20 ? 20 : $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[] = array('id' => $datum['value'], 'value' => $datum['value']);
                    }


                }

            } else {
                //  $values= array_merge($values,$result['data']);
                foreach ($result['data'] as $datum) {
                    $values[] = array('id' => $datum['value'], 'value' => $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 sell_product($product_data, $api_info)
    {


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

        //$this->merchant_id = '069fb762-b69d-4170-a1f6-ef6e165bb905';

        //$this->getToken();
        /*
                $track_id='70419930-060d-4824-8ec1-bb2f6a5d4ef4';
                $check = $this->check_status($track_id,$api_info);
                print_r($check);
                return;
        */

        $result = $this->product_send($this->token, json_encode($product_data));


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


        if ($result['success']) {

            $track_id = $result['data']['trackingId'];
            sleep(3);
            $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());


        }


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

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




        $result = $this->product_update_send($this->token, json_encode($product_data));



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


        if ($result['trackingId']) {

            $track_id = $result['trackingId'];
            //sleep(20);
            $check = $this->check_update_status($track_id, $api_info);

           echo "Full update Result";
            print_r($check);

            return array('status' => false, 'message' => 'Ürünler başarıynan güncellendi', 'result' => $check);



        } else {

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


        }


    }

    public function sell_products($product_datas, $api_info)
    {


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

        //$this->merchant_id = '069fb762-b69d-4170-a1f6-ef6e165bb905';

        // $this->getToken();
        /*
                $track_id='70419930-060d-4824-8ec1-bb2f6a5d4ef4';
                $check = $this->check_status($track_id,$api_info);
                print_r($check);
                return;
        */


        //print_r($product_datas);


        //foreach ($product_datas as $product_data) {

            $result = $this->product_send($this->token, json_encode($product_datas));

       // }




        $status  = true;
        $message = '';
        $items   = [];
        $check   = [];

        if (is_array($result) && !empty($result['success']) && isset($result['data']) && is_array($result['data']) && isset($result['data']['trackingId'])) {

            $track_id = $result['data']['trackingId'];

            // Bazı hesaplarda status sonucu geç düşebiliyor, birkaç kez dene
            $check = [];
            for ($i = 0; $i < 6; $i++) {
                $check = $this->check_status($track_id, $api_info);
                if (isset($check['data']) && is_array($check['data']) && !empty($check['data'])) {
                    break;
                }
                sleep(5);
            }

            // Hepsiburada status dönüşü çoğunlukla $check['data']['products'] şeklinde gelir
            $productsList = [];
            if (isset($check['data']['products']) && is_array($check['data']['products'])) {
                $productsList = $check['data']['products'];
            } elseif (isset($check['data']) && is_array($check['data'])) {
                $productsList = $check['data'];
            }

            if ($productsList) {
                foreach ($productsList as $product) {

                    // Barcode / SKU yakalama
                    // HB status dönüşünde barcode her zaman gelmeyebiliyor; merchantSku çoğu zaman barkod ile aynı
                    $barcode = null;
                    if (isset($product['barcode']) && $product['barcode'] !== '') {
                        $barcode = $product['barcode'];
                    } elseif (isset($product['merchantSku']) && $product['merchantSku'] !== '') {
                        $barcode = $product['merchantSku'];
                    } elseif (isset($product['merchant_sku']) && $product['merchant_sku'] !== '') {
                        $barcode = $product['merchant_sku'];
                    }

                    $merchantSku = isset($product['merchantSku']) ? $product['merchantSku'] : null;
                    $hbSku       = isset($product['hbSku']) ? $product['hbSku'] : null;

                    // Ürün status
                    $itemStatus = isset($product['status']) ? $product['status'] : null;

                    // Hata mesajlarını toparlayalım
                    $failureReasons = [];

                    if (isset($product['errors']) && is_array($product['errors']) && !empty($product['errors'])) {

                        foreach ($product['errors'] as $error) {

                            // errors dizisi genelde ['code' => ..., 'message' => ...] şeklinde
                            if (is_array($error) && isset($error['message'])) {
                                $failureReasons[] = $error['message'];
                            } elseif (is_string($error)) {
                                $failureReasons[] = $error;
                            } else {
                                // hiçbiri değilse komple jsonla ekle
                                $failureReasons[] = json_encode($error, JSON_UNESCAPED_UNICODE);
                            }
                        }

                        // En az bir üründe hata varsa genel status'ü false yap
                        if (!empty($failureReasons)) {
                            $status = false;
                            $message .= implode(' - ', $failureReasons) . ' | ';
                        }
                    }

                    // Sonuç items listesine push
                    $items[] = [
                        'barcode'        => $barcode,
                        'merchantSku'    => $merchantSku,
                        'hbSku'          => $hbSku,
                        'status'         => $itemStatus,
                        'failureReasons' => $failureReasons,
                    ];
                }
            }

            // Eğer hiç hata yoksa genel mesajı başarıya çek
            if ($status && !$message) {
                $message = 'Güncelleme isteği Hepsiburada mağazanıza başarıyla gönderildi. Hepsiburada tarafından onaylandıktan sonra güncelleme aktif olacaktır.';
            }
        } else {
            // Import cevabı beklenen formatta gelmediyse Notice üretmeden anlamlı hata dön
            $status = false;

            if (is_array($result)) {
                if (!empty($result['message'])) {
                    $message = $result['message'];
                } elseif (!empty($result['error'])) {
                    $message = $result['error'];
                } else {
                    $message = 'Hepsiburada yanıtı beklenen formatta değil: ' . json_encode($result, JSON_UNESCAPED_UNICODE);
                }
            } else {
                $message = 'Hepsiburada yanıtı alınamadı (boş/parse edilemedi).';
            }
        }

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

// Trendyol’da yaptığımız gibi barcode ile ilişkilendirilmiş sonucu döndürelim
        return [
            'status'      => $status,
            'message'     => $message,
            'trackingId'  => isset($track_id) ? $track_id : null,
            'items'       => $items,  // <<< barcode / merchantSku / hbSku + status + failureReasons
        ];


        }


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

        $status = false;


        if (true) {
            $status = true;
            $url = $this->katalog_url . '/product/api/products/status/' . $product_data . '?version=1&page=0&size=1000';


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


            return $result;


        }
    }
    public function check_update_status($product_data, $api_info)
    {
        $this->merchant_id = $api_info['merchant_id'];
        $this->service_key = $api_info['service_key'];



            $url = $this->katalog_url . '/ticket-api/api/integrator/status/' . $product_data;


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


            print_r($result);
            return $result;

    }

    public function findInStr($samanlik, $igne)
    {

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

            return false;

        } else {
            return true;
        }

    }

    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 product_send($token, $json)
    {
        $url = $this->katalog_url . 'product/api/products/import?version=1';
        $uid = uniqid();
        $cid = uniqid();
        // #region agent log
        @file_put_contents('/home/premiummarketcom/public_html/.cursor/debug.log', json_encode([
            'sessionId' => 'debug-session',
            'runId' => 'hb-debug',
            'hypothesisId' => 'H?',
            'location' => 'system/library/marketplace/hb.php:product_send:enter',
            'message' => 'HB product_send enter',
            'data' => [
                'url' => $url,
                'merchant_id_len' => is_string($this->merchant_id) ? strlen($this->merchant_id) : null,
                'service_key_len' => is_string($this->service_key) ? strlen($this->service_key) : null,
                'payload_bytes' => is_string($json) ? strlen($json) : null
            ],
            'timestamp' => round(microtime(true) * 1000)
        ], JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);
        // #endregion

        $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_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        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_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_HEADER, true);

        curl_setopt($ch, CURLOPT_USERPWD, $this->merchant_id . ":" . $this->service_key);

        //curl_setopt($ch, CURLOPT_HEADER, true);
        $headers = array(
            'Content-Type: multipart/form-data; boundary=----WebKitFormBoundary' . $uid,
            'Accept: application/json',
            // API tarafında bazı çağrılarda merchantId header'ı gerekli olabiliyor
            'merchantId: ' . $this->merchant_id,
            'Cache-Control: no-cache',
            'Content-Length: ' . strlen($curlPost),
            // 100-continue davranışını kapat (bazı WAF/proxy katmanlarında sorun çıkarabiliyor)
            'Expect:'
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $_content = curl_exec($ch);
        $errno = curl_errno($ch);
        $err   = curl_error($ch);
        $http  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $ctype = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $rawHeaders = null;
        $body = $_content;
        if (is_string($_content) && is_int($headerSize) && $headerSize > 0) {
            $rawHeaders = substr($_content, 0, $headerSize);
            $body = substr($_content, $headerSize);
        }

        $statusLine = null;
        $headerHints = [];
        if (is_string($rawHeaders)) {
            $lines = preg_split("/\\r\\n|\\n|\\r/", trim($rawHeaders));
            $statusLine = $lines && isset($lines[0]) ? $lines[0] : null;
            $wanted = ['server'=>true,'date'=>true,'content-type'=>true,'x-request-id'=>true,'x-correlation-id'=>true,'x-amz-cf-id'=>true,'x-cache'=>true,'cf-ray'=>true,'x-iinfo'=>true];
            foreach ($lines as $ln) {
                $p = strpos($ln, ':');
                if ($p === false) continue;
                $k = strtolower(trim(substr($ln, 0, $p)));
                if (!isset($wanted[$k])) continue;
                $v = trim(substr($ln, $p + 1));
                $v = mb_substr((string)$v, 0, 180);
                $v = preg_replace('/[A-Za-z0-9\\-_=]{20,}/', '[redacted]', $v);
                $headerHints[$k] = $v;
            }
        }

        // #region agent log
        $prefix = is_string($body) ? mb_substr($body, 0, 220) : null;
        if (is_string($prefix)) $prefix = preg_replace('/[A-Za-z0-9\\-_=]{20,}/', '[redacted]', $prefix);
        @file_put_contents('/home/premiummarketcom/public_html/.cursor/debug.log', json_encode([
            'sessionId' => 'debug-session',
            'runId' => 'hb-debug',
            'hypothesisId' => 'H?',
            'location' => 'system/library/marketplace/hb.php:product_send:after_exec',
            'message' => 'HB product_send response',
            'data' => [
                'http_code' => $http,
                'content_type' => $ctype,
                'status_line' => $statusLine,
                'header_hints' => $headerHints,
                'curl_errno' => $errno,
                'curl_error' => $errno ? mb_substr((string)$err, 0, 180) : null,
                'body_prefix' => $prefix
            ],
            'timestamp' => round(microtime(true) * 1000)
        ], JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);
        // #endregion

        // SSL/cert sorunlarında 1 kez verify kapatıp tekrar dene (bazı sunucularda CA eksik olabiliyor)
        if ($_content === false && in_array($errno, [35, 60, 77], true)) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            $_content = curl_exec($ch);
            $errno = curl_errno($ch);
            $err   = curl_error($ch);
            $http  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $ctype = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        }

        curl_close($ch);

        if ($_content === false) {
            if ($this->log) {
                $this->log->write(['hb_product_send_curl_error' => ['errno' => $errno, 'error' => $err, 'http_code' => $http, 'url' => $url]]);
            } else {
                error_log('hb_product_send_curl_error errno=' . $errno . ' error=' . $err . ' http=' . $http);
            }
            return [
                'success' => false,
                'message' => 'HB bağlantı hatası: ' . $err,
                'errno' => $errno,
                'http_code' => $http
            ];
        }

        $decoded = json_decode($body, 1);
        if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) {
            if ($this->log) {
                $this->log->write(['hb_product_send_invalid_json' => ['http_code' => $http, 'content_type' => $ctype, 'url' => $url, 'raw' => mb_substr((string)$body, 0, 2000)]]);
            } else {
                error_log('hb_product_send_invalid_json http=' . $http . ' raw=' . substr((string)$body, 0, 500));
            }
            return [
                'success' => false,
                'message' => 'HB yanıtı JSON değil/bozuk. HTTP: ' . $http,
                'http_code' => $http
            ];
        }

        if (is_array($decoded) && $http >= 400 && empty($decoded['success'])) {
            $decoded['success'] = false;
            if (empty($decoded['message'])) {
                $decoded['message'] = 'HB HTTP hata kodu: ' . $http;
            }
        }

        return $decoded;
    }


    public function product_update_send($token, $json)
    {
        $url = $this->katalog_url . 'ticket-api/api/integrator/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_USERPWD, $this->merchant_id . ":" . $this->service_key);

        //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',
                'User-Agent: miryazilim_dev',
                '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);
    }


    public function getProductsByStatus($api_info)
    {

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

        $url = "https://mpop.hepsiburada.com/product/api/products/products-by-merchant-and-status?merchantId=" . $this->merchant_id . "&productStatus=PRE_MATCHED&taskStatus=false&version=1&page=0&size=100";


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


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

    }


    public function rejectMatchProduct($api_info, $matched_products)
    {
        $this->merchant_id = $api_info['merchant_id'];
        $this->service_key = $api_info['service_key'];

        $url = "https://mpop.hepsiburada.com/product/api/products/reject-prematch";



        $data[]=array('merchant'=>$this->merchant_id,'merchantSkuList'=>$matched_products);


        $curl = curl_init();

        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($data),
            CURLOPT_HTTPHEADER => array(
                'Authorization: Basic ' . base64_encode($this->merchant_id . ':' . $this->service_key),
                'User-Agent: miryazilim_dev',
                'Content-Type: application/json',
                'Cookie: JSESSIONID=671E23CC6DD0A40D089E335D20B86B9C'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;



    }


    public function getUnApprovedProducts($api_info, $filter)
    {


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

        $url = "https://mpop.hepsiburada.com/product/api/products/products-by-merchant-and-status?merchantId=".$this->merchant_id ."&productStatus=".$filter['status']."&version=1&page=".$filter['page']."&size=".$filter['limit'];

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


        return json_decode($result,1);

    }
    public function approveMatchProduct($api_info, $matched_products)
    {
        $this->merchant_id = $api_info['merchant_id'];
        $this->service_key = $api_info['service_key'];

        $url = "https://mpop.hepsiburada.com/product/api/products/approve-prematch";



        $data[]=array('merchant'=>$this->merchant_id,'merchantSkuList'=>$matched_products);


        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://mpop.hepsiburada.com/product/api/products/approve-prematch',
            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($data),
            CURLOPT_HTTPHEADER => array(
                'Authorization: Basic ' . base64_encode($this->merchant_id . ':' . $this->service_key),
                'User-Agent: miryazilim_dev',
                'Content-Type: application/json',
                'Cookie: JSESSIONID=671E23CC6DD0A40D089E335D20B86B9C'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;



    }

    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->merchant_id . ':' . $this->service_key),
                'Content-Type: application/xml',
                'User-Agent: miryazilim_dev'

            );
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            $curl_response = curl_exec($curl);
            //print_r($curl_response);

        }

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


    }


    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>';
    }

    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', 'User-Agent: miryazilim_dev');
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        }

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

        if ($method == 'GET') {
            $headers = array(
                "merchantId: " . $this->merchant_id,
                'User-Agent: miryazilim_dev'
            );
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');


        }
        curl_setopt($ch, CURLOPT_USERPWD, $this->merchant_id . ":" . $this->service_key);

        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 get_products($product_data, $api_info)
    {
        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);

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

        $url = $this->listUrl . '/Listings/merchantid/' . $this->merchant_id . '?offset=' . ($product_data['page'] * $product_data['itemcount']) . '&notsalable-listings='.$product_data['on_sale'].'&limit=' . $product_data['itemcount'];
        // $url = $this->listUrl . '/listings/merchantid/' . $this->merchant_id;
        //$url = "https://listing-external-sit.hepsiburada.com/listings/merchantid/". $this->merchant_id ."?offset=0&limit=2000";


        //    https://listing-external-sit.hepsiburada.com/listings/merchantid/{merchantid}?offset=0&limit=2000

        $result = $this->clientConnect($url, 'getProducts', $this->token, 'GET', null);
        //$products = $this->xmlToArray($result);

        $return = array();
        $productdata = json_decode($result, true);

        //print_r($productdata);return;

        if (isset($productdata['listings'])) {
            $return['Listings']['Listing'] = $productdata['listings'];
            $return['TotalCount'] = $productdata['totalCount'];
            $return['limit'] = $productdata['limit'];
            $return['offset'] = $productdata['offset'];
        }

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

    }


    public function getProducts2($product_data, $api_info)
    {
        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);

        $this->merchant_id = $api_info['merchant_id'];
        $this->service_key = $api_info['service_key'];
        $url = "https://mpop.hepsiburada.com/product/api/products/products-by-merchant-and-status?merchantId=" . $this->merchant_id . "&productStatus=MISSING_INFO&page=1&size=100";
        // $url = $this->listUrl . '/listings/merchantid/' . $this->merchant_id;
        //$url = "https://listing-external-sit.hepsiburada.com/listings/merchantid/". $this->merchant_id ."?offset=0&limit=2000";

        echo $url;
        //    https://listing-external-sit.hepsiburada.com/listings/merchantid/{merchantid}?offset=0&limit=2000

        $result = $this->clientConnect($url, 'getProducts', $this->token, 'GET', null);
        //$products = $this->xmlToArray($result);

        $return = array();
        $productdata = json_decode($result, true);

        //print_r($productdata);return;



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


    }

    public function get_product($product_data, $api_info)
    {


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

        $url = $this->listUrl . '/listings/merchantid/' . $this->merchant_id . '?merchantskulist=' . implode(',', $product_data);


        $productdata = json_decode($this->clientConnect($url, 'getProducts', $this->token, 'GET', null), 1);


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

    }
}