<?php

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

class ControllerProductSell extends Controller
{



    public function index()
    {

        $filePath = DIR_IMAGE . 'catalog/easyentegre';

        // $this->deleteFolderAndFiles($filePath);


        $this->load->model('entegrasyon/general');
        $this->model_entegrasyon_general->loadPageRequired();
        $this->load->language('catalog/product');

        $this->document->setTitle($this->language->get('heading_title'));
        if (isset($this->request->get['filter_name'])) {
            $filter_name = $this->request->get['filter_name'];
        } else {
            $filter_name = '';
        }
        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }


        if (isset($this->request->get['filter_manufacturer'])) {
            $filter_manufacturer = $this->request->get['filter_manufacturer'];
        } else {
            $filter_manufacturer = false;
        }


        if (isset($this->request->get['filter_seller'])) {
            $filter_seller = $this->request->get['filter_seller'];
        } else {
            $filter_seller = false;
        }



        $urli = '';

        if ($filter_name) {
            $urli .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
        }
        if ($this->marka) {
            $urli .= '&marka=' . urlencode(html_entity_decode($this->request->get['marka'], ENT_QUOTES, 'UTF-8'));
        }




        if ($filter_manufacturer) {
            $urli .= '&filter_manufacturer=' . $this->request->get['filter_manufacturer'];
        }


        if ($filter_seller) {
            $urli .= '&filter_seller=' . $this->request->get['filter_seller'];
        }


        $data['products'] = array();


        if ($filter_name) {
            $keywords = explode(' ', $this->request->get['filter_name']);

            $max = (int)$page + 5;


            for ($i = $page; $i < $max; $i++) {



                $url = "https://apigw.trendyol.com/discovery-web-searchgw-service/v2/api/filter/sr?sst=BEST_SELLER&q=" . implode(' ', $keywords) . '&pi=' . $i . '&prc=200-8000';

                if ($filter_manufacturer) {
                    // $url.='&wb='.$filter_name;
                    $url = "https://apigw.trendyol.com/discovery-web-searchgw-service/v2/api/filter/sr?wb=" . $filter_name . "&pi=" . $i;

                }
                if ($filter_seller) {
                    // $url.='&wb='.$filter_name;
                    $url = "https://apigw.trendyol.com/discovery-web-searchgw-service/v2/api/filter/sr?mid=" . $filter_name . "&os=1&pi=" . $i . "&culture=tr-TR&userGenderId=2&pId=0&isLegalRequirementConfirmed=false&searchStrategyType=DEFAULT&productStampType=TypeA&scoringAlgorithmId=2&fixSlotProductAdsIncluded=true&searchAbDecider=Suggestion_A%2CRelevancy_1%2CFilterRelevancy_1%2CListingScoringAlgorithmId_1%2CSmartlisting_2%2CSuggestionBadges_B%2CProductGroupTopPerformer_B%2COpenFilterToggle_2%2CSuggestionStoreAds_A%2CBadgeBoost_A%2CRF_1";


                }






                $datam=file_get_contents($url);

                $content = json_decode($datam, 1);



                if (!isset($content['error'])) {


                    foreach ($content['result']['products'] as $product) {



                        // if (isset($product['ratingScore'])) {
                        $url = explode('?', $product['url'])[0];
                        $url_info = $this->db->query("select *  from product_url where  url like  '" . $this->db->escape($url) . "'")->row;

                        $product['url_info'] = $url_info;
                        $product['url']=$url;


                        if (!in_array($product['name'], $this->productss)) {
                            if (!$url_info) {
                                if (!in_array($product['brand']['name'], $this->markalarim)) {


                                    $data['products'][] = $product;
                                    $this->productss[] = $product['name'];

                                }

                            } else {


                                //if($this->db->query("select count(*) as total from product_url where barcode like ='%".$product."%'"))
                                if ($url_info['user_id'] == $this->user->getId()) {
                                    if (!in_array($product['brand']['name'], $this->markalarim)) {
                                        if (!$url_info['hb'] or !$url_info['ty']) {
                                            $data['products'][] = $product;
                                            $this->productss[] = $product['name'];
                                        }


                                    }


                                }
                            }
                            // }
                        }

                    }
                }


            }


            //print_r($content);return
            // $data['products'] = $content['result']['products'];

            //}

            //print_r($data['products']);return;


        }


        $this->document->addScript("https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.6.4/jquery.colorbox-min.js");


        $data['filter_name'] = $filter_name;
        $data['filter_manufacturer'] = $filter_manufacturer;

        $data['filter_seller'] = $filter_seller;

        $data['previous_page'] = $this->url->link('catalog/product',  $urli . '&page=' . ($page - 1), true);

        $page = $page + 10;

        $data['next_page'] = $this->url->link('catalog/product',  $urli . '&page=' . $page, true);


        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

        $data['user_id'] = $this->user->getId();

        $marketplaces = $this->db->query("select * from entegrasyon where entegrasyon_group_id=1 and status = 1 ")->rows;
        foreach ($marketplaces as $marketplace) {
            $user_marketplace_info = $this->db->query("select count(*) as total from database_entegrasyon where database_id='" . $this->user->getDbId() . "' and entegrasyon_id='" . $marketplace['entegrasyon_id'] . "'  ");

            $data[$marketplace['code']] = $user_marketplace_info->row['total'];


        }
        $this->response->setOutput($this->load->view('catalog/product_list', $data));


    }


    public function sell_product()
    {

        $this->load->model('tool/image');
        $this->load->model('catalog/product');
        $this->load->model('entegrasyon/addproduct');
        $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='" . $this->user->getUserName() . "'")->row;


        if (isset($this->request->get['hediye'])) {

            $this->hediye = $this->request->get['hediye'];

        } else {

            $this->hediye = false;
        }


        // $url = 'https://www.trendyol.com/arcelik/cm-3940-m-cay-makinasi-p-41167510?boutiqueId=61&merchantId=149869';
        $type = $this->request->post['data_type'];
        // $type = "new";


        $barcode = '';
        $status = false;

        // $urls=explode(',',$this->request->post['url']);




        if(is_array($this->request->post['url'])){
            foreach ($this->request->post['url'] as $item) {
                if($item){
                    $url_list[]=array('url'=>$item);

                }

            }
        }else {
            $url_list[]=array('url'=>$this->request->post['url']);


        }


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




        if ($type == 'hb') {


            $this->hb($products);
            return;
        }

        if ($type == 'cs') {

            $this->cs($products);
            return;
        }
        if ($type == 'n11') {

            $this->n11($products);
            return;
        }

        if ($type == 'pz') {

            $this->pz($products);
            return;
        }

        // $product['name']=$product['name'].' Garantili';


        // print_r($product);return;

        $trendyol_products=array();
        $this->load->model('entegrasyon/product/marketplace/ty');

        foreach ($products as $product) {


            $trendyol_products['items'][] = array(
                'barcode' => (string)$product['barcode'],
                'listPrice' => $this->model_entegrasyon_addproduct->calculate_price($product['price']),
                'salePrice' => $this->model_entegrasyon_addproduct->calculate_price($product['price']),
                'vatRate' => (int)$product['tax_rate'],
                'productMainId' => (string)$product['product_main_id'],
                'brandId' => (int)$product['brand_id'],
                'categoryId' => (int)$product['category_id'],
                'quantity' => 2,
                'stockCode' => (string)$product['barcode'],
                'currencyType' => 'TRY',
                'images' => $product['images'],
                'description' => $product['description_text'],
                'attributes' => $product['present_attributes'],
                'title' => $product['product_name']
            );

        }



        //print_r($attributes);return;
        // print_r($trendyol_products);

        //  echo json_encode($trendyol_product);return;
        //print_r(json_decode($exploded_data[0],1));
        // return;

//print_r($attributes);return;;



        if($trendyol_products){

            $result = $this->ty->sell_products($trendyol_products, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('ty'));

//print_r($result);

            if ($result['result']) {

                echo json_encode(array('status' => true, 'message' => $result['message'], 'price' => $product['price']));

                foreach ($products as $product) {

                    $this->model_catalog_product->addUrl($product, $product['barcode'], 'ty', 0);
                }
            } else {

                if ($result['message'] == 'Trendyol:Tüm Ürün özelliklerini tekrar güncelleyebilmek için 10 dakika beklemelisiniz.') {

                    foreach ($products as $product) {

                        $result['status'] = true;
                        $this->model_catalog_product->addUrl($product, $product['barcode'], 'ty', 0);
                    }
                } else if (strpos($result['message'], "bulunduğundan") !== false) {
                    foreach ($products as $product) {

                        $result['status'] = true;
                        $this->model_catalog_product->addUrl($product, $product['barcode'], 'ty', 1);
                    }
                }

                echo json_encode(array('status' => false, 'message' => $result['message']));
            }


        }



        // echo "Barkod:".$barcode;


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


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


    }

    public function sell_product_bulk()
    {

        $this->load->model('tool/image');
        $this->load->model('catalog/product');
        $this->load->model("tool/entegrasyon_api");

        if (isset($this->request->post['url'])) {
            $url = 'https://www.trendyol.com' . str_replace('&amp;', '&', $this->request->post['url']);
        } else {
            $url = '';
        }

        $totals = $this->request->post['total'];
        $sira = $this->request->post['sira'];

        // echo $totals;


        if (isset($this->request->get['hediye'])) {

            $this->hediye = $this->request->get['hediye'];

        } else {

            $this->hediye = false;
        }


        // $url = 'https://www.trendyol.com/arcelik/cm-3940-m-cay-makinasi-p-41167510?boutiqueId=61&merchantId=149869';
        $type = "cs";
        // $type = "new";


        $barcode = '';
        $status = false;

        // $url="https://www.trendyol.com/samsung/50bu8100-50-127-ekran-uydu-alicili-4k-ultra-hd-smart-led-tv-p-339346369?boutiqueId=61&merchantId=113458";
        //echo $url;return;

        //$url="https://www.trendyol.com/kiwi/ksi-6440-portatif-buharli-kirisik-giderici-dikey-utu-seyahat-utusu-p-639426459";
        $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]);
        $exploded_data2 = explode('window.__PRODUCT_DETAIL_APP_INITIAL_STATE__ =', $attr[1]);

        if (isset($exploded_data2[1])) {
            $exploded_data3 = explode('window.TYPageName="product_detail"', $exploded_data2[1]);

        } else {
            $exploded_data3[0] = array();
        }


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

        } else if (isset($exploded_data3[0])) {

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


        } else {

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

        }


        // print_r($product);return;


        $attributes = array();

        // print_r($product['attributes']);return;
        $prefix = $this->config->get('ty_setting_model_prefix');


        $images = array();


        foreach ($product['images'] as $index => $item) {


            if ($index < 7) {

                //$image=$this->model_tool_image->upload('https://cdn.dsmcdn.com/' . $item, $product['variants'][0]['barcode'].$index);
                $images[] = array('url' => 'https://cdn.dsmcdn.com' . $item);

            }


        }

        if ($this->hediye && count($images) < 7) {
            $images[] = array('url' => $this->model_catalog_product->{$this->hediye}()['image']);
        }


        // sleep(3);


        if (isset($images[1])) {
            $ikinci_eleman = $images[1];
            array_splice($images, 1, 1); // Diziden ikinci elemanı çıkaralım
            array_unshift($images, $ikinci_eleman); // İkinci elemanı dizinin başına ekleyelim
        }


        $product['images'] = $images;


        //shuffle($images);


        // $description='575 tl değerinde 17 dil seçenekli sıfırdan ileri seviye eLLC interaktif yabancil dil eğitim programı hediyeli, 7 den 77 ye herkes için dil eğitimi.<br>';
        $description = $product['name'] . '<br>' . $this->model_catalog_product->get_description($product['contentDescriptions']);


        $price = $this->model_catalog_product->calculate_price($product['price']['sellingPrice']['value']);


        $product['price'] = $price;
        $product['description'] = $description;
        $product['url'] = $url;


        $query = $this->db->query("select * from oc_category where ty='" . $product['originalCategory']['id'] . "'");


        $category_id = isset($query->row['cs']) ? $query->row['cs'] : 0;
        if (!$category_id) {
            $message = "kategori eşleşmemiş";
            if ($sira == $totals) {
                $sira = 0;
            } else {
                $sira++;
            }

            echo json_encode(array('sira' => $sira, 'total' => $totals, 'status' => false, 'message' => $message));

            return;

        }


        $prefix = $this->config->get('ty_setting_model_prefix');


        $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('cs');


        if ($this->isKnownBrand($product['metaBrand']['name'])) {

            $brand_id = $product['metaBrand']['id'];
            //echo "marka=".$product['metaBrand']['name'];
            $product['marka'] = $product['metaBrand']['name'];


        } else {

            $teknotrust = 2089075;

            $brand_id = $teknotrust;
            $product['marka'] = "TeknoTrust";

        }



        $barcode = $product['variants'][0]['barcode'] . $prefix;

        $marka = $this->marka ? $this->marka : $product['metaBrand']['name'];
        $cs_product = array(
            'productName' => (string)$product['name'],
            'mainProductCode' => (string)$barcode,
            'stockCode' => (string)$barcode,
            'categoryId' => (int)$category_id,
            'description' => str_replace($this->yasakli_kelimeler, '', $product['description']),
            //'medialink' => '',
            'deliveryMessageType' => 4,
            'deliveryType' => 2,
            'stockQuantity' => 1,
            'barcode' => (string)$barcode,
            'salesPrice' => $product['price'],
            'images' => array(),
            'attributes' => array(),
        );


        foreach ($product['images'] as $key => $image) {
            if ($key < 5) {

                $cs_product['images'][] = $image['url'];
            }
        }
        /* if(count($product_data['images'])>1) {
             $ikinci_eleman = $product['images'][1];
             array_splice($product['images'], 1, 1); // Diziden ikinci elemanı çıkaralım
             array_unshift($product['images'], $ikinci_eleman); // İkinci elemanı dizinin başına ekleyelim
         }*/

        // print_r($cs_product);return

        $query = $this->db->query("select ca.attribute_id,(select attribute_value_id from oc_attribute_value where attribute_id=ca.attribute_id limit 0,1) as value from `oc_category_attribute` ca where ca.category_id='" . $category_id . "' and ca.required=1");

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


            $product["attributes"][] = array(
                'id' => $item['attribute_id'],
                'valueId' => $item['value'],
            );

        }
        //print_r($product);return;


        $result = $this->cs->sell_product($cs_product, $api_info);


        if ($result['status']) {
            $result['message'] = "ürün çiçeksepeti mağazanıza başarıyla gönderildi.";
            $this->model_catalog_product->addUrl($product, $barcode, 'cs', 1);

            $res = array('status' => true, 'message' => $result['message'], 'price' => $product['price']);


        } else {

            if (strpos($result['message'], 'zaten mevcut') !== false) {
                $this->model_catalog_product->addUrl($product, $barcode, 'cs', 1);
                $result['status'] = true;

            }

            $res = $result;
        }
        $sira++;

        if ($sira > $totals) {
            $sira = 0;
        }

        $res['sira'] = $sira;
        $res['total'] = $totals;
        echo json_encode($res);


    }
    private function isKnownBrand(string $input): bool {


        foreach ($this->markalar as $brand) {
            // trim() çünkü bazı öğelerde baş/son boşluk var
            if (stripos($input, trim($brand)) !== false) {
                return true;
            }
        }

        return false;
    }





}


