<?php

class ControllerEntegrasyonAddproduct extends Controller
{
    private $markalar = array("arzum", "MİR", "ellc", "MEDITERIAN", "NIDAGE", "Mir Eğitim ve Yazılım", "LENOVO", "Elenberg", "woodhub", "HiTech", "teknotrust", "nikadu", "knittingtr", "knitpro", 'easytekno', "Rose", "dede", "sunplus", "MAGBOX", "Globex", "Skytech", " NEXT NEXTSTAR ", "Astra", "FANTOM", "Tois Baby", "ALDEBA", "Star", "Dede Oyuncak", "LETS GO BABY", "Tois 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", "altus", "singer", "rubenis", "ALTUNAY", "king", "Uğur", "tulip", "lykke", "babyliss");
    private $proxies = array("https://www.nikadu.com.tr", "https://www.colezium.com", "https://www.deilmi.com", "https://www.ozdleather.com");
    private $yasakli_kelimeler = array("irtibat", "ağrı", "menşe", "selülit", "cyclo", "kargo", "mikrop", "bakteri", "Cyclo", "iletişim", "trendyol", "delici", "kesici", "bakteri", "Bakteri", "kırışıklık");

    private $reg = '';

    private $target = null;
    private $source = null;

    private $user_info = null;
    private $log = null;

    private $products = array();

    public function __construct($registry)
    {

        parent::__construct($registry);

        $this->reg = $registry;
        $this->log = new \Log('product.log');
    }

    protected function loadConfig()
    {
        $this->registry->set('uconfig', new Uconfig());
        $query = $this->db->query("SELECT * FROM setting");
        foreach ($query->rows as $setting) {
            if (!$setting['serialized']) {
                $this->config->set($setting['key'], $setting['value']);
            } else {
                $this->config->set($setting['key'], json_decode($setting['value'], true));
            }
        }

    }


    public function index()
    {

        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);


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


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

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

        $user_info_query = $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='" . USERNAME . "' ");
        $active_market = "ty";

        $user_info = $user_info_query->row;


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


        $queryp = $this->db->query("select * from auto_update where auto_type=2 and status=1 order by auto_update_id DESC ");

        if (!$queryp->row) {

            echo 'bitti';
            return;

        }


        $main_url = $queryp->row['url'];
        $page = $queryp->row['current_page'];
        $total_page = $queryp->row['total_page'];
        $brand_id = $queryp->row['brand_id'] ? $queryp->row['brand_id'] : BRAND_ID;


        $products = $this->model_entegrasyon_addproduct->get_products($main_url, $user_info, $page);


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

            $url_list[] = array('url' => $product);
        }


        if ($products == 4) {

            echo '404';
            return;
        }

        if ($page > $total_page) {

            echo 'iptal';

            $this->db->query("update auto_update SET `status`=0 where `auto_update_id`='" . $queryp->row['auto_update_id'] . "'");

            return;
        }


        $market_products = array();


        //print_r($products);


        $result = $this->model_entegrasyon_addproduct->get_trendyol_products($url_list, $user_info);


        foreach ($result as $product_info) {


            $category_info = json_decode(file_get_contents("http://79.98.31.162/index.php?route=appi/category/get_category&category_id=" . $product_info['category_id']), 1);


            if (!$category_info['category_info']['hb']) {

                $this->db->query("update auto_update SET `status`=0, `recycle`='" . $product_info['category_id'] . "' where `auto_update_id`='" . $queryp->row['auto_update_id'] . "'");

                return;
            }


            $product_info['brand_id_2'] = $brand_id;
            // sleep(1);
            // $product_info = $this->model_entegrasyon_addproduct->get_product($url, $this->user_info);


            $market_products[] = $product_info;


            $query = $this->db->query("select count(*) as total from ready_product where url like '" . $this->db->escape($product_info['url']) . "' ");

            if (!$query->row['total']) {

                echo 'eklendi!';

                $this->db->query("insert into ready_product  SET user_id='" . $user_info['user_id'] . "', content ='" . $this->db->escape(serialize($product_info)) . "', url='" . $product_info['url'] . "', date_added=NOW() ");

            } else {


                echo ' daha önce eklendi';

            }


        }

        //  print_r($market_products);

        if ($page < $total_page) {
            $page++;
            $status = 1;
        } else {

            $status = 0;
        }

        $this->db->query("update auto_update SET current_page='" . $page . "', status='" . $status . "' where auto_update_id='" . $queryp->row['auto_update_id'] . "'");


        // print_r($market_products);


    }

    public function test()
    {
        $this->load->model("entegrasyon/addproduct");

        $productName = 'MASA LAMBASI MUTFAK TEZGAH ALTI BANYO DOLABI DOLAP İÇİ KABLOSUZ 3LÜ KUMANDALI VE PİLLİ LED';
        $promptTitle = "Lütfen yalnızca 100 karakteri aşmayacak şekilde, aşağıdaki ürün adı için Türkçe bir e-ticaret başlığı oluştur:\n"
            . "{$productName}";

        $generatedTitle = $this->model_entegrasyon_addproduct->callOpenAI($promptTitle, 70);
        $generatedDesc = $this->model_entegrasyon_addproduct->callOpenAI($promptTitle, 70);

        print_r($generatedTitle);

    }

    public function updatehbproducts()
    {

        $products = $this->getProducts();

    }

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

        $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' => true
            )
        );

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


    public function sell_now()
    {

        $ty_enable = TY_ENABLE;

        // $this->reg->set('db', new DB\Userdb(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, USERNAME));

        // $this->loadConfig();
        $this->load->model("tool/entegrasyon_api");
        $this->load->model("entegrasyon/addproduct");
        $this->load->model("catalog/product_finder");
        $this->load->model("tool/image");
        $this->load->model("tool/entegrasyon_api");
        $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='" . USERNAME . "'")->row;

        $query = $this->db->query("select * from ready_product where status=0  and user_id='" . $user_info['user_id'] . "' order by product_id  limit 100 ");

        $market_products = array();


        if (!$query->rows) {

            return;

        }

        $i = 0;

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

            $base_product = unserialize($item['content']);


            $product_url = $this->db->query("select * from product_url where url like '%" . $item['url'] . "%'")->row;

            if ($base_product['barcode']) {


                $cs_opened = false;
                if ($product_url) {

                    $cs_opened = $product_url['cs'] ? true : false;
                }

                if (!$cs_opened) {
                    $product = $this->model_entegrasyon_addproduct->cs($base_product, $user_info);


                    if (isset($product['attributes']['Barcode'])) {
                        $product['url'] = $item['url'];
                        $product['barcode'] = $product['attributes']['Barcode'];
                        $product['price'] = $product['attributes']['price'];
                    }


                    $market_products['cs'][] = $product;
                    //  print_r($market_products);

                }


                $ty_opened = false;
                if ($product_url) {

                    $ty_opened = $product_url['ty'] ? true : false;
                }

                if ($ty_enable && !$ty_opened && TY_ENABLE) {

                    $product_ty = $this->model_entegrasyon_addproduct->ty($base_product);
                    $product_ty['url'] = $item['url'];
                    $product_ty['barcode'] = $product_ty['barcode'];
                    $product_ty['price'] = $product_ty['salePrice'];
                    $market_products['ty'][] = $product_ty;


                }


                $hb_opened = false;
                if ($product_url) {

                    $hb_opened = $product_url['hb'] ? true : false;
                }

                if (!$hb_opened) {
                    $product = $this->model_entegrasyon_addproduct->hb($base_product, $user_info);


                    if (isset($product['attributes']['Barcode'])) {
                        $product['url'] = $item['url'];
                        $product['barcode'] = $product['attributes']['Barcode'];
                        $product['price'] = $product['attributes']['price'];
                    }


                    $market_products['hb'][] = $product;
                    //  print_r($market_products);

                }


            }
            $i++;

         
        }



        if (isset($market_products['hb']) ) {


            //print_r($market_products['hb']);
            $hb_result = $this->hb->sell_products($market_products['hb'], $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('hb', $user_info['database_id']));

            print_r($hb_result);

        }

        if (isset($market_products['cs'])) {


            //print_r($market_products['hb']);
            $cs_result = $this->cs->sell_product($market_products['cs'], $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('cs', $user_info['database_id']));

            print_r($cs_result);

        }


        if (isset($market_products['ty'])) {

            $trendyol_product['items'] = $market_products['ty'];

            $ty_result = $this->ty->sell_products($trendyol_product, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('ty', $user_info['database_id']));

            print_r($ty_result);
        }


        foreach ($market_products['hb'] as $market_product) {


            if (isset($market_product['barcode'])) {
                $this->model_catalog_product_finder->addUrl($market_product, $market_product['barcode'], 'hb', 1, $user_info);
                echo $market_product['barcode'] . 'eklendi!';
            }


        }

        foreach ($market_products['cs'] as $market_product) {


            if (isset($market_product['barcode'])) {
                $this->model_catalog_product_finder->addUrl($market_product, $market_product['barcode'], 'cs', 1, $user_info);
                echo $market_product['barcode'] . 'eklendi!';
            }


        }

        foreach ($market_products['ty'] as $market_product) {


            if (isset($market_product['barcode'])) {
                $this->model_catalog_product_finder->addUrl($market_product, $market_product['barcode'], 'ty', 1, $user_info);
                echo $market_product['barcode'] . 'eklendi!';
            }


        }


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


            $this->db->query("update ready_product SET status=1 where product_id='" . $item['product_id'] . "'");
            // $this->model_catalog_product_finder->addUrl($market_product, $market_product['barcode'], 'ty', 1, $user_info);

        }

        //  print_r($market_products);
        return;


        /*   if ($market_products['ty']) {
               $trendyol_product['items'] = $market_products['ty'];

               $ty_result = $this->ty->sell_products($trendyol_product, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('ty', $user_info['database_id']));
               $hb_result = $this->hb->sell_products($trendyol_product, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('hb', $user_info['database_id']));

           }


           if (isset($ty_result['result']['batchRequestId'])) {
               foreach ($market_products['ty'] as $market_product) {

                   $this->model_catalog_product_finder->addUrl($market_product, $market_product['barcode'], 'ty', 1, $user_info);

               }
           }

           if (isset($hb_result['data']['trackingId'])) {
               foreach ($market_products['ty'] as $market_product) {

                   $this->model_catalog_product_finder->addUrl($market_product, $market_product['barcode'], 'hb', 1, $user_info);

               }
           }

   */
    }


}