<?php

// Admin tarafında JSON cevapları bozabilecek PHP notice/warning çıktısını engelle
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);



class ControllerCatalogProductFinder extends Controller
{

    private $reg = '';

    private $error = array();
    private $marka = false;//"Nikadu";

    private $hediye = false;
    private $proxies = array("https://www.yeryuzundebirkacadim.com");
   //  private $proxies = array("https://www.yeryuzundebirkacadim.com","https://www.easyentegre.com", "http://www.followenglish.com", "https://www.knittingtr.com");


    private $productss = array();

    private $markalarim = array("AboutThePerfect",'Arzum',"Powertec","REVOPRO","Fantom","Munico","go ithalat",'dyson',"Babyliss","DYSON",'nikadu', 'woodhub', 'teknotrust', 'teknotrust', 'NIDAGE', 'MEDITERIAN',"ozbience");
    private $yasakli_kelimeler = array("irtibat","topuk dikeni","Selülit Giderici ","Smart","smartwatch", "SMART", "Selülit",' sim kart','ortam dinleme', "ağrı", "menşe", "selülit", "cyclo", "kargo", "mikrop", "bakteri", "Cyclo", "iletişim", "trendyol", "delici", "kesici", "bakteri", "Bakteri", "kırışıklık","airpods");
    private $yasakli_urunler= array("deprem","ilkyardım","yangın","afet");

    private $markalar = array(
        'Philips','Braun','Remington','Panasonic','Wahl','Sinbo',
        'Babyliss','Rowenta','Dyson','Bosch','Electrolux','Fakir',
        'Arzum','Arçelik','Kenwood','Tefal',
        'LENOVO','Elenberg','Karcher','Miele','Mabel','Nike','Adidas','HiTech','Rose','dede','sunplus','MAGBOX','Globex','Skytech','NEXT NEXTSTAR',
        'Astra','FANTOM','Tois Baby','ALDEBA','Star','Dede Oyuncak','LETS GO BABY','Mikado','Maxword','TCL','DailyTech','Samsung','DailyLink','Vestel','Urban Sound','Jopus','Jameson','Bestway',
        'inFace','beko','Stilevs','Profilo','Siemens','Nilfisk','Intex','grundig','phillips','arnica','hutt','altus','wiami','npo','onvo','singer','rubenis','ALTUNAY','king','Uğur'
    );

    public function __construct($registry)
    {

        parent::__construct($registry);

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


    public function index()
    {

        $filePath = DIR_IMAGE . 'catalog/easyentegre';

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


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

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

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

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


        $urli = '';

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

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


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

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


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


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


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

            $max = (int)$page + 5;


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


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

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


                }

                if ($filter_special) {
                    // $url.='&wb='.$filter_name;

                    $filter_name2 = str_replace(array('https://www.trendyol.com/', '&pi=1'), '', $filter_name);
                    $filter_name2 = str_replace('&amp;', '&', $filter_name2);

                    $url = "https://apigw.trendyol.com/discovery-web-searchgw-service/v2/api/filter/" . $filter_name2 . "&pi=" . $i;

                    //$url="https://apigw.trendyol.com/discovery-web-searchgw-service/v2/api/filter/sr?prc=200-5000&q=oto&qt=oto&st=oto&tag=kirmizi_kampanya_urunu&os=1&pi=1";
                }




                $datam=file_get_contents($url);

                $content = json_decode($datam, 1);



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


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



                        // if (isset($product['ratingScore'])) {
                        $url = explode('?', $product['url'])[0];


                        $url_info = $this->db->query("select *  from product_url where  url like  '" . $this->db->escape($url) . "'")->row;

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


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


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

                                }

                            } else {


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


                                    }


                                }
                            }
                            // }
                        }

                    }
                }


            }


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

            //}

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


        }


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

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

        $data['filter_name'] = $filter_name;
        $data['hediye'] = $hediye;
        $data['filter_category'] = $filter_category;
        $data['filter_manufacturer'] = $filter_manufacturer;
        $data['filter_special'] = $filter_special;
        $data['filter_seller'] = $filter_seller;

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

        $page = $page + 5;

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


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

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

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

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


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


    }





    public function sell_product()
    {
        // ==========================
        //  Timeout ve memory ayarları
        // ==========================
        set_time_limit(300); // 5 dakika
        ini_set('max_execution_time', 300);
        ini_set('memory_limit', '512M');
        
        // ==========================
        //  Gerekli modelleri dahil et
        // ==========================
        include_once DIR_CATALOG . '/model/entegrasyon/addproduct.php';
        include_once DIR_CATALOG . '/model/catalog/product_finder.php';
        include_once DIR_CATALOG . '/model/tool/image.php';

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

        // Registry'e manuel set (mevcut yapını bozmamak için korunuyor)
        $this->registry->set('model_catalog_product_finder', new ModelCatalogProductFinder($this->registry));
        $this->registry->set('model_entegrasyon_addproduct', new ModelEntegrasyonAddproduct($this->registry));
        $this->registry->set('model_tool_image', new ModelToolImage($this->registry));

        // ==========================
        //  Kullanıcı bilgisi
        // ==========================
        $usernameEsc = $this->db->escape($this->user->getUserName());

        $user_info = $this->db->query("
        SELECT * 
        FROM `oc_user_database` ud 
        LEFT JOIN oc_user u ON (ud.database_id = u.user_database_id) 
        WHERE ud.name = '" . $usernameEsc . "'
        LIMIT 1
    ")->row;

        if (!$user_info) {
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode([
                'error' => 'Kullanıcı bilgisi bulunamadı.'
            ]));
            return;
        }

        // ==========================
        //  Hediye parametresi
        // ==========================
        $this->hediye = isset($this->request->get['hediye']) ? $this->request->get['hediye'] : false;

        // ==========================
        //  URL listesi input kontrolü
        // ==========================
        $postUrls = (isset($this->request->post['url_list']) && is_array($this->request->post['url_list']))
            ? $this->request->post['url_list']
            : [];

        if (!$postUrls) {
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode([
                'hb_result' => [],
                'ty_result' => [],
                'cs_result' => [],
                'error'     => 'URL listesi boş.'
            ]));
            return;
        }

        // url_list formatı: ['...'] veya [ ['url'=>'...'], ... ] destekli
        $url_list = [];
        foreach ($postUrls as $u) {
            if (is_array($u) && isset($u['url'])) {
                $u = $u['url'];
            }
            if (!is_string($u) || trim($u) === '') continue;
            $url_list[] = ['url' => trim($u)];
        }

        if (!$url_list) {
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode([
                'hb_result' => [],
                'ty_result' => [],
                'cs_result' => [],
                'error'     => 'Geçerli URL bulunamadı.'
            ]));
            return;
        }

        // ==========================
        //  Trendyol URL'lerinden ürün bilgilerini çek
        // ==========================
        $result_all = $this->model_entegrasyon_addproduct->get_trendyol_products($url_list, $user_info);

        if (!$result_all || !is_array($result_all)) {
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode([
                'hb_result' => [],
                'ty_result' => [],
                'cs_result' => [],
                'error'     => 'Ürünler alınamadı.'
            ]));
            return;
        }

        // ==========================
        //  URL bazlı product_url bilgilerini tek sorguda çek
        // ==========================
        $allUrls = [];
        foreach ($result_all as $it) {
            if (!empty($it['url'])) $allUrls[] = $it['url'];
        }
        $allUrls = array_values(array_unique($allUrls));

        $urlInfoMap = []; // url => row
        if ($allUrls) {
            $escaped = [];
            foreach ($allUrls as $u) {
                $escaped[] = "'" . $this->db->escape($u) . "'";
            }

            $sql = "SELECT * FROM product_url WHERE url IN (" . implode(',', $escaped) . ")";
            $q = $this->db->query($sql);

            if (!empty($q->rows)) {
                foreach ($q->rows as $row) {
                    if (!empty($row['url'])) $urlInfoMap[$row['url']] = $row;
                }
            }
        }

        // ==========================
        //  Market ürünlerini hazırla
        // ==========================
        $barkod_url = [];
        $market_products = [
            'ty' => ['items' => []],
            'hb' => [],
            'cs' => []
        ];

        foreach ($result_all as $item) {

            if (empty($item['url']) || empty($item['barcode'])) continue;

            $url     = $item['url'];
            $barcode = $item['barcode'];

            $barkod_url[] = ['barcode' => $barcode, 'url' => $url];

            $url_info = isset($urlInfoMap[$url]) ? $urlInfoMap[$url] : null;

            // --------------------------
            // Trendyol
            // --------------------------
            if (defined('TY_ENABLE') && TY_ENABLE) {
                $shouldAddTY = true;

                if ($url_info && !empty($url_info['ty'])) $shouldAddTY = false;

                if ($shouldAddTY) {
                    $product = $this->model_entegrasyon_addproduct->ty($item);

                    if (is_array($product)) {
                        $product['price'] = isset($product['salePrice']) ? $product['salePrice'] : (isset($product['price']) ? $product['price'] : 0);
                        $product['url']   = $url;

                        $market_products['ty']['items'][] = $product;
                    }
                }
            }

            // --------------------------
            // Hepsiburada
            // --------------------------
            if (defined('HB_ENABLE') && HB_ENABLE) {
                $shouldAddHB = true;

                if ($url_info && !empty($url_info['hb'])) $shouldAddHB = false;

                if ($shouldAddHB) {
                    $product = $this->model_entegrasyon_addproduct->hb($item, $user_info);

                    if (is_array($product)) {
                        $product['url'] = $url;
                        $market_products['hb'][] = $product;
                    }
                }
            }

            // --------------------------
            // Çiçeksepeti (CS)
            // --------------------------
            if (defined('CS_ENABLE') && CS_ENABLE) {
                $shouldAddCS = true;

                if ($url_info && !empty($url_info['cs'])) $shouldAddCS = false;

                if ($shouldAddCS) {
                    $product = $this->model_entegrasyon_addproduct->cs($item, $user_info);

                    if (is_array($product)) {
                        $product['url'] = $url;
                        $market_products['cs'][] = $product;
                    }
                }
            }
        }

        // ==========================
        //  Sonuç dizileri
        // ==========================
        $result_ty = [];
        $result_hb = [];
        $result_cs = [];

        // ==========================
        //  Trendyol satış
        // ==========================
        if (defined('TY_ENABLE') && TY_ENABLE && !empty($market_products['ty']['items'])) {


            $ty_api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('ty', $user_info['database_id']);
            $ty_result   = $this->ty->sell_products($market_products['ty'], $ty_api_info);

            if (!empty($ty_result['items']) && is_array($ty_result['items'])) {

                foreach ($ty_result['items'] as $product) {
                    $barcode = $product['barcode'] ?? null;
                    if (!$barcode) continue;

                    $pro = $this->find_inProducts($barcode, $result_all);
                    if (!$pro || empty($pro['url'])) continue;

                    if (empty($product['failureReasons'])) {
                        $result_ty[$pro['url']] = ['status' => true, 'message' => 'Başarılı'];
                        $this->model_catalog_product_finder->addUrl2(
                            $pro['sell_price2'] ?? 0,
                            $pro['url'],
                            $barcode,
                            'ty',
                            $user_info
                        );
                    } else {
                        $result_ty[$pro['url']] = ['status' => false, 'message' => $product['failureReasons']];
                    }
                }

            } else {
                foreach ($market_products['ty']['items'] as $mp) {
                    $barcode = $mp['barcode'] ?? null;
                    $url     = $mp['url'] ?? null;
                    if (!$barcode || !$url) continue;

                    $pro = $this->find_inProducts($barcode, $result_all);
                    $sellPrice2 = $pro['sell_price2'] ?? 0;

                    $result_ty[$url] = ['status' => true, 'message' => 'Başarılı'];
                    $this->model_catalog_product_finder->addUrl2(
                        $sellPrice2,
                        $url,
                        $barcode,
                        'ty',
                        $user_info
                    );
                }
            }
        }

        // ==========================
        //  Hepsiburada satış
        // ==========================
        if (defined('HB_ENABLE') && HB_ENABLE && !empty($market_products['hb'])) {

            $hb_api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('hb', $user_info['database_id']);
            $hb_result   = $this->hb->sell_products($market_products['hb'], $hb_api_info);

            if (!empty($hb_result['items']) && is_array($hb_result['items'])) {

                foreach ($hb_result['items'] as $product) {
                    $barcode = $product['barcode'] ?? null;
                    if (!$barcode) continue;

                    $pro = $this->find_inProducts($barcode, $result_all);
                    if (!$pro || empty($pro['url'])) continue;

                    if (empty($product['failureReasons'])) {
                        $this->model_catalog_product_finder->addUrl2(
                            0,
                            $pro['url'],
                            $barcode,
                            'hb',
                            $user_info
                        );
                        $result_hb[$pro['url']] = ['status' => true, 'message' => 'Başarılı'];
                    } else {
                        $result_hb[$pro['url']] = ['status' => false, 'message' => $product['failureReasons']];
                    }
                }
            } else {
                // HB gönderimi başarısız olup item dönmezse bile kullanıcıya hata mesajını göster
                $msg = '';
                if (is_array($hb_result) && !empty($hb_result['message'])) {
                    $msg = $hb_result['message'];
                } else {
                    $msg = 'Hepsiburada gönderimi başarısız (detay alınamadı).';
                }

                foreach ($market_products['hb'] as $mp) {
                    $url = $mp['url'] ?? null;
                    if (!$url) continue;
                    $result_hb[$url] = ['status' => false, 'message' => $msg];
                }
            }
        }



        // ==========================
        //  Çiçeksepeti satış (CS)
        // ==========================
        if (defined('CS_ENABLE') && CS_ENABLE && !empty($market_products['cs'])) {

            $cs_api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('cs', $user_info['database_id']);
            $cs_result   = $this->cs->sell_product($market_products['cs'], $cs_api_info);


            // Diğerleri ile aynı mantık: items dönerse tek tek kontrol
            if (!empty($cs_result['items']) && is_array($cs_result['items'])) {

                foreach ($cs_result['items'] as $product) {
                    $barcode = $product['barcode'] ?? null;
                    if (!$barcode) continue;

                    $pro = $this->find_inProducts($barcode, $result_all);
                    if (!$pro || empty($pro['url'])) continue;

                    if (empty($product['failureReasons'])) {
                        $this->model_catalog_product_finder->addUrl2(
                            0,
                            $pro['url'],
                            $barcode,
                            'cs',
                            $user_info
                        );
                        $result_cs[$pro['url']] = ['status' => true, 'message' => 'Başarılı'];
                    } else {
                        $result_cs[$pro['url']] = ['status' => false, 'message' => $product['failureReasons']];
                    }
                }

            } else {
                // items yoksa: gönderilenleri başarılı kabul eden fallback
                foreach ($market_products['cs'] as $mp) {
                    $barcode = $mp['barcode'] ?? null;
                    $url     = $mp['url'] ?? null;
                    if (!$barcode || !$url) continue;

                    $result_cs[$url] = ['status' => true, 'message' => 'Başarılı'];

                    $this->model_catalog_product_finder->addUrl2(
                        0,
                        $url,
                        $barcode,
                        'cs',
                        $user_info
                    );
                }
            }
        }

        // ==========================
        //  JSON output
        // ==========================
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode([
            'hb_result' => $result_hb,
            'ty_result' => $result_ty,
            'cs_result' => $result_cs
        ]));
    }


    private function find_inProducts($barcode,$products)
    {

        foreach ($products as $product) {
            if($product['full_barcode'] === $barcode){
                return $product;
            }
        }
        return  array();
    }










    public function product_list()
    {
        $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['code'])) {
            $code = $this->request->get['code'];
        } else {
            $code = 'code';
        }
        if (isset($this->request->get['target'])) {
            $target= $this->request->get['target'];
        } else {
            $target = 'hb';
        }




        $sql = "select * from product_url where $code=1 and $target=0 and user_id='".$this->user->getId()."'  ";

        //echo $sql;return;

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

        $products=$query->rows;
        print_r($products);
        return;


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


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


    }




}


