<?php

class ControllerEntegrasyonHepsiburada extends Controller
{
    private $markalar = array(
        "arzum", "SerenityHaven", "MİR", "ellc", "teknotrust", "MEDITERIAN", "NIDAGE",
        "Mir Eğitim ve Yazılım", "LENOVO", "Elenberg", "woodhub", "HiTech", "nikadu",
        "knittingtr", "knitpro", "easytekno", "Rose", "dede", "sunplus", "MAGBOX",
        "Globex", "Skytech", "NEXT NEXTSTAR", "Astra", "FANTOM", "Tois Baby", "ALDEBA",
        "Star", "Dede Oyuncak", "LETS GO BABY", "Mikado", "Maxword", "TCL", "DailyTech",
        "Samsung", "DailyLink", "Vestel", "Urban Sound", "Jopus", "Jameson", "Bestway",
        "arçelik", "inFace", "beko", "Stilevs", "Bosch", "Profilo", "Electrolux",
        "Siemens", "Nilfisk", "Karcher", "Intex", "grundig", "phillips", "arnica",
        "hutt", "altus", "wiami", "npo", "onvo", "singer", "rubenis", "ALTUNAY",
        "king", "Uğur", "tulip", "lykke", "babyliss"
    );

    private $prefix_list = array('OZL', 'U6', "YK3", 'XBT', 'KRKC', 'ADN', 'YENI-SERI-2024', 'KRK', 'AHY', 'FY1', 'MU66', 'MU31', 'BL2', 'C2', 'WD2');

    private $normalizedMarkalar = array();
    private $lastPageFile = DIR_IMAGE . 'hb_last_page.txt';
    private $lastAllProductsUpdate = DIR_IMAGE . 'hb_last_update_product_page.txt';
    private $lastPageForUnApproved = DIR_IMAGE . 'hb_last_page_for_unapproved_products.txt';
    private $lastAllProductsUpdateTest = DIR_IMAGE . 'hb_last_update_product_page_test.txt';
    private $totalPages = 0;

    // “Marka uyumsuz” ürünler
    private $brandMismatch = array();

    // “Güncellenmeyen” ürünler arasında product_url'de bulunan ve bulunmayan olarak ayrılmış diziler
    private $updatableOutdated = array();
    private $missingProductUrl = array();

    private $user_info = null;
    private $api_info = null;

    public function __construct($registry)
    {
        parent::__construct($registry);
        $this->reg = $registry;

        // Marka listesini normalize edelim (baş/son boşlukları temizle + UTF-8 strtolower)
        foreach ($this->markalar as $m) {
            $key = mb_strtolower(trim($m), 'UTF-8');
            if ($key !== '') {
                $this->normalizedMarkalar[$key] = true;
            }
        }
    }

    public function index()
    {
        if (!STATUS) {
            return;
        }

        $start_time = microtime(true);


        $this->load->model("entegrasyon/addproduct");
        $this->load->model("catalog/product_finder");

        $check429 = $this->model_entegrasyon_addproduct->check429Status();

        if ($check429 > 100) {
            echo 'çok fazla 429 hatası var bir süre bekleyeceğiz';
            return;
        }


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

        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        if (file_exists($this->lastPageFile)) {
            $lastPage = (int)file_get_contents($this->lastPageFile);
        } else {
            // Dosya yoksa 0 kabul et
            $lastPage = 0;
        }

        // -------------------------
        // 1) “Bir sonraki” sayfa numarasını hesapla
        // -------------------------
        $nextPage = $lastPage;

        // ---------------------------------------------------------------------
        // 3) Kullanıcı bilgilerini çekelim (SQL enjeksiyonunu önlemek için escape)
        // ---------------------------------------------------------------------
        $this->user_info = $this->db
            ->query(
                "SELECT * FROM `oc_user_database` ud 
                 LEFT JOIN `oc_user` u 
                   ON (ud.database_id = u.user_database_id) 
                 WHERE ud.name = '" . $this->db->escape(USERNAME) . "'"
            )
            ->row;

        // ---------------------------------------------------------------------
        // 4) Marketplace sınıfını oluşturup registry’e ekleyelim
        // ---------------------------------------------------------------------
        $marketplace = "hb";
        $className = "Marketplace\\$marketplace";
        $this->reg->set($marketplace, new $className($this->reg));


        $this->api_info = $this->model_tool_entegrasyon_api
            ->getEntegrasyonApiInfo($marketplace, $this->user_info['database_id']);

        // ---------------------------------------------------------------------
        // 6) Trendyol’dan ürünleri çekelim (örnek: 100 kayıt, sayfa 102)
        // ---------------------------------------------------------------------


        $productFilter = array(
            'itemcount' => LIMIT,
            'page' => $nextPage
        );

        $apiResult = $this->getProducts($productFilter, "true", "false", false);


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

            $this->totalPages = round($apiResult['result']['TotalCount'] / LIMIT);

        } else {


            file_put_contents($this->lastPageFile, 1);
        }


        if (
            isset($apiResult['result']['Listings']['Listing']) &&
            is_array($apiResult['result']['Listings']['Listing'])) {
            foreach ($apiResult['result']['Listings']['Listing'] as $product) {


                $market_id = $product['hepsiburadaSku'];
                $barcode = $product['merchantSku'];

                $query = $this->db->query(
                    "SELECT * FROM `product_url` WHERE `barcode` = '" . $this->db->escape($barcode) . "'"
                );

                if ($query->num_rows) {
                    // Ürün product_url tablosunda mevcut → güncellenebilir
                    $this->updatableOutdated[] = array(
                        'id' => $query->row['id'],
                        'barcode' => $barcode,
                        'market_id' => $market_id,
                        'price' => $product['price'],
                        'url' => $query->row['url'],

                    );
                } else {

                    if ($product['availableStock'] < 5) {

                        $this->missingProductUrl[] = array(
                            'barcode' => $barcode,
                            'market_id' => $market_id,
                        );

                    }

                    // product_url tablosunda yok → eksik olarak kaydet

                }

            }


            $hb_update_list = array();
            $url_list = array();

            foreach ($this->updatableOutdated as $item) {
                $url_list[] = $item;
            }

            // Çok fazla URL varsa paralel istek sayısını ayarlamak için
            $bulkResults = $this->model_entegrasyon_addproduct->getProductsBulkWithRetry($url_list, 5, 2);


            foreach ($bulkResults as $index => $ty_product_info) {
                //  $item = $this->updatableOutdated[$index]; // aynı sıra korunmalı
                if ($ty_product_info) {

                    if ($ty_product_info['httpcode'] == 200) {
                        $status = $ty_product_info['has_stock'] ? QUANTITY : 0;
                        // product_url tablosunu güncelle
                        $this->db->query(
                            "UPDATE `product_url` 
                     SET `status` = '" . $status . "',
                         `title` = '" . $this->db->escape($ty_product_info['title']) . "',
                         `image` = '" . $this->db->escape($ty_product_info['image']) . "',
                         `update_cycle` = `update_cycle` + 1,
                         `orginal_price` = '" . (float)$ty_product_info['price'] . "',
                         `httpcode` = '" . $ty_product_info['httpcode'] . "',
                         `last_update_date` = NOW()
                     WHERE `stock_code` like '" . (int)$ty_product_info['barcode'] . "'"
                        );

                        // Fiyat hesaplama ve satılabilirlik
                        $calculatedPrice = $this->model_entegrasyon_addproduct->calculate_price($ty_product_info['price']);
                        if ($calculatedPrice > MAX_PRICE) {
                            $quantity = 0;
                        } else {
                            $quantity = $ty_product_info['has_stock'] ? QUANTITY : 0;
                        }

                        if ($ty_product_info['current_price'] > $calculatedPrice) {

                            $calculatedPrice = $ty_product_info['current_price'];
                        }

                        $hb_update_list[] = array(
                            'barcode' => $ty_product_info['barcode'],
                            'stockCode' => $ty_product_info['barcode'],
                            'orginal_price' => $ty_product_info['price'],
                            'salePrice' => $calculatedPrice,
                            'is_missing' => false,

                            'listPrice' => $calculatedPrice,
                            'quantity' => $quantity,
                        );
                    } else if ($ty_product_info['httpcode'] == 429) {
                        echo '429 hatası aldık';

                        $this->db->query(
                            "UPDATE `product_url` 
                     SET  `httpcode` = '" . $ty_product_info['httpcode'] . "',
                         `last_update_date` = NOW()
                     WHERE `stock_code` like '" . (int)$ty_product_info['barcode'] . "'"
                        );

                    } else {

                        $hb_update_list[] = array(
                            'barcode' => $ty_product_info['barcode'],
                            'stockCode' => $ty_product_info['barcode'],
                            'salePrice' => 0,
                            'listPrice' => 0,
                            'quantity' => 0
                        );

                    }

                } else {

                    echo 'ÜRÜN BULUNAMADI!';
                }


            }

            foreach ($this->missingProductUrl as $brandMismatch) {


                $hb_update_list[] = array(
                    'barcode' => $brandMismatch['barcode'],
                    'stockCode' => $brandMismatch['barcode'],
                    'salePrice' => 0,
                    'listPrice' => 0,
                    'quantity' => 0
                );


            }


            print_r($hb_update_list);


            $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($marketplace, $this->user_info['database_id']);
            $result = $this->{$marketplace}->update_fast($hb_update_list, $api_info);


            $writePage = $nextPage + 1;
            // Eğer bir sonraki > toplam sayfa sayısı, 1 yazarız
            if (isset($this->totalPages) && $writePage > $this->totalPages) {
                $writePage = 1;
            }
            file_put_contents($this->lastPageFile, $writePage);
            // print_r($result);
            //print_r($hb_update_list);return;

            $output = array(
                'brand_mismatch' => $this->brandMismatch,
                'updatable_outdated' => $this->updatableOutdated,
                'missing_product_url' => $this->missingProductUrl
            );


        }
        $end_time = microtime(true);

        // Geçen süreyi hesapla (saniye cinsinden)
        $execution_time = $end_time - $start_time;

        // Dakika ve saniye olarak yazdırma
        $minutes = floor($execution_time / 60);
        $seconds = $execution_time - ($minutes * 60);

        echo "Sayfa yüklenme süresi: " . $minutes . " dakika " . round($seconds, 2) . " saniye";
    }

    public function index_test()
    {

        $limit = 30;

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

        $check429 = $this->model_entegrasyon_addproduct->check429Status();

        if ($check429 > 100) {
            echo 'çok fazla 429 hatası var bir süre bekleyeceğiz';
            return;
        }


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

        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        if (file_exists($this->lastPageFile)) {
            $lastPage = (int)file_get_contents($this->lastAllProductsUpdateTest);
        } else {
            // Dosya yoksa 0 kabul et
            $lastPage = 0;
        }

        // -------------------------
        // 1) “Bir sonraki” sayfa numarasını hesapla
        // -------------------------
        $nextPage = $lastPage;

        // ---------------------------------------------------------------------
        // 3) Kullanıcı bilgilerini çekelim (SQL enjeksiyonunu önlemek için escape)
        // ---------------------------------------------------------------------
        $this->user_info = $this->db
            ->query(
                "SELECT * FROM `oc_user_database` ud 
                 LEFT JOIN `oc_user` u 
                   ON (ud.database_id = u.user_database_id) 
                 WHERE ud.name = '" . $this->db->escape(USERNAME) . "'"
            )
            ->row;

        // ---------------------------------------------------------------------
        // 4) Marketplace sınıfını oluşturup registry’e ekleyelim
        // ---------------------------------------------------------------------
        $marketplace = "hb";
        $className = "Marketplace\\$marketplace";
        $this->reg->set($marketplace, new $className($this->reg));


        $this->api_info = $this->model_tool_entegrasyon_api
            ->getEntegrasyonApiInfo($marketplace, $this->user_info['database_id']);

        // ---------------------------------------------------------------------
        // 6) Trendyol’dan ürünleri çekelim (örnek: 100 kayıt, sayfa 102)
        // ---------------------------------------------------------------------
        $productFilter = array(
            'itemcount' => $limit,
            'page' => $nextPage
        );

        $apiResult = $this->getProducts($productFilter, "true", "true", false);


        $this->totalPages = round($apiResult['result']['TotalCount'] / $limit);

        if (
            isset($apiResult['result']['Listings']['Listing']) &&
            is_array($apiResult['result']['Listings']['Listing'])) {
            foreach ($apiResult['result']['Listings']['Listing'] as $product) {


                $market_id = $product['hepsiburadaSku'];
                $barcode = $product['merchantSku'];

                $query = $this->db->query(
                    "SELECT * FROM `product_url` WHERE `barcode` = '" . $barcode . "'"
                );

                if ($query->num_rows) {
                    // Ürün product_url tablosunda mevcut → güncellenebilir
                    $this->updatableOutdated[] = array(
                        'id' => $query->row['id'],
                        'barcode' => $barcode,
                        'market_id' => $market_id,
                        'url' => $query->row['url'],

                    );
                } else {
                    // product_url tablosunda yok → eksik olarak kaydet
                    $this->missingProductUrl[] = array(
                        'barcode' => $barcode,
                        'market_id' => $market_id,
                    );
                }


            }

            $listem = null;
            $hb_update_list = array();
            $url_list = array();
            $listem[] = array('id' => 30, 'url' => '/shopdrm/3-tekerlekli-merdiven-cikan-pazar-arabasi-tekerlegi-teker-takimi-2-adet-p-774902922', 'barcode' => 'dfdsf');
            $listem[] = array('id' => 31, 'url' => '/grand-star/4-tekerlekli-alisveris-arabasi-frenli-sogutucu-torbali-50l-p-931724140', 'barcode' => 'dsfdsfds');
            foreach ($listem as $item) {
                $url_list[] = $item;
            }

            // Çok fazla URL varsa paralel istek sayısını ayarlamak için
            $bulkResults = $this->model_entegrasyon_addproduct->getProductsBulkWithRetry($url_list, 5, 2);


            print_r($bulkResults);
            return;


            foreach ($bulkResults as $index => $ty_product_info) {
                //  $item = $this->updatableOutdated[$index]; // aynı sıra korunmalı


                if ($ty_product_info['httpcode'] == 200) {
                    $status = $ty_product_info['has_stock'] ? 1 : 0;

                    // product_url tablosunu güncelle
                    $this->db->query(
                        "UPDATE `product_url` 
                     SET `status` = '" . $status . "',
                         `title` = '" . $this->db->escape($ty_product_info['title']) . "',
                         `image` = '" . $this->db->escape($ty_product_info['image']) . "',
                         `update_cycle` = `update_cycle` + 1,
                         `orginal_price` = '" . (float)$ty_product_info['price'] . "',
                         `httpcode` = '" . $ty_product_info['httpcode'] . "',
                         `last_update_date` = NOW()
                     WHERE `stock_code` like '" . (int)$ty_product_info['barcode'] . "'"
                    );

                    // Fiyat hesaplama ve satılabilirlik
                    $calculatedPrice = $this->model_entegrasyon_addproduct->calculate_price($ty_product_info['price']);
                    if ($calculatedPrice > 20000) {
                        $quantity = 0;
                    } else {
                        $quantity = $ty_product_info['has_stock'] ? 7 : 0;
                    }

                    $hb_update_list[] = array(
                        'barcode' => $ty_product_info['barcode'],
                        'stockCode' => $ty_product_info['barcode'],
                        'orginal_price' => $ty_product_info['price'],
                        'salePrice' => $calculatedPrice,
                        'listPrice' => $calculatedPrice,
                        'quantity' => $quantity,
                    );
                } else if ($ty_product_info['httpcode'] == 429) {


                    $this->db->query(
                        "UPDATE `product_url` 
                     SET  `httpcode` = '" . $ty_product_info['httpcode'] . "',
                         `last_update_date` = NOW()
                     WHERE `stock_code` like '" . (int)$ty_product_info['barcode'] . "'"
                    );

                }

            }


            foreach ($this->missingProductUrl as $brandMismatch) {


                $hb_update_list[] = array(
                    'barcode' => $brandMismatch['barcode'],
                    'stockCode' => $brandMismatch['barcode'],
                    'salePrice' => 0,
                    'listPrice' => 0,
                    'quantity' => 0
                );
            }


            $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($marketplace, $this->user_info['database_id']);
            $result = $this->{$marketplace}->update_fast($hb_update_list, $api_info);

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

            //return;

            $writePage = $nextPage + 1;
            // Eğer bir sonraki > toplam sayfa sayısı, 1 yazarız
            if (isset($this->totalPages) && $writePage > $this->totalPages) {
                $writePage = 1;
            }
            file_put_contents($this->lastAllProductsUpdateTest, $writePage);
            // print_r($result);


            //print_r($hb_update_list);return;

            $output = array(
                'brand_mismatch' => $this->brandMismatch,
                'updatable_outdated' => $this->updatableOutdated,
                'missing_product_url' => $this->missingProductUrl
            );

            print_r($output);

        }
    }


    public function update_product()
    {
        return;

        $start_time = microtime(true);

        $limit = 10;
        $this->load->model("entegrasyon/addproduct");
        $this->load->model("catalog/product_finder");

        $check429 = $this->model_entegrasyon_addproduct->check429Status();

        if ($check429 > 100) {
            echo 'çok fazla 429 hatası var bir süre bekleyeceğiz';
            return;
        }


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

        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        if (file_exists($this->lastAllProductsUpdate)) {
            $lastPage = (int)file_get_contents($this->lastAllProductsUpdate);
        } else {
            // Dosya yoksa 0 kabul et
            $lastPage = 0;
        }

        if ($lastPage == 99999999) {

            echo 'Tüm güncellemeler tamamlandı!';
            return;

        }

        // -------------------------
        // 1) “Bir sonraki” sayfa numarasını hesapla
        // -------------------------
        $nextPage = $lastPage;

        // ---------------------------------------------------------------------
        // 3) Kullanıcı bilgilerini çekelim (SQL enjeksiyonunu önlemek için escape)
        // ---------------------------------------------------------------------
        $this->user_info = $this->db
            ->query(
                "SELECT * FROM `oc_user_database` ud 
                 LEFT JOIN `oc_user` u 
                   ON (ud.database_id = u.user_database_id) 
                 WHERE ud.name = '" . $this->db->escape(USERNAME) . "'"
            )
            ->row;

        // ---------------------------------------------------------------------
        // 4) Marketplace sınıfını oluşturup registry’e ekleyelim
        // ---------------------------------------------------------------------
        $marketplace = "hb";
        $className = "Marketplace\\$marketplace";
        $this->reg->set($marketplace, new $className($this->reg));


        $this->api_info = $this->model_tool_entegrasyon_api
            ->getEntegrasyonApiInfo($marketplace, $this->user_info['database_id']);

        // ---------------------------------------------------------------------
        // 6) Trendyol’dan ürünleri çekelim (örnek: 100 kayıt, sayfa 102)
        // ---------------------------------------------------------------------
        $productFilter = array(
            'itemcount' => $limit,
            'page' => $nextPage
        );

        $apiResult = $this->getProducts($productFilter, "true", "true", false);


        $this->totalPages = round($apiResult['result']['TotalCount'] / $limit);

        if ($this->totalPages)

            if (
                isset($apiResult['result']['Listings']['Listing']) &&
                is_array($apiResult['result']['Listings']['Listing'])) {
                foreach ($apiResult['result']['Listings']['Listing'] as $product) {


                    $market_id = $product['hepsiburadaSku'];
                    $barcode = $product['merchantSku'];

                    $query = $this->db->query(
                        "SELECT * FROM `product_url` WHERE `barcode` = '" . $barcode . "'"
                    );

                    if ($query->num_rows) {
                        // Ürün product_url tablosunda mevcut → güncellenebilir
                        $this->updatableOutdated[] = array(
                            'id' => $query->row['id'],
                            'barcode' => $barcode,
                            'market_id' => $market_id,
                            'url' => $query->row['url'],

                        );
                    } else {
                        // product_url tablosunda yok → eksik olarak kaydet
                        $this->missingProductUrl[] = array(
                            'barcode' => $barcode,
                            'market_id' => $market_id,
                        );
                    }


                }


                $hb_update_list = array();
                $url_list = array();

                foreach ($this->updatableOutdated as $item) {
                    $url_list[] = $item;
                }

                // Çok fazla URL varsa paralel istek sayısını ayarlamak için
                $bulkResults = $this->model_entegrasyon_addproduct->get_trendyol_products($url_list, $this->user_info);

                $products = array();
                $updated = array();
                foreach ($bulkResults as $index => $ty_product_info) {


                    $ai_result = $this->model_entegrasyon_addproduct->generateAIContent(
                        $ty_product_info['product_name'], $ty_product_info['category_hierarchy'], $ty_product_info['color'], $ty_product_info['attributes_list'], $ty_product_info['description_text']);


                    $products[] = array(
                        "hbSku" => $ty_product_info['item']['market_id'],
                        'productName' => $ty_product_info['brand_name'] . ' ' . $ai_result['title_ai'],
                        'productDescription' => $ai_result['description_ai']
                    );

                    /*   $updated[]=array(
                           'barcode' => $ty_product_info['item']['barcode'],
                           'stockCode' => $ty_product_info['item']['barcode'],
                           'salePrice' =>  $this->model_entegrasyon_addproduct->calculate_price($ty_product_info['price']),
                           'listPrice' => $this->model_entegrasyon_addproduct->calculate_price($ty_product_info['price']),
                           'quantity' => 7);

   */
                }

                // print_r($update_data);

                // print_r($products);
                //print_r($products);

                $full_update_item = array('items' => $products, 'merchantId' => $this->api_info['merchant_id']);
                //$update_data = array('items' => $products, 'merchantId' => $this->api_info['merchant_id']);
                $result = $this->hb->update_full_product($full_update_item, $this->api_info);
                //  $update_result =$this->hb->update_fast($updated, $this->api_info);

                // print_r($result);
                //  print_r($update_result);

                $writePage = $nextPage + 1;
                // Eğer bir sonraki > toplam sayfa sayısı, 1 yazarız
                if ($writePage > $this->totalPages) {
                    $writePage = 99999999;
                }
                file_put_contents($this->lastAllProductsUpdate, $writePage);


            }

        $end_time = microtime(true);

        // Geçen süreyi hesapla (saniye cinsinden)
        $execution_time = $end_time - $start_time;

        // Dakika ve saniye olarak yazdırma
        $minutes = floor($execution_time / 60);
        $seconds = $execution_time - ($minutes * 60);

        echo "Sayfa yüklenme süresi: " . $minutes . " dakika " . round($seconds, 2) . " saniye";
    }

    public function getProducts($data = array(), $onlyApproved = "true", $onSale = "true", $debug = false)
    {
        $this->load->model('entegrasyon/general');
        $this->load->model('tool/image');

        $itemcount = isset($data['itemcount']) ? (int)$data['itemcount'] : 20;
        $page = isset($data['page']) ? (int)$data['page'] : 1;

        $post_data = array(
            'request_data' => array(
                'itemcount' => $itemcount,
                'page' => $page,
                'approved' => $onlyApproved,
                'on_sale' => $onSale
            )
        );




        return $this->hb->get_products(
            $post_data['request_data'],
            $this->api_info
        );
    }

    public function check_unapproved_products()
    {

        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        $this->load->model('tool/entegrasyon_api');

        $limit = 20;
        if (file_exists($this->lastPageForUnApproved)) {
            $lastPage = (int)file_get_contents($this->lastPageForUnApproved);
        } else {
            // Dosya yoksa 0 kabul et
            $lastPage = 0;
        }

        if ($lastPage == 99999999) {

            echo 'Tüm güncellemeler tamamlandı!';
            return;

        }

        // -------------------------
        // 1) “Bir sonraki” sayfa numarasını hesapla
        // -------------------------
        $nextPage = $lastPage;

        // ---------------------------------------------------------------------
        // 3) Kullanıcı bilgilerini çekelim (SQL enjeksiyonunu önlemek için escape)
        // ---------------------------------------------------------------------
        $this->user_info = $this->db
            ->query(
                "SELECT * FROM `oc_user_database` ud 
                 LEFT JOIN `oc_user` u 
                   ON (ud.database_id = u.user_database_id) 
                 WHERE ud.name = '" . $this->db->escape(USERNAME) . "'"
            )
            ->row;

        // ---------------------------------------------------------------------
        // 4) Marketplace sınıfını oluşturup registry’e ekleyelim
        // ---------------------------------------------------------------------
        $marketplace = "hb";
        $className = "Marketplace\\$marketplace";
        $this->reg->set($marketplace, new $className($this->reg));


        $this->api_info = $this->model_tool_entegrasyon_api
            ->getEntegrasyonApiInfo($marketplace, $this->user_info['database_id']);

        // ---------------------------------------------------------------------
        // 6) Trendyol’dan ürünleri çekelim (örnek: 100 kayıt, sayfa 102)
        // ---------------------------------------------------------------------
        $productFilter = array(
            'limit' => $limit,
            'page' => $nextPage
        );


        $apiResult = $this->hb->getUnApprovedProducts($this->api_info, $productFilter);


        $this->totalPages = round($apiResult['result']['TotalCount'] / $limit);


        $writePage = $nextPage + 1;
        // Eğer bir sonraki > toplam sayfa sayısı, 1 yazarız
        if (isset($this->totalPages) && $writePage > $this->totalPages) {
            $writePage = 99999999;
        }
        file_put_contents($this->lastPageForUnApproved, $writePage);

    }


    public function bulbakem()
    {


        $this->load->model("entegrasyon/addproduct");
        $barcode1 = "8684869480399YK3";


        $barcode = str_replace($this->prefix_list, '', $barcode1);

        echo $barcode;

        $result = $this->model_entegrasyon_addproduct->fetchTrendyolProductViaApi($barcode);

        print_r($result);

        if ($result) {

            $this->db->query("INSERT INTO `product_url` SET user_id='" . $this->user_info['user_id'] . "', `stock_code`='" . $this->db->escape($barcode) . "', `barcode`='" . $this->db->escape($barcode) . "', `url`='" . $result['link'] . "', `sale_price` ='" . $result['price'] . "', hb=1 ");
            $calculatedPrice = $this->model_entegrasyon_addproduct->calculate_price($result['price']);
            $quantity = 7;
            $hb_update_list[] = array(
                'barcode' => $barcode,
                'stockCode' => $barcode,
                'orginal_price' => $result['price'],
                'salePrice' => $calculatedPrice,
                'listPrice' => $calculatedPrice,
                'is_missing' => true,
                'quantity' => $quantity,
            );

            print_r($result);
        }
    }

    public function delete()
    {

        $this->user_info = $this->db
            ->query(
                "SELECT * FROM `oc_user_database` ud 
                 LEFT JOIN `oc_user` u 
                   ON (ud.database_id = u.user_database_id) 
                 WHERE ud.name = '" . $this->db->escape(USERNAME) . "'"
            )
            ->row;

        $this->load->model("tool/entegrasyon_api");
        $marketplace = "hb";
        $className = "Marketplace\\$marketplace";
        $this->reg->set($marketplace, new $className($this->reg));


       $this->api_info = $this->model_tool_entegrasyon_api
            ->getEntegrasyonApiInfo($marketplace, $this->user_info['database_id']);



        // ---------------------------------------------------------------------
        // 6) Trendyol’dan ürünleri çekelim (örnek: 100 kayıt, sayfa 102)
        // ---------------------------------------------------------------------


        $productFilter = array(
            'itemcount' => 100,
            'page' => 0
        );

        $apiResult = $this->getProducts($productFilter, "true", "true",false);


        $products=array();

        foreach ($apiResult['result']['Listings']['Listing'] as $product) {


          $products[]=array('marketplace_product_id'=>$product['hepsiburadaSku'],'model'=>$product['merchantSku']);
        }


        $result = $this->{$marketplace}->delete_product($products, $this->api_info);

        print_r($result);




    }

}