<?php class ControllerEntegrasyonUpdateProduct extends Controller
{
    private $reg;
    private $username = "admin";
    private $password;
    private $shopId;
    private $proxies = [
        "https://www.nikadu.com.tr",
        "https://www.colezium.com",
        "https://www.deilmi.com",
        "https://www.ozdleather.com"
    ];

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


    public function db_check()
    {

        // Veritabanı bağlantısını yapalım (OpenCart'da zaten mevcut)
        $query = $this->db->query("SHOW COLUMNS FROM `product_url` LIKE 'status'");

// Eğer 'status' sütunu yoksa, ALTER TABLE ile sütunu ekleyelim
        if (!$query->num_rows) {
            $this->db->query("ALTER TABLE `product_url` ADD `status` INT(1) NOT NULL AFTER `ty`");
        }


    }

    public function update_db()
    {

        $this->db->query("ALTER TABLE `product_url`
ADD COLUMN IF NOT EXISTS `httpcode` INT(3) NULL;
");

    }


    public function update_again()
    {

        return;

        // Sayfa yüklenme süresi başlangıcı
        $start_time = microtime(true);

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

        $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 . "'");
        $limit = 50;
        $query = $this->db->query("SELECT * FROM product_url WHERE httpcode=429 ORDER BY id DESC LIMIT 0, $limit");

        $update_list = [];

        $url_list=array();


        print_r($query->rows);

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



          $url_list[]=  $item;

        }



        $bulkResults = $this->model_entegrasyon_addproduct->getProductsBulkWithRetry($url_list, 5, 2);





        foreach ($bulkResults as $res) {


            $item=$this->db->query("SELECT *  FROM `product_url` WHERE `barcode` LIKE '%".$this->db->escape($res['barcode'])."%'")->row;


         /*   if ($res['httpcode'] == 404) {
                $this->db->query("DELETE FROM `product_url` WHERE id='" . $item['id'] . "'");
                echo $res['url'] . " Silindi!";
                continue;
            }*/

            if ($res['status']) {

                if ($res['httpcode'] == 200) {


                    $status = $res['has_stock'] ? 1 : 0;
                    $this->db->query("UPDATE product_url SET `status`='" . $status . "', title='" . $this->db->escape($res['title']) . "', image='" . $this->db->escape($res['image']) . "', update_cycle = update_cycle + 1, orginal_price='" . $res['price'] . "', httpcode='".$res['httpcode']."', last_update_date = NOW() WHERE id='" . $item['id'] . "'");


                    //ürünün fiyatı 20 bin tlden büyükse ürünü kapat.
                    if ($this->model_entegrasyon_addproduct->calculate_price($res['price']) > 20000) {
                        $quantity = 0; // Set stock to 0
                    } else {
                        $quantity = !$res['has_stock'] ? 0 : 6; // Keep the original stock logic
                    }

                    $update_data = [
                        'barcode' => $item['barcode'],
                        'current_price' => $item['sale_price'],
                        'salePrice' => $this->model_entegrasyon_addproduct->calculate_price($res['price']),
                        'listPrice' => $this->model_entegrasyon_addproduct->calculate_price($res['price']),
                        'quantity' => $quantity,
                        'stock_code'=>$item['stock_code']

                    ];



                    if ($item['ty'] && $res['barcode']) {
                        $update_list['ty'][] = $update_data;
                    }
                    if ($item['hb'] && $res['barcode']) {

                        $update_data['stockCode']=$item['stock_code'];

                        $update_list['hb'][] = $update_data;
                    }
                    if ($item['cs'] && $res['barcode']) {
                        $market_product = $this->db->query("SELECT * FROM market_product WHERE barcode LIKE '%" . $item['barcode'] . "%' AND code='cs'")->row;
                        if ($market_product) {
                            if ($market_product['marketplace_product_id']) {
                                $update_list['cs'][] = array_merge($update_data, [
                                    'stock_code' => $market_product['barcode'],
                                    'marketplace_product_id' => $market_product['marketplace_product_id'],
                                ]);
                            }
                        }
                    }
                    if ($item['n11'] && $res['barcode']) {
                        $market_product = $this->db->query("SELECT * FROM market_product WHERE barcode LIKE '%" . $item['barcode'] . "%' AND code='n11'")->row;
                        if ($market_product['marketplace_product_id']) {
                            $update_list['n11'][] = array_merge($update_data, [
                                'marketplace_product_id' => $market_product['marketplace_product_id'],
                            ]);
                        }
                    }
                    if ($item['pz'] && $res['barcode']) {
                        $update_list['pz'][] = $update_data;
                    }
                } else {
                    $status = 0;

                    $this->db->query("UPDATE product_url SET `status`='" . (int)$status . "', last_update_date = NOW(), httpcode='".$res['httpcode']."' WHERE id='" . $item['id'] . "'");

                }
            }
        }




        print_r($update_list);


        if ($update_list) {
            foreach (['pz', 'cs', 'hb', 'ty', 'n11'] as $marketplace) {
                if (isset($update_list[$marketplace])) {
                    echo strtoupper($marketplace) . ' Güncelleme';
                    $className = "Marketplace\\$marketplace";
                    $this->reg->set($marketplace, new $className($this->registry));

                    $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($marketplace, $user_info_query->row['database_id']);
                    $result = $this->{$marketplace}->update_fast($update_list[$marketplace], $api_info);
                    print_r($result);
                }
            }

        } else {
            echo 'güncellenmedi!';
        }

        // Sayfa yüklenme süresi bitişi
        $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";
    }



}