<?php

class ControllerEntegrasyonHbUpdate extends Controller
{

    private $reg = null;
    private $username = null;
    private $password = null;
    private $shopId = null;

    public function __construct($registry)
    {

        parent::__construct($registry);

        $this->reg = $registry;

    }

    public function index()
    {


        if (isset($_REQUEST['username'])) {
            $username = $_REQUEST['username'];
        } else if (isset($_GET['username'])) {
            $username = $_GET['username'];
        } else {

            echo 'kullanıcı bulunamadı';
            return;
        }

        $this->reg->set('udb', new DB\Userdb(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, $username));


        $this->loadConfig();

        $user_info_query = $this->db->query("SELECT * FROM `oc_user_database` where name='" . $username . "'");


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

        $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('hb', $user_info_query->row['database_id']);


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


        $queryp = $this->udb->query("select * from auto_update where auto_update_id=2");

        $page = $queryp->row['current_page'];


        $limit = 30;
        $start = 0;//($page - 1) * $limit;


        $total = $this->udb->query("select count(*) as total from product_url pu left join market_product mp ON(pu.barcode=mp.barcode)  where mp.market_product_id is NOT NULL and pu.code='hb' ")->row['total'];
        $query = $this->udb->query("select pu.barcode,mp.sale_price,pu.url,mp.market_product_id from product_url pu left join market_product mp ON(pu.barcode=mp.barcode)  where mp.market_product_id is NOT NULL and pu.code='hb' limit $start,$limit");


        echo $total;
        return;

        $total_page = round($total / $limit);


        $i = 1;


        $update_list = array();

        $status = false;

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

            $result = $this->get_product(explode('?', $item['url'])[0]);


            if (!$result['has_stock']) {
                $market_product = $this->udb->query("select * from market_product where barcode like '" . $item['barcode'] . "' and code='hb' and sale_status=1 ");

                if ($market_product->row['quantity']) {
                    $update_list[] = array(
                        "stock_code" => $item['barcode'],
                        "marketplace_product_id" => $market_product->row['marketplace_product_id'],
                        "sale_price" => 0,
                        "list_price" => 0,
                        "quantity" => 0,

                    );
                }
                echo 'Stok Tükenmiş:' . $item['barcode'] . '<br>';


            } else {
                $sql = "select * from market_product where barcode like '" . $item['barcode'] . "' and code='hb'";
                $market_product = $this->udb->query($sql);


                if ($market_product->num_rows) {



                        $update_list[] = array(
                            "stock_code" => $item['barcode'],
                            "marketplace_product_id" => $market_product->row['marketplace_product_id'],
                            "sale_price" => $result['price'],
                            "list_price" => $result['price'],
                            "quantity" => 1,

                        );



                } else {
                     echo 'ürün Listede Yok Silindi';
                    //$this->udb->query("delete from product_url where barcode like '" . $item['barcode'] . "' and code='hb'");
                }


            }
            sleep(1);

        }


        print_r($update_list);
        return;
        if ($update_list) {

            $this->reg->set('hb', new Marketplace\hb($this->registry));
            $this->reg->set('cs', new Marketplace\cs($this->registry));
            $this->reg->set('ty', new Marketplace\ty($this->registry));



            $results = $this->hb->update_fast($update_list, $api_info, true);

            print_r($results);


            foreach ($results['items'] as $item) {


                if (isset($item['requestItem'])) {

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

                        $this->udb->query("update market_product SET sale_price='" . $item['requestItem']['salePrice'] . "', quantity='" . $item['requestItem']['quantity'] . "' where barcode='" . $item['requestItem']['barcode'] . "' and code='hb'");

                    }


                }

            }


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

                $status = 1;

            }
        }

        $page++;

        if ($page >= $total_page) {

            $page = 1;
        }


        $this->udb->query("update auto_update SET current_page='" . $page . "', status='" . $status . "',total_page='" . $total_page . "',date_modified=NOW() where auto_update_id=2");


    }


    private
    function update_on_tredyol($update_list)
    {


        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/products/price-and-inventory',
            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_list),
            CURLOPT_HTTPHEADER => array(
                'Authorization: Basic ' . base64_encode("$this->username:$this->password"),
                'Content-Type: application/json',
                'Cookie: __cfruid=8b5d2adb208204a4811c0f78b79f05d976a1a90d-1685299400; _cfuvid=II_34tNJCaQvXfH1yMxntUGAhL7ob.ud.M3.9I8DdTI-1685299400267-0-604800000; __cflb=02DiuEkjxji3pxUywYoR8hKcjQvCpYR5XkY58QCPvGugx'
            ),
        ));

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

        curl_close($curl);

        sleep(20);

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


            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://api.trendyol.com/sapigw/suppliers/' . $this->shopId . '/products/batch-requests/' . $response['batchRequestId'],
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => array(
                    'Authorization: Basic ' . base64_encode("$this->username:$this->password"),
                    'Cookie: __cfruid=8b5d2adb208204a4811c0f78b79f05d976a1a90d-1685299400; _cfuvid=II_34tNJCaQvXfH1yMxntUGAhL7ob.ud.M3.9I8DdTI-1685299400267-0-604800000; __cflb=02DiuEkjxji3pxUywYoR8hKcjQvCpYR5XkY58QCPvGugx'
                ),
            ));

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

            curl_close($curl);


            return $response;


        }


    }

    public function get_product($url)
    {


        //$url="https://www.trendyol.com/philips/epilasyon-makinasi-32-cimbiz-kompakt-epilator-epilasyon-cihazi-satinelle-p-321934118?boutiqueId=61&merchantId=718238";


        $barcode = '';
        $status = false;

        //echo $url;return;
        $content = file_get_contents($url);
        //preg_match('#"barcode":"(.*?)"#si',$content,$veri);
        preg_match('#<script type="application/javascript">(.*?)</script>#si', $content, $attr);

        $exploded_data = explode('STATE__=', $attr[1]);

        if (isset($exploded_data[1])) {
            $exploded_data = explode(';window.TYPageName', $exploded_data[1]);

        } else {

            preg_match('#window.__PRODUCT_DETAIL_APP_INITIAL_STATE__ = {(.*?)#si', $attr[1], $attr2);

        }

        $product = json_decode($exploded_data[0], 1)['product'];

        $hasStock = $product['hasStock'];


        return array('has_stock' => $hasStock, 'price' => $this->calculate_price($product['price']['sellingPrice']['value']));


        // echo "Barkod:".$barcode;


        //print_r($this->request->post);


        // echo json_encode(array('status'=>$status,'barcode'=>$barcode));


    }


    private function calculate_price($ty_price)
    {

        $price = $ty_price;

        if ($ty_price > 0 && $ty_price < 100) {
            $price = $ty_price * 4;
        } else if ($ty_price > 100 && $ty_price < 300) {
            $price = $ty_price * 3.5;
        } else if ($ty_price > 300 && $ty_price < 500) {
            $price = $ty_price * 3;
        } else if ($ty_price > 500 && $ty_price < 1000) {
            $price = $ty_price * 2.8;
        } else if ($ty_price > 1000 && $ty_price < 2000) {
            $price = $ty_price * 2.6;
        } else if ($ty_price > 2000 && $ty_price < 3000) {
            $price = $ty_price * 2.5;
        } else if ($ty_price > 3000 && $ty_price < 5000) {
            $price = $ty_price * 2.3;

        } else if ($ty_price > 5000 && $ty_price < 8000) {
            $price = $ty_price * 2.2;
        } else {
            $price = $ty_price * 2;
        }

        return number_format($price, 0, '', '');

    }


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

    }


}