<?php

class ControllerCatalogProductFinder extends Controller
{
    private $error = array();


    public function index()
    {


        $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 = '';
        }
        $data['products'] = array();
        if ($filter_name) {
            $keywords = explode(' ', $this->request->get['filter_name']);


            $url = "https://public.trendyol.com/discovery-web-searchgw-service/v2/api/infinite-scroll/sr?sst=MOST_FAVOURITE&q=" . implode(' ', $keywords);

            // $url="https://www.trendyol.com/sr?q=".implode('+',$keywords);
            $content = json_decode(file_get_contents($url), 1);

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

        }

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


        $data['user_token'] = $this->session->data['user_token'];

        $data['filter_name'] = $filter_name;

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

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


    }

    public function sell_product()
    {


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

        $type = $this->request->post['data_type'];


        $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]);

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

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

        $attributes = array();

        // print_r($product['attributes']);return;


        $images = array();

        foreach ($product['images'] as $item) {
            $images[] = array('url' => 'https://cdn.dsmcdn.com/' . $item);
        }


        $query = $this->db->query("select * from " . DB_PREFIX . "category_attribute where category_id='" . $product['originalCategory']['id'] . "' and required=1");

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


        $attributes = $this->get_attributes($product['originalCategory']['id']);


        if ($type == 'new') {
            $barcode = $product['productCode'] . rand(11111, 99999);
            $brand_id = 1879199;
        } else {
            $brand_id = $product['metaBrand']['id'];

            $barcode = $product['allVariants'][0]['barcode'];

        }


        // print_r($attributes);return;

        //print_r($product);return
        $trendyol_product['items'][] = array(
            'barcode' => (string)$barcode,
            'listPrice' => 600,
            'salePrice' => 499,
            'vatRate' => (int)$product['tax'],
            'productMainId' => (string)$product['productCode'],
            'brandId' => (int)$brand_id,
            'categoryId' => (int)$product['originalCategory']['id'],
            'quantity' => (int)10,
            'stockCode' => (string)$product['productCode'],
            'currencyType' => 'TRY',
            'images' => $images,
            'description' => $product['contentDescriptions'][0]['description'] . '<br>' . $product['contentDescriptions'][1]['description'],
            'attributes' => $attributes,
            'title' => (string)$product['name']
        );


        // print_r($trendyol_product);return;

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


        $result = $this->ty->sell_product($trendyol_product, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('ty'));


        print_r($result);

        // echo "Barkod:".$barcode;


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


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


    }

    public function get_attributes($category_id)
    {

        $result = $this->ty->category_attributes($category_id, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('ty'));

        $attributes = array();
        foreach ($result['result']['categoryAttributes'] as $categoryAttribute) {

            if ($categoryAttribute['required']) {

                if ($categoryAttribute['allowCustom']) {
                    $attributes[] = array('attributeId' => 47, 'customAttributeValue' => "beyaz");

                } else {


                    $attributes[] = array('attributeId' => $categoryAttribute['attribute']['id'], 'attributeValueId' => $categoryAttribute['attributeValues'][0]['id']);


                }

            }
        }

        return $attributes;

    }


    public function category_list()
    {

        $ignore_list=array(0,1,2,3,4,6,7,8,11,12,16,17,29,30,40,41,42,43,46,59);
        $content=file_get_contents("https://www.trendyol.com/kadin-saat-x-g1-c34");
        preg_match_all('#<ul class="sub-item-list">(.*?)</ul>#',$content,$result);

        foreach ($result[0] as $index => $item) {
            preg_match_all('#<a href="(.*?)">(.*?)</a>#',$item,$link_data);

            if(!in_array($index,$ignore_list)) {


                foreach ($link_data[1] as $link) {

                    if($link){
                        $query =$this->db->query("select count(*) as total from trendyol_bot_category where name='".$link."'");

                        if($query->row['total']==0){
                            $this->db->query("insert into trendyol_bot_category SET name='".$this->db->escape($link)."'");


                        } }
                }





                //$category=$link_data[1];
                //echo $category;
            }

        }


    }

    public function bot()
    {

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];

        } else {

            $page = 1;

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

        } else {

            $cat = 0;

        }




        $total_count=$this->db->query("select count(*) as total from trendyol_bot_category where progress=0 ")->row['total'];
        echo $total_count;

        if($cat==$total_count){

            echo "tüm ürünler eklendi";
            return;

        }

        $query = $this->db->query("select name from trendyol_bot_category where progress=0 limit $cat,1  ");

        $category = str_replace('/','',$query->row['name']);


        $url = "https://public.trendyol.com/discovery-web-searchgw-service/v2/api/infinite-scroll/" . $category . "?pi=" . $page;

        //$url="https://public.trendyol.com/discovery-web-searchgw-service/v2/api/infinite-scroll/sr?wg='.$gender.'&wc='.$category.'&rp=true&pi='.$page.'&culture=tr-TR&userGenderId=1&pId=0&isLegalRequirementConfirmed=true&searchStrategyType=DEFAULT&productStampType=TypeA&scoringAlgorithmId=2&fixSlotProductAdsIncluded=true&searchAbDecider=Suggestion_A%2CRelevancy_1%2CFilterRelevancy_1%2CListingScoringAlgorithmId_1%2CSmartlisting_2%2CSuggestionBadges_A%2CProductGroupTopPerformer_B%2COpenFilterToggle_2%2CSuggestionStoreAds_B%2CBadgeBoost_A&offset=0";

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

        $data = curl_exec($curl);
        $data2 = json_decode($data, 1);

        curl_close($curl);

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

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


                $query = $this->db->query("select count(*) as total from trendyol_product where listing_id='" . $product['id'] . "'");

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

                    $sql = "insert into trendyol_product SET listing_id='" . $product['id'] . "',url='" . $product['url'] . "',image='" . $product['images'][0] . "', title='" . $this->db->escape($product['name']) . "', brand='" . $this->db->escape($product['brand']['name']) . "', brand_id='" . $product['brand']['id'] . "', list_price='" . $product['price']['discountedPrice'] . "',sale_price='" . $product['price']['originalPrice'] . "', date_added=NOW(), date_modifed=NOW() ";

                    if (isset($product['ratingScore']['averageRating'])) {
                        $sql .= ", rating='" . number_format($product['ratingScore']['averageRating'], 2) . "', comment='" . $product['ratingScore']['totalCount'] . "'";
                    }

                    $this->db->query($sql);

                }
                //  print_r($product);return;



            }
            $page++;
            $token = $this->session->data['user_token'];
            $thisurl="http://79.98.31.162/admin/index.php?route=catalog/product_finder/bot&user_token=".$token."&cat=".$cat."&page=".$page;
            echo '<meta http-equiv="refresh"
            content="0; url=' . $thisurl . '">';
        } else {


            $page=1;
            $cat++;
            $token = $this->session->data['user_token'];
            $thisurl="http://79.98.31.162/admin/index.php?route=catalog/product_finder/bot&user_token=".$token."&cat=".$cat."&page=".$page;
            echo '<meta http-equiv="refresh"
            content="0; url=' . $thisurl . '">';


        }

    }


    public function product_list()
    {




    }


}