<?php

class ControllerEntegrasyonProduct extends Controller
{
    private $markalar = array("arzum", "MİR", "ellc","MEDITERIAN","NIDAGE","eLLC", "Mir Eğitim ve Yazılım", "LENOVO", "Elenberg", "woodhub", "HiTech", "teknotrust", "nikadu", "knittingtr", "knitpro", 'easytekno', "Rose", "dede", "sunplus", "MAGBOX", "Globex", "Skytech", " NEXT NEXTSTAR ", "Astra", "FANTOM", "Tois Baby", "ALDEBA", "Star", "Dede Oyuncak", "LETS GO BABY", "Tois Baby", "Mikado", "Maxword", "TCL", " DailyTech", "Samsung", "DailyLink", "Vestel", "Urban Sound", "Jopus", "Jameson", "Bestway", "arçelik", "inFace", "beko", "Stilevs", "Bosch", "Profilo", "Electrolux", " Siemens", "Nilfisk", "Karcher", "Intex", 'grundig', 'phillips', 'arnica', "hutt", "altus", "wiami", "npo", "onvo", "altus", "singer", "rubenis", "ALTUNAY", "king", "Uğur", "tulip", "lykke", "babyliss");
    private $proxies = array("https://www.nikadu.com.tr", "https://www.colezium.com", "https://www.deilmi.com", "https://www.ozdleather.com");
    private $yasakli_kelimeler = array("irtibat", "ağrı", "menşe", "selülit", "cyclo", "kargo", "mikrop", "bakteri", "Cyclo", "iletişim", "trendyol", "delici", "kesici", "bakteri", "Bakteri", "kırışıklık");

    private $reg = '';

    private $target = null;
    private $source = null;

    private $user_info = null;
    private $log = null;

    public function __construct($registry)
    {

        parent::__construct($registry);

        $this->reg = $registry;
        $this->log = new \Log('product.log');
    }

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

    }

    public function category_matcher()
    {

        ini_set('display_errors', 0);
        ini_set('display_startup_errors', 0);
        error_reporting(0);
        $this->load->model('catalog/product_finder');

        $i=0;
        $a=0;

        $code='hb';

        $query =  $this->db->query("SELECT * FROM `oc_category` where $code=0");

        $categories = $this->db->query("select * from categories_hb")->rows;

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




            $category_name = substr($item['name'], strrpos($item['name'], '>') + 1);



            $result = $this->model_catalog_product_finder->yaklasik_deger_pz_category($categories, $category_name, 85);



            if($result){

                echo 'trendyol category:'.$category_name.'---eşleşen:'.$result['name'].'</br>';


                $sql="update oc_category SET $code='".$result['category_id']."' where id='".$item['id']."'";

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

            }else {

                $a++;
            }





        }
        echo $i.' adet kategori eşleşti. '.$a.'adet kategori eşleşmedi!';

        // $this->log->write($message - 'kategori:'.$query->row['name']);

        return;
    }


    public function sync()
    {




    }


    public function index()
    {


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


        if (isset($_REQUEST['mode'])) {
            $mode = true;
        } else {
            $mode = false;
        }

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

            $debug = true;
        }

        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();
        $this->load->model("tool/entegrasyon_api");


        $user_info_query = $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='" . $username . "'");
        $active_market = "ty";


        $user_info = $user_info_query->row;

        $this->user_info = $user_info;
        $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($active_market, $user_info['database_id']);


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

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




        $post_data['request_data'] = array('itemcount' => 100, 'page' => $page, 'approved' => 1, 'on_sale' => true);
        $result = $this->ty->get_products($post_data['request_data'], $api_info);
        $total_page = $result['result']['totalPages'];


        $update_list = array();

        print_r($update_list);

        if ($result['status']) {
            $total = $result['result']['totalElements'];
            $pages = $result['result']['totalPages'];
            if (count($result['result']['content']) > 0) {


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


                    if (!$this->checkBrand($item['brand'])) {


                        $update_list[] = array(
                            "barcode" => $item['barcode'],
                            "salePrice" => 0,
                            "brand" => $item['brand'],
                            "quantity" => 0,

                        );
                        $this->db->query("DELETE FROM `multimarket`.`product_url` WHERE barcode='" . $item['barcode'] . "' ");


                    }


                }
            }


        }


        if ($update_list) {

            $result = $this->ty->update_fast($update_list, $api_info);

            print_r($result);
        }


        if ($page < $total_page) {
            $page++;
        } else {

            $page = 1;
        }

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


    }

    private function checkBrand($brand)
    {

        foreach ($this->markalar as $item) {

            if (strtolower($item) == strtolower($brand)) {
                return true;
            }

        }

        return false;

    }






    public function add_product_cs()
    {


        // $this->source = $this->request->get['source'];
        // $this->target = $this->request->get['target'];




        $this->target = 'cs';
        $this->source ="hb";



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


        // $this->loadConfig();
        $this->load->model("tool/entegrasyon_api");
        $this->load->model("tool/image");
        $this->load->model("entegrasyon/addproduct");
        $this->load->model("catalog/product_finder");


        $user_info_query = $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='" . USERNAME . "'");


        $user_info = $user_info_query->row;


        $this->user_info = $user_info;
        $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($this->target, $user_info['database_id']);



        $query = $this->db->query("select * from product_url pu left join market_product mp on (pu.barcode=mp.barcode) where mp.code='hb' and mp.marketplace_product_id !='' and $this->source=1 and $this->target=0  limit 0,10");


        $url_list = array();
        foreach ($query->rows  as $product) {

            $url_list[] = array('url' => $product['url']);
        }


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





        $products=array();

        foreach ($result as $product_info) {



            if($product_info['has_stock']) {
                $products[] = $this->cs($product_info);

                $this->db->query("update  product_url SET cs=1 where url like '" . $product_info['url'] . "'");
            }else {
                $this->db->query("update  product_url SET cs=1 where url like '" . $product_info['url'] . "'");

            }

        }




        if($products){

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

        }


        print_r($result);

        return;


    }

    public function seo($str)
    {

        $bul = array('İ', 'Ü', 'Ç', 'Ğ', 'Ş', 'Ö', 'ı');
        $degistir = array('i', 'u', 'c', 'g', 's', 'o', 'i');
        return str_replace($bul, $degistir, $str);

    }

    private function pz($product_data)
    {

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

        if (!$query->num_rows) {
            echo json_encode(array('status' => false, 'message' => "Kategori bulunamadı!", 'price' => $product_data['price']));

            return;
        }


        $category_id = $query->row['pz'];
        if (!$category_id) {
            $message = "kategori eşleşmemiş";
            echo json_encode(array('status' => false, 'message' => $message, 'price' => $product_data['price']));

            // $this->log->write($message - 'kategori:' . $query->row['name']);

            return;
        }


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

        $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('pz', $this->user_info['user_database_id']);



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


        $query = $this->db->query("select * from pz_brand where name like '" . $product_data['metaBrand']['name'] . "'");


        $marka_id = $query->num_rows ? $query->row['brand_id'] : 'e53de732-a41b-4796-3651-08db81d96932';

        $product = array(
            'Name' => $product_data['name'],
            'DisplayName' => $product_data['name'],
            'Description' => $product_data['description'],
            'BrandId' => $marka_id,
            'Desi' => 1,
            'Code' => $barcode,
            'GroupCode' => $barcode, // Gruplandırma için ana barkod
            'StockCount' => 2,
            'VatRate' => 20,
            'ListPrice' => $product_data['price'],
            'SalePrice' => $product_data['price'],
            'CategoryId' => $category_id,

        );


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

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

                $product['images'][]['imageurl'] = $image;

            }
        }

        // print_r($product);return;


        $attr = $this->model_catalog_product_finder->get_pz_category_attr($category_id, $this->user_info['user_database_id']);


        // $query=$this->db->query("select ca.attribute_id,ca.required,(select name 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 ");

        // print_r($query->rows);return;


        $product["attributes"] = $attr;


        $result = $this->pz->sell_product($product, $api_info);


        if ($result['status']) {
            $result['message'] = "ürün Pazarama mağazanıza başarıyla gönderildi.";
            $this->model_catalog_product_finder->addUrl($product_data, $barcode, 'pz', 0);

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


        } else {

            if ($result['message'] == 'Ürününüz pazarama kataloğunda mevcuttur, onaylandığında satışa açaılacaktır.') {

                $result['status'] = true;
                $this->model_catalog_product_finder->addUrl($product_data, $barcode, 'pz', 0);


            }

            echo json_encode($result);
        }

        //echo json_encode( $result);

        //print_r(re);

    }


    private function hb($product_data)
    {


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

        if (!$query->num_rows) {
            echo json_encode(array('status' => false, 'message' => "Kategori bulunamadı!", 'price' => $product_data['price']));

            return;
        }


        $category_id = $query->row['hb'];
        if (!$category_id) {
            $message = "kategori eşleşmemiş";
            echo json_encode(array('status' => false, 'message' => $message, 'price' => $product_data['price']));

            return;
        }


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

        $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('hb',$this->user_info['user_database_id']);

        $attr_list = $this->model_catalog_product_finder->atrr_list($product_data['attributes']);


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

        $product = array(
            "categoryId" => $category_id,
            "merchant" => $api_info['merchant_id'],
            "attributes" => array(
                "merchantSku" => $barcode,
                "VaryantGroupID" => rand(111111111, 999999999),
                "Barcode" => $barcode,
                "price" => $product_data['price'],
                "stock" => 2,
                "UrunAdi" => $product_data['product_name'],
                "UrunAciklamasi" => str_replace($this->yasakli_kelimeler, '', $product_data['description']),
                "Marka" => $product_data['marka'],
                "GarantiSuresi" => 24,
                "kg" => 1,
                "tax_vat_rate" => (int)isset($product_data['tax']) ? $product_data['tax'] : 20,

            )
        );




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

                $product['attributes']['Image' . ($key + 1)] = $image;

            }
        }


        /*  if(count($product_data['images'])>1){


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

          }*/
        //print_r($product);return;


        // $query=$this->db->query("select ca.attribute_id,ca.required,(select name 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 ");

        // print_r($query->rows);return;

        foreach ($this->model_catalog_product_finder->get_hb_category_attr($category_id, $attr_list,$this->user_info['user_database_id']) as $index => $item) {


            $product["attributes"][$index] = $item;

        }

        $result = $this->hb->sell_product($product, $api_info);


        if ($result['status']) {
            $result['message'] = "ürün hepsiburada mağazanıza başarıyla gönderildi.";
            $this->model_catalog_product_finder->addUrl($product_data, $barcode, 'hb', 1, $this->user_info);
            echo json_encode(array('status' => true, 'message' => $result['message'], 'price' => $product_data['price']));


        } else {

            if ($result['message'] == 'Ürününüz hepsiburada kataloğunda mevcuttur, onaylandığında satışa açaılacaktır.') {

                $result['status'] = true;
                $this->model_catalog_product_finder->addUrl($product_data, $barcode, 'hb', 1, $this->user_info);


            }

            echo json_encode($result);
        }

        //echo json_encode( $result);

        //print_r(re);

    }


    private function cs($product_data)
    {



        $category_info=json_decode(file_get_contents("http://79.98.31.162/index.php?route=appi/category/get_category&category_id=".$product_data['category_id']),1);



        if (!$category_info['category_info']['cs']) {
            echo json_encode(array('status' => false, 'message' => "Kategori bulunamadı!", 'price' => $product_data['price']));

            return;
        }


        $category_id = $category_info['category_info']['cs'];
        if (!$category_id) {
            $message = "kategori eşleşmemiş";
            echo json_encode(array('status' => false, 'message' => $message, 'price' => $product_data['price']));

            return;
        }

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


        $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('cs', $this->user_info['user_database_id']);




        $marka = $this->marka ? $this->marka : $product_data['brand_name'];
        $product = array(
            'productName' => (string)$product_data['product_name'],
            'mainProductCode' => (string)$product_data['barcode'].$this->config->get('ty_setting_model_prefix'),
            'stockCode' => (string)$product_data['barcode'].$this->config->get('ty_setting_model_prefix'),
            'categoryId' => (int)$category_id,
            'isActive' =>true,
            'description' => str_replace($this->yasakli_kelimeler, '', $product_data['description_text']),
            //'medialink' => '',
            'deliveryMessageType' => 6,
            'deliveryType' => 2,
            'stockQuantity' => 2,
            'barcode' => (string)$product_data['barcode'].$this->config->get('ty_setting_model_prefix'),
            'listPrice' => $this->model_entegrasyon_addproduct->calculate_price(1.1*$product_data['price']),
            'salesPrice' => $this->model_entegrasyon_addproduct->calculate_price($product_data['price']),
            'images' => array(),
            'attributes' => array(),
        );




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

                $product['images'][] = $image;
            }
        }
        /* 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
         }*/

        $product["attributes"]=json_decode(file_get_contents("http://79.98.31.162/index.php?route=appi/category/get_cs_attributes&category_id=".$category_id),1)['attributes'];


        //print_r($product);return;



        //print_r($product);

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


        return $product;

        //echo json_encode( $result);

        //print_r(re);

    }

    private function getProductCode($array) {
        if (isset($array['message']) && preg_match('/Ürün kodu:\s*(\w+)/', $array['message'], $matches)) {
            return $matches[1];
        }
        return null; // Ürün kodu bulunamadıysa null döner
    }
    private function sell_product($barcode, $url)
    {

        $this->load->model('tool/image');
        $this->load->model('catalog/product_finder');


        $url = 'https://www.trendyol.com' . $url;







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



        $content = file_get_contents($url);




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


        if (!$attr) {

            echo json_encode(array('status' => false, 'message' => 'Veri Alınamadı!'));

            return;
        }


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

        //print_r($exploded_data2);return;

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

        }


        $attributes_list = array();

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

            if ($attribute['value']['name'] != 'Var' || $attribute['value']['name'] == 'Yok')
                $attributes_list[] = $attribute['value']['name'];

        }


        $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) {

                $images[] = 'https://easyentegre3.b-cdn.net/' . $this->model_tool_image->upload('https://cdn.dsmcdn.com' . $item, $product['id'] . '_' . $index, $this->user_info['username']);

            }


        }


        $product['images'] = $images;


        //shuffle($images);


        $this->load->model("tool/entegrasyon_api");
        $attributes = $this->model_catalog_product_finder->get_attributes2($product, $product['originalCategory']['id'], $this->user_info['user_database_id']);


        $woodhub = 2044041;
        $nikadu = 1344114;
        $easytekno = 1879199;
        $teknotrust = 2089075;
        $NobleVita = 2138910;
        $SerenityHaven = 2138912;
        $NIDAGE = 1574537;
        $Nikadu = 1344114;
        $MEDITERIAN=1075954;

        $barcode = $product['variants'][0]['barcode'] . $prefix;
        //$brand_id = 1879199;
        $brand_id = $product['metaBrand']['id'];
        //$product['name']=$product['name'];
        $product_code = $product['productCode'] . $prefix;

        if ($this->user_info['username'] == 'fortacigokhan') {
            $brand_id = $easytekno;
            $product['marka'] = "Easytekno";

        } else if($this->user_info['username'] == 'aliugur2011'){

            $brand_id = $woodhub;
            $product['marka'] = "Woodhub";

        }else if($this->user_info['username'] == 'adnanhasimyakut45'){

            $brand_id = $NIDAGE;
            $product['marka'] = "NIDAGE";

        }else if($this->user_info['username'] == 'lovepug'){

            $brand_id = $MEDITERIAN;
            $product['marka'] = "MEDITERIAN";

        } else {

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




        $barcode = $product['variants'][0]['barcode'] . $prefix;
        //$brand_id = 1879199;
        //$product['name']=$product['name'];
        $product_code = $product['productCode'] . $prefix;


        $product['name'] = $product['name'];


        // $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_finder->get_description($product['contentDescriptions']);

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


        $product['price'] = $price;
        $quanatity = 2;


        $product['description'] = $description;
        $product['url'] = $url;
        shuffle($attributes_list);

        if (isset($attributes_list[0])) {
            $ilk = $attributes_list[0];
            unset($attributes_list[0]);
            $product_name = (string)mb_substr($ilk . ' ' . $product['name'] . ' ' . implode(' ', $attributes_list), 0, 99);

        } else {

            $product_name = (string)mb_substr($product['name'] . ' ' . implode(' ', $attributes_list), 0, 99);

        }

        $product['product_name'] = $product_name;


        $title = $product['name'];



        if ($this->target == 'cs') {

            return $this->cs($product);


        }

        if ($this->target == 'pz') {



            return $this->pz($product);



        }


        if ($this->target == 'hb') {

            return $this->hb($product);



        }


        $trendyol_product['items'][] = array(
            'barcode' => (string)$barcode,
            'listPrice' => $price,
            'salePrice' => $price,
            'vatRate' => (int)$product['tax'],
            'productMainId' => (string)mb_substr($this->seo($product_code), 0, 10),
            'brandId' => (int)$brand_id,
            'categoryId' => (int)$product['originalCategory']['id'],
            'quantity' => (int)$quanatity,
            'stockCode' => (string)$product_code,
            'currencyType' => 'TRY',
            'images' => $images,
            'description' => $description . '<br>',
            'attributes' => $attributes,
            'title' => $product_name
        );


        //print_r($attributes);return;


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

//print_r($attributes);return;
        $result = $this->{$this->target}->sell_product($trendyol_product, $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($this->target, $this->user_info['user_database_id']));

        return $result;


    }


}



