<?php

class ModelCatalogProductFinder extends Model
{
    public function addUrl2($price,$url, $barcode, $code, $user_info)
    {

        $query = $this->db->query("select count(*) as total from product_url where `url` = '" . $url . "'");


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

            $this->db->query("INSERT INTO `product_url` SET user_id='" . $user_info['user_id'] . "', `stock_code`='" . $this->db->escape($barcode) . "', `barcode`='" . $this->db->escape($barcode) . "', `url`='" . $url . "', `sale_price` ='" . $price . "', $code=1, date_added=NOW() ");

        } else {


            $this->db->query("UPDATE `product_url` SET  $code=1, date_added=NOW() WHERE url='" . $url . "'");

        }
    }

    public function get_n11_category_attr($category_id, $attr_list)
    {
        $this->load->model('tool/entegrasyon_api');

        $attr = array();

        $query = $this->db->query("select * from n11_category_attributes where category_id='" . $category_id . "'");
        $result = $this->n11->category_attributes($category_id, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('n11'), $debug = false);


        if ($query->num_rows) {
            $result = unserialize($query->row['attributes']);



        } else  {


            $result = $this->n11->category_attributes($category_id, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('n11'), $debug = false);
           if($result['status']){
               $this->db->query("insert into n11_category_attributes SET attributes='" . $this->db->escape(serialize($result)) . "', category_id='" . $category_id . "'");

           }

        }

        

        foreach ($result['result'] as $item) {


            //if($item['required']){

            $bestMatchIndex = $this->yaklasik_index($attr_list, $item['name'], 50);




            if ($bestMatchIndex !== null) {
                //echo "aranan".$item['name']." bulunan En yakın indeks: $bestMatchIndex\n";




                $bestMatchValue = $this->yaklasik_deger_n11($item['values'], $attr_list[$bestMatchIndex], 80);

               // echo $attr_list[$bestMatchIndex].'-'.$bestMatchValue;

                // $selected_val=$attr_list[$bestMatchIndex]
                // $bestMatchValue=$this->yaklasik_deger($values['data']);

              if($item['name']=='Marka'){
                   $attr[]=array('name'=>'Marka','value'=>'Diğer');


              }else {
                  $attr[] = array('name'=>$item['name'],'value'=>$attr_list[$bestMatchIndex]);

              }


            } else {

                if($item['name']=='Marka'){
                    $attr[]=array('name'=>'Marka','value'=>'Diğer');


                }else {
                    $attr[] =array('name'=>$item['name'],'value'=>isset($item['values']['name'])?$item['values']['name']:$item['values'][0]['name']); ;

                }


                //print_r($item);
                // echo "Eşik değere göre yakın bir indeks bulunamadı.\n";
              /*  $values = $this->hb->getAttributeValues($category_id, $item['id']);

                if (isset($values['data'][0])) {
                    $attr[$item['id']] = $values['data'][0];

                }*/



                //$attr[$item['attribute_id']] = 353;


            }


        }

        return $attr;

    }

    public function get_hb_category_attr($category_id, $attr_list)
    {
        $this->load->model('tool/entegrasyon_api');

        $attr = array();


        $query = $this->db->query("select * from hb_category_attributes where category_id='" . $category_id . "'");

        if ($query->num_rows) {
            $result = unserialize($query->row['attributes']);


        } else {
            $result = $this->hb->category_attributes($category_id, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('hb',$user_database_id), $debug = false);
            $this->db->query("insert into hb_category_attributes SET attributes='" . $this->db->escape(serialize($result)) . "', category_id='" . $category_id . "'");

        }


        foreach ($result['result'] as $item) {


            //if($item['required']){

            $bestMatchIndex = $this->yaklasik_index($attr_list, $item['name'], 80);

            if ($bestMatchIndex !== null) {
                //echo "aranan".$item['name']." bulunan En yakın indeks: $bestMatchIndex\n";

                // $selected_val=$attr_list[$bestMatchIndex]
                $bestMatchValue = $this->yaklasik_deger($item['values'], $attr_list[$bestMatchIndex], 80);


                if ($bestMatchValue) {
                    $attr[$item['id']] = $attr_list[$bestMatchIndex];
                } else {

                    if (isset($item['values'])) {
                        $attr[$item['id']] = $item['values'][0]['value'];

                    }
                }


            } else {


                // echo "Eşik değere göre yakın bir indeks bulunamadı.\n";

                if (isset($item['values'])) {
                    $attr[$item['id']] = isset($item['values'][0]['value']) ? $item['values'][0]['value'] : 0;

                }

            }


        }

        return $attr;

    }


    public function yaklasik_index($array, $searchKey, $threshold)
    {


        $bestMatch = null;
        $bestMatchScore = 0;

        foreach ($array as $key => $value) {
            similar_text($key, $searchKey, $similarityPercentage);

            if ($similarityPercentage >= $threshold && $similarityPercentage > $bestMatchScore) {
                $bestMatch = $key;
                $bestMatchScore = $similarityPercentage;
            }
        }

        return $bestMatch;
    }

    public function yaklasik_deger($array, $searchKey, $threshold)
    {


        $bestMatch = null;
        $bestMatchScore = 0;

        foreach ($array as $key => $value) {
            similar_text($value['value'], $searchKey, $similarityPercentage);

            if ($similarityPercentage >= $threshold && $similarityPercentage > $bestMatchScore) {
                $bestMatch = $key;
                $bestMatchScore = $similarityPercentage;
            }
        }

        return $bestMatch;
    }


    public function yaklasik_deger_n11($array, $searchKey, $threshold)
    {


        $bestMatch = null;
        $bestMatchScore = 0;

        if(isset($array['name'])){

            similar_text($array['name'], $searchKey, $similarityPercentage);

            if ($similarityPercentage >= $threshold && $similarityPercentage > $bestMatchScore) {
                $bestMatch = 0;
                $bestMatchScore = $similarityPercentage;
            }


        }else {
            foreach ($array as $key => $value) {


                similar_text($value['name'], $searchKey, $similarityPercentage);

                if ($similarityPercentage >= $threshold && $similarityPercentage > $bestMatchScore) {
                    $bestMatch = $key;
                    $bestMatchScore = $similarityPercentage;
                }
            }
        }



        return $bestMatch;
    }


    public function atrr_list($attr)
    {

        $list = array();
        foreach ($attr as $item) {


            $list[$item['key']['name']] = $item['value']['name'];

        }

        return $list;
    }


    public function get_pz_category_attr($category_id)
    {
        $this->load->model('tool/entegrasyon_api');

        $attr = array();

        $result = $this->pz->category_attributes($category_id, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('pz'), $debug = false);

        foreach ($result['result'] as $item) {
            if ($item['required']) {
                $attr[] = array(
                    'attributeId' => $item['id'],
                    'attributeValueId' => $item['values'][0]['id']
                );
            }

        }

        return $attr;

    }


    public function kelimeKontrol($metin)
    {
        $yasakliKelimeler = array("üründen en fazla", "kampanyasına dahil", "fiyatından satılmak", "tarafından","tıklayın","satış fiyatını", "satıcı tarafından");
        foreach ($yasakliKelimeler as $kelime) {
            if (stripos($metin, $kelime) !== false) {
                return false;
            }
        }
        return true;
    }

    public function get_description($data)
    {




        $description = array();
        foreach ($data as $datum) {
            if ($this->kelimeKontrol($datum['text'])) {
                $description[] = $datum['text'];

            }
        }


// Uygun açıklamayı bulana kadar döngüyü çalıştır


        return implode('<br>', $description);


    }

    public function findIn($val,$attributes,$find_id)
    {

        foreach ($attributes['result']['categoryAttributes'] as $categoryAttribute) {
            if($categoryAttribute['attribute']['id']==$find_id){

                foreach ($categoryAttribute['attributeValues'] as $item) {

                    if($item['name']==$val){
                        return $item['id'];
                    }
                }
                
            }

        }
        
    }

    public function find_attibutes($name, $attibutes)
    {


        foreach ($attibutes as $attibute) {

            if (strtolower($attibute['key']['name']) == strtolower($name)) {
                return $attibute['value']['name'];
            }

        }

    }


    public function find_in_category_attributes($ty_attributes, $category_attibute)
    {


        foreach ($ty_attributes as $attibute) {


            if ($attibute['key']['name'] == $category_attibute['attribute']['name']) {

                //print_r($category_attibute);
                // return $attibute['value']['name'];

                $value_id = $this->find_in_attribute_values($attibute['value']['name'], $category_attibute['attributeValues']);


                $attribute_id = $category_attibute['attribute']['id'];


                if ($value_id && $attribute_id) {
                    return array('attributeId' => $attribute_id, 'attributeValueId' => $value_id);
                }


            }

        }

        //echo "bulamadım";
        return false;


    }

    public function find_in_attribute_values($name, $values)
    {

        foreach ($values as $value) {

            if ($name == $value['name']) {

                return $value['id'];
            }

        }

        return 0;
    }

    public function addUrl($product_data, $barcode, $code, $sale_status)
    {

        $url=$product_data['url'];
        $query = $this->db->query("select count(*) as total from product_url where `url` like '" . $url . "'");


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

            $this->db->query("INSERT INTO `product_url` SET user_id='" . $this->user->getId() . "', `stock_code`='" . $this->db->escape($barcode) . "', `barcode`='" . $this->db->escape($barcode) . "', `url`='" . $url . "', `sale_price` ='" . $product_data['price'] . "', $code=1 ");
          //  $this->db->query("insert into market_product SET code='" . $code . "', `stock_code`='" . $this->db->escape($barcode) . "', `barcode`='" . $this->db->escape($barcode) . "',model='" . $this->db->escape($barcode) . "',`sale_price` ='" . $product_data['price'] . "',`list_price` ='" . $product_data['price'] . "',quantity=1,name='" . $this->db->escape($product_data['name']) . "',sale_status='" . (int)$sale_status . "' ");

        } else {


            $this->db->query("UPDATE `product_url` SET  $code=1 WHERE url='" . $url . "'");
          //  $this->db->query("insert into market_product SET code='" . $code . "', `stock_code`='" . $this->db->escape($barcode) . "', `barcode`='" . $this->db->escape($barcode) . "',model='" . $this->db->escape($barcode) . "',`sale_price` ='" . $product_data['price'] . "',`list_price` ='" . $product_data['price'] . "',quantity=1,name='" . $this->db->escape($product_data['name']) . "',sale_status='" . (int)$sale_status . "' ");

        }
    }

    public function get_attributes($category_id, $attr_ty)
    {


        $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']) {
                    $renk = $this->find_attibutes('renk', $attr_ty);
                    if ($renk) {
                        $attributes[] = array('attributeId' => 47, 'customAttributeValue' => $renk);

                    } else {
                        $attributes[] = array('attributeId' => 47, 'customAttributeValue' => "Görsel");

                    }

                } else {

                    $attr_info = $this->find_in_category_attributes($attr_ty, $categoryAttribute);


                    if ($attr_info) {

                        $attributes[] = $attr_info;


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

                    }


                }

            }
        }

        return $attributes;

    }

    private function required($attributes)
    {
        $required_list=array();
        foreach ($attributes as $attribute) {
            //if($attribute['required']){
                $required_list[]=$attribute['attribute']['id'];
           // }

        }

        return $required_list;

    }

    public function get_attributes2($product,$category_id)
    {
        //1=kadın,2=erkek,3=kız çocuk,4=erkek çocuk

        //print_r($product['attributes']);
        $attributes = array();

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


        $required_list = $this->required($result['result']['categoryAttributes']);

       // print_r($product);return ;


      // print_r($gender);

        if(isset($product['categoryTopRankings']['url'])) {
            $gender = explode('webGenderId=',$product['categoryTopRankings']['url']);

            if ($gender[1]) {


              //  return ;

                if (in_array(343, $required_list)) {
                    $attrvalueid = ($gender[1] == 1 || $gender[1] == 3) ? 4295 : 4294;
                    $attributes[] = array(
                        'attributeId' => 343,
                        'attributeValueId' => $attrvalueid
                    );
                }

                          if (in_array(346, $required_list)) {
                    $attrvalueid = ($gender[1] == 1 || $gender[1] == 2) ? 4293 : 4291;
                    $attributes[] = array(
                        'attributeId' => 346,
                        'attributeValueId' => $attrvalueid
                    );
                }



            }
        }else if(isset($product['gender']['name'])){
          $cinsiyet =  $product['gender']['name'];

            if (in_array(343, $required_list)) {
                $attrvalueid = ($cinsiyet == 'Kadın' || $cinsiyet == 'Kız') ? 4295 : 4294;
                $attributes[] = array(
                    'attributeId' => 343,
                    'attributeValueId' => $attrvalueid
                );
            }

            if (in_array(346, $required_list)) {
                $attrvalueid = ($cinsiyet == 'Kadın' || $cinsiyet == 'Erkek') ? 4293 : 4291;
                $attributes[] = array(
                    'attributeId' => 346,
                    'attributeValueId' => $attrvalueid
                );
            }

        }



        if($product['variants'][0]['attributeId']){

            $attributes[] = array(
                'attributeId' => $product['variants'][0]['attributeId'],
                'attributeValueId' => $this->findIn($product['variants'][0]['attributeValue'],$result,338)
            );
        }

        foreach ($product['attributes'] as $item) {

            if($item['key']['id']==348){
                $attributes[] = array('attributeId' => 47, 'customAttributeValue' =>$item['value']['name']) ;

            }else if(in_array($item['key']['id'], $required_list)) {
                if($item['value']['id']) {
                    $attributes[] = array(
                        'attributeId' => $item['key']['id'],
                        'attributeValueId' => $item['value']['id']
                    );
                }
            }



        }




        return $attributes;

    }

    public function calculate_price($ty_price)
    {

        $price = $ty_price;

        if ($ty_price > 0 && $ty_price < 100) {
            $price = $ty_price * 9;
        } else if ($ty_price >= 100 && $ty_price < 300) {
            $price = $ty_price * 7;
        } else if ($ty_price >= 300 && $ty_price < 500) {
            $price = $ty_price * 6;
        } else if ($ty_price >= 500 && $ty_price < 700) {
            $price = $ty_price * 5.5;
        } else if ($ty_price >= 700 && $ty_price < 1000) {
            $price = $ty_price * 5;
        } else if ($ty_price >= 1000 && $ty_price < 1500) {
            $price = $ty_price * 4.5;
        } else if ($ty_price > 1500 && $ty_price < 2000) {
            $price = $ty_price * 4;
        } else if ($ty_price > 3000 && $ty_price < 4000) {
            $price = $ty_price * 4;

        } else if ($ty_price > 4000 && $ty_price < 5000) {
            $price = $ty_price * 4;

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

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

    }

    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 ellc()
    {

        $url = "https://www.ellconline.com/image/ellc-lisans1.jpeg";
        $desc = "<hr><h2>875 TL değerindee eLLC  kendi kendine dil öğrenme kursu hediye!</h2><p style='font-size: large'>eLLC ile 17 dilden birini seçin ve 3 ayda yeni dilinizde konuşmaya başlayın. <br> eLLC Tüm Akıllı telefon, Tablet ve bilgisayarlarda çalışan eLLC Dil öğrenme programı sanal zeka ile kurgulanmış yöntemi ile okuma, yazma, dinleme ve konuşma yeteneklerinizi birlikte geliştirecek ve farkında olmadan yeni dilinizi gramer kuralları ile ve doğru telaffuzları ile öğreneceksiniz. Yani aynı anadilinizi öğrendiğiniz gibi. </p><h2> 875 tl değerindeki eLLC kartınız ile 17 dilden birini seçip dil öğrenmeye başlayabilirsiniz.</h2><br><img src='https://www.ellconline.com/image/ellc-lisans-2.jpeg' />";

        return array('image' => $url, 'desc' => $desc);

    }


}