<?php

class ControllerEntegrasyonTrendUpdate 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 {

            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('ty', $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=1");

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


        $limit = 20;
        $start = ($page - 1) * $limit;


        $total = $this->db->query("SELECT * FROM `product_url` where code='ty' ")->num_rows;
        $query = $this->db->query("select * from product_url where  limit $start,$limit");

        $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 ='" . $item['barcode'] . "' and code='ty' ");

                if ($market_product->row['quantity']) {
                    $update_list['items'][] = array(
                        "barcode" => $item['barcode'],
                        "salePrice" => 0,
                        "listPrice" => 0,
                        "quantity" => 0,

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


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

                if ($market_product->num_rows) {

                        echo '<p style="color:red">Fiyat yükselmiş güncellemek gerek, Ürün barkod:' . $item['barcode'] . ' eski fiyat:' . $market_product->row['sale_price'] . '- Yeni Fiyat' . $result['price'] . '</p>';;

                        $update_list['items'][] = array(
                            "barcode" => $item['barcode'],
                            //  "oldPrice"=>$market_product->row['sale_price'],
                            "salePrice" => $result['price'],
                            "listPrice" => $result['price'],
                            "quantity" => 1,

                        );



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


            }

        }

        if ($update_list['items']) {

            $results = $this->update_on_tredyol($update_list);


            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='ty'");

                    }


                }

            }


            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=1");


    }


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

    }


}