<?php
class ControllerCatalogMarketProduct extends Controller
{
    public function index()
    {

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

        $this->document->setTitle($this->language->get('heading_title'));

        $query=$this->db->query("select * from product_url where pz=1");
        $products=$query->rows;
       $data['products']=$products;

        $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/market_product', $data));


    }

    public function update_product()
    {

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

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

        $barcode = '';
        $status = false;

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

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


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


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

        }

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


        $images = array();


        foreach ($product['images'] as $index => $item) {


            if ($index < 7) {

                //$image=$this->model_tool_image->upload('https://cdn.dsmcdn.com/' . $item, $product['variants'][0]['barcode'].$index);
                $images[] = array('url' => 'https://cdn.dsmcdn.com' . $item);

            }



        }

        $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;
        $product['description'] = $description;
        $product['url'] = $url;


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


        $product['images'] = $images;



            $this->pz($product);


    }


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

            return;
        }


        $prefix = $this->uconfig->get('ty_setting_model_prefix');
        $this->load->model("tool/entegrasyon_api");

        $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('pz');


        $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'] : 'yokyit';



        $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' => 1,
            '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['url'];

            }
        }

        //print_r($product);return;


        $attr = $this->model_catalog_product_finder->get_pz_category_attr($category_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üncellendi.";
          //  $this->model_catalog_product_finder->addUrl($product_data, $barcode, 'pz', 0);

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


        } 

        //echo json_encode( $result);

        //print_r(re);

    }




}

