<?php

class Entegrasyon
{

    private $registry;
    private $udb;
    private $session;
    private $url;
    private $config;
    private $log;
    private $customer;
    private $currency;
    private $tax;
    private $installed_markets = array();

    public $marketPlaces = array('n11' => 'N11', 'gg' => 'Gittigidiyor', 'hb' => 'Hepsiburada', 'ty' => 'Trendyol', 'eptt' => 'EpttAvm', 'amz' => 'Amazon', 'cs' => 'Çiçeksepeti');

    public function __construct($registry)
    {

        
        $this->config = $registry->get('config');
        $this->session = $registry->get('session');
        $this->url = $registry->get('url');
        $this->config = $registry->get('config');
        $this->log = $registry->get('log');
        $this->customer = $registry->get('customer');
        $this->currency = $registry->get('currency');
        $this->tax = $registry->get('tax');
        $this->registry = $registry;

       // $log = new \Log('easyentegre.log');


        $this->getInstalled();

    }

    public function setUdb($db)
    {

        $this->udb=$db;


    }

    private function getInstalled()
    {


        foreach ($this->marketPlaces as $key => $marketPlace) {
            if ($this->config->get($key . '_status')) {

                $this->installed_markets[] = $key;
            }

        }

    }


    public function getSelectedAttributes($code, $product_setting, $category_setting)
    {


        if (isset($product_setting['selected_attributes'])) {
            $selected_attributes = $product_setting['selected_attributes'];

        } else if (isset($category_setting['selected_attributes'])) {
            $selected_attributes = $category_setting['selected_attributes'];

        } else {
            $selected_attributes = false;

        }


        $attributes = array();
        if ($selected_attributes) {

            foreach ($selected_attributes as $selected_attribute) {
                if ($selected_attribute['value']) {
                    $attributes[] = $selected_attribute;
                }
            }
        }

        return $attributes;

    }


    public function log($code, $message, $bulk = false)
    {

        $bulk = $bulk ? 'Bulk' : 'Manual';

        $date = date("d.m.y");

        $log = new Log('easyentegre-' . $date . '.log');
        $log->write($code . ':' . $bulk . '-' . $message);

    }






    public function getSavedApiInfos($code)
    {

        if ($code == 'gg') {

            $params = array(
                'appKey' => $this->config->get('gg_api_anahtari'),
                'appSecret' => $this->config->get('gg_api_sifre'),
                'nick' => $this->config->get('gg_site_kullanici_adi'),
                'password' => $this->config->get('gg_site_kullanici_sifresi'),
                'auth_user' => $this->config->get('gg_role_kullanici_adi'),
                'auth_pass' => $this->config->get('gg_role_kullanici_sifresi'),
            );
        } else if ($code == 'n11') {

            $params = array(
                'appKey' => $this->config->get('n11_api_key'),
                'appSecret' => $this->config->get('n11_api_secret'),

            );

        } else if ($code == 'hb') {

            $params = array(
                'merchant_id' => $this->config->get('hb_merchant_id'),
            );

        } else if ($code == 'ty') {


            $params = array(
                'username' => $this->config->get('ty_api_anahtari'),
                'password' => $this->config->get('ty_api_sifresi'),
                'shopId' => $this->config->get('ty_satici_numarasi')
            );

        } else if ($code == 'cs') {


            $params = array(
                'apiKey' => $this->config->get('cs_api_anahtari')
                // 'shopId' => $this->config->get('cs_satici_numarasi')
            );

        } else if ($code == 'eptt') {

            $params = array(
                'username' => $this->config->get('eptt_kullanici_adi'),
                'password' => $this->config->get('eptt_api_parola'),
                'shopId' => $this->config->get('eptt_magaza_id')
            );

        }


        return $params;

    }



    public function getProductByMarketId($productCode, $code)
    {
        $sql = "select product_id from `product_to_marketplace` where  $code like '%" . $productCode . "%'";


        $query = $this->udb->query("select product_id from `product_to_marketplace` where  $code like '%" . $productCode . "%' ");


        if ($query->num_rows) {

            return $this->getProduct($query->row['product_id']);

        } else {

            return false;
        }

    }



    public function updateMarketplaceProdutcsAfterOrder($products, $catalog_url, $mode = false)
    {
        $updated = array();

        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);
        foreach ($products as $product) {

            foreach ($this->marketPlaces as $code => $marketPlace) {
                $product_info = $this->getProduct($product, $code);
                $marketPlace_info = $product_info[$code] ? unserialize($product_info[$code]) : array();

                if ($marketPlace_info) {

                    $product_info = $this->getProductForUpdate($code, $product_info, 0, $mode, $catalog_url);
                    $product_info['model'] = $this->config->get($code . '_setting_model_prefix') . $product_info['model'];

                    $post_data['request_data'] = $product_info;
                    $post_data['market'] = $this->getMarketPlace($code, $catalog_url);
                    $marketplace_data = unserialize($product_info[$code]);

                    if ($product_info['quantity'] < 0) {
                        $product_info['quantity'] = 0;
                        $post_data['request_data']['quantity'] = 0;
                    }


                    if (!$marketplace_data['sale_status'] && $code != 'hb') {


                        $result['message'] = 'Ürün Satışa kapalı olduğu için güncellenmedi! ';
                        $updated[$product_info['product_id']][$code] = array('status' => false, 'message' => $result['message']);

                    } else {


                        $result = $this->clientConnect($post_data, 'update_basic', $code, false);


                        if ($result['status']) {

                            $marketplace_data = unserialize($product_info[$code]);
                            $marketplace_data['commission'] = $product_info['defaults']['commission'];
                            $marketplace_data['price'] = $product_info['sale_price'];

                            $this->addMarketplaceProduct($product_info['product_id'], $marketplace_data, $code);

                            $updated[$product_info['product_id']][$code] = array('status' => true);
                            //echo $i . ' : ' . $marketPlace['name'] . ' : ' . $product_info['name'] . '<strong style="color: #0baf5c"> Güncellendi</strong><br>';


                        } else {

                            $updated[$product_info['product_id']][$code] = array('status' => false, 'message' => $result['message']);


                            $error = $this->getError($product_info['product_id'], $code);
                            if ($error) {
                                $this->updateError($product_info['product_id'], $code, 3, $result['message']);
                            } else {
                                $this->addError($product_info['product_id'], $code, 3, $result['message']);
                            }

                        }
                    }


                    $logmesage = $product_info['model'] . ' Action:Update After Order';;
                    if ($mode) {
                        $logmesage .= '- Otomatik - Cron';
                    } else {
                        $logmesage .= '- Manuel';
                    }

                    $logmesage .= ' - Update content:' . 'Stok & Fiyat';

                    $logmesage .= '- Stock - :' . $product_info['quantity'] . ' - Sale Price:' . $product_info['sale_price'] . ' - List Price:' . $product_info['list_price'];

                    $logmesage .= '- Result:' . $result['message'];

                    $this->log($code, $logmesage, false);


                }

            }

        }


        return $updated;

    }

    public function getProductForUpdate($code, $product_info, $commission = 0, $mode = true, $catalog_url = '')
    {


        //include_once('././config.php');

        $category_setting = $this->getMarketPlaceCategory($product_info['product_id'], $code);
        $manufacturer_setting = isset($product_info['manufacturer_id']) ? $this->getMarketPlaceManufacturer($product_info['manufacturer_id'], $code) : array();
        $product_setting = $this->getSettingData($code, 'product', $product_info['product_id']);
        $defaults = $this->getDefaults($category_setting, $manufacturer_setting, $product_setting, $code);

        if ($commission) {

            $defaults['commission'] = $commission;
        } else {

            /* if($product_info[$code]){
                    $defaults['commission']=unserialize($product_info[$code])['commission'];
                }
            */

        }

        $product_info['product_setting'] = $product_setting;
        $product_info['have_discount'] = $product_info['special'] && $defaults['product_special'] ? true : false;
        if ($this->config->get("easy_setting_price_place") && $product_info[$this->config->get("easy_setting_price_place")]) {

            $product_info['price'] = $product_info[$this->config->get("easy_setting_price_place")];
            $product_info['spacial'] = $product_info[$this->config->get("easy_setting_price_place")];

        }


        if (isset($product_setting[$code . '_product_sale_price']) || isset($product_setting[$code . '_product_sale_price']) && !isset($product_setting[$code . '_product_list_price'])) {
            $product_data['sale_price'] = $product_setting[$code . '_product_sale_price'];

            if (isset($product_setting[$code . '_product_list_price'])) {

                if ($product_setting[$code . '_product_list_price'] > $product_setting[$code . '_product_sale_price']) {
                    $product_info['have_discount'] = true;
                }
                $product_info['list_price'] = $product_setting[$code . '_product_list_price'];

            }

        } else {
            $product_info['list_price'] = $this->calculatePrice($product_info['price'], $defaults, $product_info['tax_class_id'], $code, $product_info);
        }


        if (isset($product_setting[$code . '_product_sale_price']) || isset($product_setting[$code . '_product_sale_price']) && !isset($product_setting[$code . '_product_list_price'])) {
            $product_info['sale_price'] = $product_setting[$code . '_product_sale_price'];
            if (!isset($product_setting[$code . '_product_list_price'])) {
                $product_info['list_price'] = $product_info['sale_price'];
                $product_info['have_discount'] = false;

            }
        } else {
            $product_info['sale_price'] = $product_info['special'] && $defaults['product_special'] ? $this->calculatePrice($product_info['special'], $defaults, $product_info['tax_class_id'], $code, $product_info) : $product_info['list_price'];
        }


        // $product_info['list_price'] = $this->calculatePrice($product_info['price'], $defaults, $product_info['tax_class_id'], $code);
        //$product_info['sale_price'] = $product_info['special'] && $defaults['product_special'] ? $this->calculatePrice($product_info['special'], $defaults, $product_info['tax_class_id'], $code) : $product_info['list_price'];


        $product_info['defaults'] = $defaults;
        $product_info['title'] = $product_info['name'];
        $product_info['kdv'] = $this->getKdvRange($product_info['tax_class_id']);

        $product_info['quantity'] = $product_info['quantity'] > 9999 ? 100 : $product_info['quantity'];



        if (isset($category_setting[$code . '_category_id'])) {
            $category_info = explode('|', $category_setting[$code . '_category_id']);
            $product_info['category_id'] = $category_info[0];
        } else {

            $product_info['category_id'] = false;
        }


        if ($this->config->get($code . '_setting_barkod_place')) {

            $product_info['product_setting'][$code . '_barcode'] = $product_info[$this->config->get($code . '_setting_barkod_place')];

        }

        if (isset($category_info[0])) {
            $is_category_varianter = $this->isCategoryVarianter($category_info[0]);

        } else {

            $is_category_varianter = true;

        }
        if($code=='n11' || $code=='eptt'){

            $is_category_varianter = true;
        }


        $product_info['images'] = $mode ? $this->getImagesByMarketPlace($product_info['product_id'], $product_info['image'], $code, $catalog_url) : array();

        if ($this->config->get($code . '_setting_variant')) {
            if ($this->isVarianterProduct($product_info['product_id']) && $is_category_varianter ) {

                $product_variants = $this->getPoductVariants($product_info['product_id']);

                if (($code == 'ty' || $code == 'hb' || $code == 'cs') && !$mode) {

                    $variants = $this->getMarketVariantNotNeedMatchOption($product_variants, $code, $product_info['product_id'], $this->config->get($code . '_setting_model_prefix') . $product_info['model'], $catalog_url, array('tax_class_id' => $product_info['tax_class_id'], 'defaults' => $defaults));

                } else {

                    $category_id=$category_info[0]?$category_info[0]:0;

                        $variants = $this->getMarketVariant($product_variants, $code,$category_id , $product_info['product_id'], $this->config->get($code . '_setting_model_prefix') . $product_info['model'], $catalog_url, array('tax_class_id' => $product_info['tax_class_id'], 'defaults' => $defaults));



                }
                // $variants = $this->getVariants($code, $product_info['product_id'], $category_info[0]);


                $product_info['variants'] = $variants;
            } else {

                $product_info['variants'] = false;

            }


        } else {

            $product_info['variants'] = false;

        }
        $message = '';
        if (!$product_info['variants']) {


            if ($this->config->get('easy_setting_critical_stock')) {
                $product_info['quantity'] = $product_info['quantity'] <= $this->config->get('easy_setting_critical_stock') ? 0 : $product_info['quantity'];

                $message .= ' Ürün kritik stoğun altında kaldığı için stoğu 0 olarak belirlendi. kritik stok ayarınızı ayarlar sayfasından güncelleyebilirsiniz..';


            }

        }

        if ($this->config->get('easy_setting_list_price') && $this->config->get($code . '_setting_product_special')) {

            $product_info['list_price'] = $product_info['sale_price'];
            $product_info['special'] = false;

        }

        if ($mode) {

            if ($defaults['additional_content']) {
                $information = $this->getInformationDescriptions($defaults['additional_content']);

                $product_info['description'] .= '<br>' . $information;

            }


            if (isset($product_setting[$code . '_product_desciption'])) {

                $product_info['description'] = $product_setting[$code . '_product_desciption'];
            }

            $product_info['model_prefix'] = $this->config->get($code . '_setting_model_prefix');
        }

        if ($mode) {
            $message = '';
            if ($code == 'ty' || $code == 'hb') {
                if (!$product_info['manufacturer_id']) {
                    $message .= ' Ürününüz bir markaya ait olmalıdır!. Katalog->Ürünler bölümünden ürününüze bir marka ekleyin';

                } else if ($code == 'ty') {

                    if (!isset($manufacturer_setting['ty_manufacturer_id'])) {
                        $message .= ' Marka Eşleştirmesi yapmalısınız!.';
                    } else {

                        $product_info['manufacturer_id'] = $manufacturer_setting['ty_manufacturer_id'];

                    }

                }

            }

            if ($code == 'ty') {
                $product_info['attributes'] = isset($product_setting['selected_attributes']) ? $this->getTyAttributes($product_setting['selected_attributes']) : null;

            }

        }


        return $product_info;


    }


    public function getImagesByMarketPlace($product_id, $main_image, $code, $catalog_url = '', $v_mode = false)
    {

        $product_setting = $this->getSettingData($code, 'product', $product_id);

        $main_image = isset($product_setting[$code . '_main_image']) ? $product_setting[$code . '_main_image'] : $main_image;


        $images = array();
        if ($v_mode) {
            $product_images = array();
            $main_image = $v_mode;
        } else {
            $product_images = $this->getProductImages($product_id);

        }


        if (strlen($this->config->get('easy_setting_img_domain')) > 5) {
            $catalog_url = $this->config->get('easy_setting_img_domain');
        }


        if ($code == 'n11') {


            if ($this->config->get('easy_setting_img_domain') == 'null') {
                $images['image'][] = array(
                    'url' => $main_image,
                    'order' => 1);


            } else {

                if ($this->config->get('easy_setting_resize_image')) {

                    $images['image'][] = array(
                        'url' => $this->resize($main_image, 900, 900, $catalog_url),
                        'order' => 1);
                } else {

                    $images['image'][] = array(
                        'url' => $catalog_url . 'image/' . $main_image,
                        'order' => 1);
                }

            }
            $sort = 2;
            foreach ($product_images as $row => $product_image) {


                if (is_file(DIR_IMAGE . $product_image['image'])) {

                    if ($this->config->get('easy_setting_img_domain') == 'null') {
                        $images['image'][] = array(
                            'url' => $product_image['image'],
                            'order' => $row + 2);


                    } else {
                        if ($this->config->get('easy_setting_resize_image')) {


                            $images['image'][] = array(
                                'url' => $this->resize($product_image['image'], 900, 900, $catalog_url),
                                'order' => $row + 2);

                        } else {

                            $images['image'][] = array(
                                'url' => $catalog_url . 'image/' . $product_image['image'],
                                'order' => $row + 2);
                        }

                    }
                    $sort++;
                }
            }
        } else if ($code == 'gg') {


            //$main_image=$this->resize($main_image, 900, 900, $catalog_url);


            $images['photo'] [] = array(
                'url' => $this->resize($main_image, 900, 900, $catalog_url),
                'base64' => base64_encode(file_get_contents(DIR_IMAGE . $main_image)),
                'photoId' => 0);

            $sort = 1;
            foreach ($product_images as $product_image) {
                if ($sort < 8) {
                    if (is_file(DIR_IMAGE . $product_image['image'])) {

                        // $ext_image=$this->resize($product_image['image'], 900, 900, $catalog_url);

                        $images['photo'][] = array(
                            'url' => $catalog_url . 'image/' . $product_image['image'],
                            'base64' => base64_encode(file_get_contents(DIR_IMAGE . $product_image['image'])),
                            'photoId' => $sort
                        );
                        $sort++;
                    }
                }
            }


        } else if ($code == 'cs' || $code == 'ty') {
            if ($this->config->get('easy_setting_resize_image')) {

                $images[] = $this->resize($main_image, 900, 900, $catalog_url);

            } else {
                $images[] = $catalog_url . 'image/' . $main_image;


            }

            $i = 1;
            foreach ($product_images as $row => $product_image) {
                //  if ($i < 5) {


                if (is_file(DIR_IMAGE . $product_image['image'])) {

                    if ($this->config->get('easy_setting_resize_image')) {

                        $images[] = $this->resize($product_image['image'], 900, 900, $catalog_url);

                    } else {
                        $images[] = $catalog_url . 'image/' . $product_image['image'];
                    }


                    //  }
                    $i++;
                }
                if ($code == 'cs' && $i > 4) break;
                if ($code == 'ty' && $i > 7) break;

            }


        } else if ($code == 'hb' || $code == 'eptt') {

            $images[] = $catalog_url . 'image/' . $main_image;

            foreach ($product_images as $product_image) {
                if (is_file(DIR_IMAGE . $product_image['image'])) {
                    $images[] = $catalog_url . 'image/' . $product_image['image'];

                }
            }

        }


        return $images;

    }




    public function getDefaults($category, $manufacturer, $product, $code)
    {

        $default = array();

        $default['commission'] = $this->checkParameter($category, $manufacturer, $product, $code . '_commission', $code . '_setting_commission', 'easy_setting_commission');
        $default['shipping_template'] = $this->checkParameter($category, $manufacturer, $product, $code . '_shipping_template', $code . '_setting_shipping_template');
        $default['city'] = $this->checkParameter($category, $manufacturer, $product, $code . '_city', $code . '_setting_city');
        $default['shipping_time'] = $this->checkParameter($category, $manufacturer, $product, $code . '_shipping_time', $code . '_setting_shipping_time');
        $default['subtitle'] = $this->checkParameter($category, $manufacturer, $product, $code . '_product_subtitle', $code . '_setting_subtitle');
        $default['image'] = $this->checkParameter($category, $manufacturer, $product, $code . '_main_image', $code . '_setting_image');
        $default['title'] = $this->checkParameter($category, $manufacturer, $product, $code . '_title', $code . '_setting_title');
        $default['shipping_price'] = $this->checkParameter($category, $manufacturer, $product, $code . '_shipping_price', $code . '_setting_shipping_price', 'easy_setting_shipping_price');
        $default['hour'] = $this->checkParameter($category, $manufacturer, $product, $code . '_hour', $code . '_setting_hour');
        $default['minute'] = $this->checkParameter($category, $manufacturer, $product, $code . '_minute', $code . '_setting_minute');
        $default['show_time'] = $this->checkParameter($category, $manufacturer, $product, $code . '_show_time', $code . '_setting_show_time');
        $default['shipping_company'] = $this->checkParameter($category, $manufacturer, $product, $code . '_shipping_company', $code . '_setting_shipping_company');
        $default['additional_content'] = $this->checkParameter($category, $manufacturer, $product, $code . '_additional_content', $code . '_setting_additional_content', 'easy_setting_additional_content');
        $default['product_special'] = $this->checkParameter($category, $manufacturer, $product, $code . '_setting_product_special', $code . '_setting_product_special');
        $default['currency'] = $this->checkParameter($category, $manufacturer, $product, $code . '_currency', $code . '_setting_currency', 'easy_setting_currency');
        $default['domestic'] = $this->checkParameter($category, $manufacturer, $product, $code . '_domestic', $code . '_setting_domestic');
        $default['delivery_type'] = $this->checkParameter($category, $manufacturer, $product, $code . '_delivery_type', $code . '_setting_delivery_type');
        $default['delivery_message_type'] = $this->checkParameter($category, $manufacturer, $product, $code . '_delivery_message_type', $code . '_setting_delivery_message_type');
        $default['maximum_order'] = $this->checkParameter($category, $manufacturer, $product, $code . '_maximum_order', $code . '_setting_maximum_order');
        $default['need_product_weight'] = $this->checkParameter($category, $manufacturer, $product, $code . '_need_product_weight', $code . '_setting_need_product_weight');
        $default['pay_in_the_basket'] = $this->checkParameter($category, $manufacturer, $product, $code . '_pay_in_the_basket', $code . '_setting_pay_in_the_basket');
        $default['price_multiplier'] = $this->checkParameter($category, $manufacturer, $product, $code . '_price_multiplier', $code . '_setting_price_multiplier', 'easy_setting_price_multiplier');

        return $default;

    }

    public function getKdvRange($tax_class_id)
    {
        $query = $this->udb->query("SELECT rate FROM `tax_rule` tru left join tax_rate tra ON(tru.tax_rate_id=tra.tax_rate_id) where tru.tax_class_id='" . $tax_class_id . "' ");

        if ($query->num_rows) {

            return (int)$query->row['rate'];


        } else {

            return 0;


        }

    }


    public function calculatePrice($price, $default, $tax_id, $code, $product = array())
    {


        $default['commission'] = str_replace(array('%', 'yüzde', 'yuzde'), '', $default['commission']);

        // $default['commission']="22.46 TL";


        if ($this->config->get('config_currency') != 'TRY') {

            $price = $this->currency->convert($price, $this->config->get('config_currency'), 'TRY');
        }


        if ($default['currency']) {
            if ($default['currency'] != 'TRY') {
                $price = $this->currency->convert($price, $default['currency'], 'TRY');
            }
        }



        //KDV Ayarlar sayfası kontrol edilcek
        if ($this->config->get($code . '_setting_kdv_setting')) {

            $price = $this->tax->calculate($price, $tax_id);

        }

        $tempPrice = $price;


        if ($this->config->get('easy_setting_add_after_shipping_price')) {

            if ($default['shipping_price']) {

                if ($this->config->get($code . '_setting_shipping_template') != 'B') {
                    $price += str_replace(',', '.', $default['shipping_price']);
                }

            }

            if ($default['commission']) {

                $price = $price + ($price * $default['commission'] / 100);

            }

            if ($default['price_multiplier']) {

                $price = $this->price_multiplier($tempPrice, $default['price_multiplier']);
            }


        } else {
            if ($default['commission']) {

                $price = $price + ($price * $default['commission'] / 100);

            }

            if ($default['price_multiplier']) {

                $price = $this->price_multiplier($tempPrice, $default['price_multiplier']);
            }

            if ($default['shipping_price']) {

                if ($this->config->get($code . '_setting_shipping_template') != 'B') {
                    $price += str_replace(',', '.', $default['shipping_price']);
                }

            }

        }


        $price = number_format($price, 2);
        $price = str_replace(',', '', $price);

        return $price;

    }


    public function price_multiplier($price, $multipliers)
    {


        $returned_price = 0;

        $wholesaleTable = explode("\n", $multipliers);

        natsort($wholesaleTable);


        foreach ($wholesaleTable as $row) {
            $wholesale = explode(':', $row);

            if (count($wholesale) == 2) {
                if (isset($wholesale[1])) {

                    if ($price < $wholesale[0]) {

                        return $price + ($price * (int)$wholesale[1] / 100);

                    }
                }
            } else {

                return $price;
            }
        }


        return $returned_price;
    }




    private function checkParameter($category, $manufacturer, $product, $index, $config, $easy = '')
    {


        $param = isset($product[$index]) ? $product[$index] : false;

        if ($param) return $param;

        $param = isset($manufacturer[$index]) ? $manufacturer[$index] : false;
        if ($param) return $param;

        $param = isset($category[$index]) ? $category[$index] : false;
        if ($param) return $param;

        if ($config) return $this->config->get($config);

        return $this->config->get($easy);


    }

    public function getSettingData($code, $controller, $primary_key)
    {

        $data = array();
        if($controller=='product'){
            $controller='product_setting';
            $controller2='product';
        }else {

            $controller2=$controller;
        }

        $sql="select * from " . $controller . " where " . $controller2 . "_id='" . $primary_key . "'";

        $query = $this->udb->query($sql);

        
        if ($query->num_rows) {
            $row = $query->row;


            $variable = $row['' . $code . ''];

            if ($variable) {
                $data = unserialize($variable);
            }

        }


        return $data;

    }




    public function getMarketPlaceUrl($code, $market_id, $cs_link = false)
    {


        if ($code == 'gg') {

            return 'http://urun.gittigidiyor.com/' . $market_id;
        } else if ($code == 'n11') {

            return 'http://urun.n11.com/xxx-P' . $market_id;
        } else if ($code == 'ty') {

            return 'https://www.trendyol.com/p/p-p-p-' . $market_id;
        } else if ($code == 'hb') {

            return 'https://www.hepsiburada.com/product-p-' . $market_id;

        } else if ($code == 'eptt') {

            return 'https://www.epttavm.com/item/' . $market_id . '_p';

        } else if ($code == 'cs') {

            return $cs_link;

        } else {

            return false;
        }


    }





    public function str_search($samanlik, $igne)
    {

        if (strpos(strtolower($samanlik), strtolower($igne)) === false) {
            return false;
        } else {
            return true;
        }

    }





    public function getImage($image_url, $name,$image_folder)
    {


        if (!file_exists(DIR_IMAGE . $image_folder)) {

            mkdir(DIR_IMAGE . $image_folder, 0777, true);

        }

        $image_url = str_replace(" ", "%20", $image_url);
        $image_name = explode("/", $image_url);
        $image_name = $image_name[count($image_name) - 1];
        $path_parts = pathinfo($image_name);
        $extension = $path_parts['extension'];

        $image_name = $this->createSEOKeyword($name) . '.' . $extension;


        $image_file = DIR_IMAGE . $image_folder . $image_name;

        //if (!file_exists($image_file)) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $image_url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $image_content = curl_exec($ch);

        if ($image_content == false) {
            $image_content = file_get_contents($image_url);
        }
        file_put_contents($image_file, $image_content);

        // }

        return $image_folder . $image_name;
    }


    public function createSEOKeyword($title, $options = array('transliterate'))
    {
        // Make sure string is in UTF-8 and strip invalid UTF-8 characters
        $title = mb_convert_encoding((string)$title, 'UTF-8', mb_list_encodings());
        $defaults = array(
            'delimiter' => '-',
            'limit' => null,
            'lowercase' => true,
            'replacements' => array(),
            'transliterate' => true,
        );
        // Merge options
        $options = array_merge($defaults, $options);
        $char_map = array(
            // Latin
            'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'AE', 'Ç' => 'C',
            'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I',
            'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ő' => 'O',
            'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', 'Ý' => 'Y', 'Þ' => 'TH',
            'ß' => 'ss',
            'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c',
            'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
            'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o',
            'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th',
            'ÿ' => 'y', 'ž' => 'z',
            // Latin symbols
            '©' => '(c)',
            // Greek
            'Α' => 'A', 'Β' => 'B', 'Γ' => 'G', 'Δ' => 'D', 'Ε' => 'E', 'Ζ' => 'Z', 'Η' => 'H', 'Θ' => '8',
            'Ι' => 'I', 'Κ' => 'K', 'Λ' => 'L', 'Μ' => 'M', 'Ν' => 'N', 'Ξ' => '3', 'Ο' => 'O', 'Π' => 'P',
            'Ρ' => 'R', 'Σ' => 'S', 'Τ' => 'T', 'Υ' => 'Y', 'Φ' => 'F', 'Χ' => 'X', 'Ψ' => 'PS', 'Ω' => 'W',
            'Ά' => 'A', 'Έ' => 'E', 'Ί' => 'I', 'Ό' => 'O', 'Ύ' => 'Y', 'Ή' => 'H', 'Ώ' => 'W', 'Ϊ' => 'I',
            'Ϋ' => 'Y',
            'α' => 'a', 'β' => 'b', 'γ' => 'g', 'δ' => 'd', 'ε' => 'e', 'ζ' => 'z', 'η' => 'h', 'θ' => '8',
            'ι' => 'i', 'κ' => 'k', 'λ' => 'l', 'μ' => 'm', 'ν' => 'n', 'ξ' => '3', 'ο' => 'o', 'π' => 'p',
            'ρ' => 'r', 'σ' => 's', 'τ' => 't', 'υ' => 'y', 'φ' => 'f', 'χ' => 'x', 'ψ' => 'ps', 'ω' => 'w',
            'ά' => 'a', 'έ' => 'e', 'ί' => 'i', 'ό' => 'o', 'ύ' => 'y', 'ή' => 'h', 'ώ' => 'w', 'ς' => 's',
            'ϊ' => 'i', 'ΰ' => 'y', 'ϋ' => 'y', 'ΐ' => 'i',
            // Turkish
            'Ş' => 'S', 'İ' => 'I', 'Ç' => 'C', 'Ü' => 'U', 'Ö' => 'O', 'Ğ' => 'G',
            'ş' => 's', 'ı' => 'i', 'ç' => 'c', 'ü' => 'u', 'ö' => 'o', 'ğ' => 'g',
            // Russian
            'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'Yo', 'Ж' => 'Zh',
            'З' => 'Z', 'И' => 'I', 'Й' => 'J', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
            'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
            'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sh', 'Ъ' => '', 'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'Yu',
            'Я' => 'Ya',
            'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo', 'ж' => 'zh',
            'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o',
            'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c',
            'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sh', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e', 'ю' => 'yu',
            'я' => 'ya',
            // Ukrainian
            'Є' => 'Ye', 'І' => 'I', 'Ї' => 'Yi', 'Ґ' => 'G',
            'є' => 'ye', 'і' => 'i', 'ї' => 'yi', 'ґ' => 'g',
            // Czech
            'Č' => 'C', 'Ď' => 'D', 'Ě' => 'E', 'Ň' => 'N', 'Ř' => 'R', 'Š' => 'S', 'Ť' => 'T', 'Ů' => 'U',
            'Ž' => 'Z',
            'č' => 'c', 'ď' => 'd', 'ě' => 'e', 'ň' => 'n', 'ř' => 'r', 'š' => 's', 'ť' => 't', 'ů' => 'u',
            'ž' => 'z',
            // Polish
            'Ą' => 'A', 'Ć' => 'C', 'Ę' => 'e', 'Ł' => 'L', 'Ń' => 'N', 'Ó' => 'o', 'Ś' => 'S', 'Ź' => 'Z',
            'Ż' => 'Z',
            'ą' => 'a', 'ć' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ś' => 's', 'ź' => 'z',
            'ż' => 'z',
            // Latvian
            'Ā' => 'A', 'Č' => 'C', 'Ē' => 'E', 'Ģ' => 'G', 'Ī' => 'i', 'Ķ' => 'k', 'Ļ' => 'L', 'Ņ' => 'N',
            'Š' => 'S', 'Ū' => 'u', 'Ž' => 'Z',
            'ā' => 'a', 'č' => 'c', 'ē' => 'e', 'ģ' => 'g', 'ī' => 'i', 'ķ' => 'k', 'ļ' => 'l', 'ņ' => 'n',
            'š' => 's', 'ū' => 'u', 'ž' => 'z',
            //special
            'Ľ' => 'L', 'ľ' => 'l',
        );
        // Make custom replacements
        $title = preg_replace(array_keys($options['replacements']), $options['replacements'], $title);
        // Transliterate characters to ASCII
        if ($options['transliterate']) {
            $title = str_replace(array_keys($char_map), $char_map, $title);
        }
        // Replace non-alphanumeric characters with our delimiter
        $title = preg_replace('/[^\p{L}\p{Nd}]+/u', $options['delimiter'], $title);
        // Remove duplicate delimiters
        $title = preg_replace('/(' . preg_quote($options['delimiter'], '/') . '){2,}/', '$1', $title);
        // Truncate slug to max. characters
        $title = mb_substr($title, 0, ($options['limit'] ? $options['limit'] : mb_strlen($title, 'UTF-8')), 'UTF-8');
        // Remove delimiter from ends
        $title = trim($title, $options['delimiter']);
        return $options['lowercase'] ? mb_strtolower($title, 'UTF-8') : $title;
    }



    public function imageControl($image)
    {

        return $image;

        $bosluk = strpos($image, ' ');

        if ($bosluk) {
            if (is_file(DIR_IMAGE . $image)) {

                $degisti = $this->imageTemizle($image);


                $produduct_image = $this->udb->query("select * from product WHERE image='" . $image . "' ");

                if ($produduct_image->num_rows) {

                    $product_id = $produduct_image->row['product_id'];

                    $this->udb->query("UPDATE product SET image='" . $degisti . "' WHERE product_id=" . (int)$product_id . " ");

                    rename(DIR_IMAGE . $image, DIR_IMAGE . $degisti);

                    return $degisti;
                } else {

                    $produduct_image = $this->udb->query("select * from product_image WHERE image='" . $image . "' ");


                    if ($produduct_image->num_rows)

                        $image_id = $produduct_image->row['product_image_id'];

                    $this->udb->query("UPDATE product_image SET image='" . $degisti . "' WHERE product_id='" . (int)$image_id . "' ");

                    rename(DIR_IMAGE . $image, DIR_IMAGE . $degisti);

                    return $degisti;

                }
            }
        } else {

            return $image;

        }


    }

    public function imageTemizle($image)
    {
//Veritabanına kayıtlı olan imajı seoya uygun hale getirir
        $basename = basename($image);


        $file_path = explode($basename, $image);

        $ext = pathinfo($basename, PATHINFO_EXTENSION);


        $withoutExt = explode($ext, $basename);

        $temizle = $this->createSEOKeyword($withoutExt[0]);
        $degisti = $file_path[0] . $temizle . '.' . $ext;


        return $degisti;
    }



    public function findColor($options)
    {
        $is_exists = false;
        foreach ($options as $option) {
            if ($this->str_search($option, 'renk')) {
                $is_exists = true;
                return $is_exists;
            }
        }

        return $is_exists;
    }


    public function stringClear($str)
    {

        $bul = array('&');
        $degistir = array('-');

        return str_replace($bul, $degistir, $str);

    }

    public function currentRate($currency, $price)
    {
        $connect_web = simplexml_load_file('http://www.tcmb.gov.tr/kurlar/today.xml');
        $usd = $connect_web->Currency[0]->BanknoteSelling;
        $euro = $connect_web->Currency[3]->BanknoteSelling;
        if ($currency == 'USD') {
            $price = (float)$price * (float)$usd;
        } else if ($currency == 'EUR') {
            $price = $price * $euro;
        }
        return $price;
    }




}