<?php

class ModelEntegrasyonProductMarketplacePz extends Model{

    public function sendProduct($product_data,$selected_attributes=array(),$debug=false)
    {

        $status=false;
        $message='';


        if(!$selected_attributes) {
            if (isset($product_setting['selected_attributes'])) {
                $selected_attributes = $product_data['attributes'];
            } else {
                $selected_attributes = array();
            }
        }

        $product_data['attributes']=$this->getAttributes($selected_attributes);

        //$product_data['images']=$this->getImages($product_data['product_id'],$product_data['main_image']);

        $defaults=$product_data['defaults'];

        $post_data['request_data']=$product_data;
        $post_data['market']=$this->model_entegrasyon_general->getMarketPlace('ty');
        $send=$this->entegrasyon->clientConnect($post_data,'addProduct','ty',$debug);



        if($send['status']) {

            $status = true;
            $message .= $send['message'];

            if (isset($send['result']['result']['batchRequestId'])){
                $data = array('commission' => $defaults['commission'], 'message' => $message, 'sale_status' => 0, 'approval_status' => 0, 'product_id' => $product_data['product_id'], 'request_id' => $send['result']['result']['batchRequestId'], 'price' => $product_data['sale_price'], 0);

                $this->entegrasyon->addMarketplaceProduct($product_data['product_id'], $data, 'ty');
                //   $this->entegrasyon->addMarketProductAfterAddProduct($product_data['product_id'], array('barcode'), 'ty');


                return array('status'=>$status,'message'=>$message,'price'=>$product_data['sale_price'].' TL');

            }else {
                return array('status'=>false,'message'=>$send['message']);
            }


        } else {

            return array('status'=>$status,'message'=>$send['message']);

        }


    }

    public function close_for_sale($products)
    {
        $this->load->model('tool/entegrasyon_api');
        $success=array();
        $fail=array();

        $barcodes=array();
        foreach ($products as $product) {

            $barcodes[]=$product['barcode'];

        }

        $result = $this->ty->close_for_sale($barcodes,$this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('ty'));


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



            if($result['status']=='SUCCESS'){
                $success[]=$result['requestItem']['barcode'];
                $this->db->query("update market_product SET sale_status=0 where barcode='".$result['requestItem']['barcode']."' ");
            }else {
                $fail[]=$result['requestItem']['barcode'];
            }

        }

        return array('success'=>$success,'fail'=>$fail);

    }


    public function open_for_sale($products)
    {
        $this->load->model('tool/entegrasyon_api');
        $success=array();
        $fail=array();

        foreach ($products as $product) {


            $result= $this->ty->open_for_sale($product['barcode'],$this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('ty'));
            if($result['status']){
                $success[]=$product['barcode'];
                $this->db->query("update market_product SET sale_status=1 where barcode='".$product['barcode']."' ");
            }else {
                $fail[]=$product['barcode'];
            }

        }

        return array('success'=>$success,'fail'=>$fail);

    }


    public function getMarketVariants($product_info)
    {
        $this->load->model('entegrasyon/product/variant');

        return $this->model_entegrasyon_product_variant->getProductVariants($product_info['product_id']);
    }



    public function getProducts($data=array(),$onlyApproved=true,$debug=false)
    {

        error_reporting(E_ALL);
        ini_set('display_errors', 0);
        $this->load->model('tool/entegrasyon_api');

        $this->load->model('entegrasyon/general');
        $message='';
        $status=false;
        $total=0;
        $products=array();


        $onlyApproved=$onlyApproved?'true':'false';


        $post_data['request_data']=array('itemcount'=>$data['itemcount'],'page'=>$data['page'],'approved'=>$onlyApproved);
        $result =$this->pz->get_products($post_data['request_data'],$this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('pz'));


   
       // print_r($result);



        if($debug){
            print_r($result);
        }

        $pages=0;
        if($result['success']){
            $total=0;
            $pages=0;
            if(count($result['data'])>0){
                foreach ($result['data'] as $item) {

                    //   if(!in_array($item['productMainId'],$products_uniq)) {
                    
                    $market_id=isset($item['code']) ? $item['code'] : false;
                    $product = array(
                        'market_id' => $market_id,
                        'product_code'=>$market_id,
                        'model' => $item['code'],
                        'stock_code'=>isset($item['code']) ? $item['code']:'' ,
                        'name' => $item['name'],
                        'list_price' => isset($item['listPrice'])?$item['listPrice']:0,
                        'barcode' => $item['code'],
                        'sale_price' => isset($item['salePrice'])?$item['salePrice']:0,
                        'sale_status' => $item['status']?1:0,
                        'quantity' => $item['stockCount'],
                        'approval_status' => $item['waitingApproveExp']?false:true,

                        'custom_data'=>$item

                    );





                    $products[] = $product;

                    //  $products_uniq[] = $item['productMainId'];

                    //  }
                }
            }

        }else {

            $message=$result['message'];
        }





        return array('status'=>$result['success'],'total'=>$total,'pages'=>$pages,'message'=>$message,'products'=>$products);
    }


    public function getProduct($product_id,$debug=false)
    {


        // $product_id='9786055s06sd2200';

        $this->load->model('entegrasyon/general');


        $post_data['request_data'] = array('itemcount' => 1, 'page' => 1, 'barcode' => $product_id, 'approved' => true);

        $post_data['market'] = $this->model_entegrasyon_general->getMarketPlace('ty');

        $result = $this->entegrasyon->clientConnect($post_data, 'get_product', 'ty', $debug);



        if ($result['result']['content'][0]){
            $match_status=true;
            $message='Ürün Bulundu';
        }else{
            $match_status=false;
            $message='Ürün Bulunamadı';
            $product = array(
                'match_status'=>$match_status,
                'message'=>$message
            );
            return $product;
        }



        //$product=array();

        if(!$result['status']) {

            return $result;
        }



        if(!$result['status']) return $result;

        $item=$result['result']['content'][0];


        $market_id=isset($item['productContentId']) ? $item['productContentId'] : false;
        $product = array(
            'market_id' => $market_id,
            'match_status'=>$match_status,
            'message'=>$message,
            'model' => $item['productMainId'],
            'stock_code'=>$item['stockCode'],
            'name' => $item['title'],
            'list_price' => isset($item['listPrice'])?$item['listPrice']:0,
            'barcode' => $item['barcode'],
            'sale_price' => isset($item['salePrice'])?$item['salePrice']:0,
            'sale_status' => $market_id && $item['quantity'] ? 1:0,
            'quantity' => $item['quantity'],
            'approval_status' => $item['approved']

        );



        return $product;

    }

    public function getImages($product_info)
    {

        $images=array();

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


        $images[] = $this->model_tool_image->resize($product_info['image']);


        $product_images=$this->db->query("select * from product_image where product_id='".$product_info['product_id']."'")->rows;

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


            $images[] = array('url'=> $this->model_tool_image->resize($product_image['image']));

            //  }
            $i++;


        }

        return $images;

    }

    public function getMarketPlaceProduct($product_id,$debug=false)
    {

        $totalStock=0;
        $sale_status=0;
        // $product_id='8681123687181';

        $this->load->model('entegrasyon/general');
        $this->load->model('entegrasyon/market_product');
        $post_data =array('itemcount'=>1,'page'=>1,'barcode'=>$product_id,'approved'=>true);

        // $market = $this->model_entegrasyon_general->getMarketPlace('ty');
        $this->load->model('tool/entegrasyon_api');

        $result=$this->ty->get_product($post_data,$this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('ty'));

        $product=$result['result']['content'][0];



        if($debug){
            print_r($result);
            return ;
        }



        $language_id = $this->config->get('config_language_id');


        if(!$result['status']) {

            return $result;
        }

        if(!$result['status']) return $result;




        $images=array();

        foreach ($product['images'] as $key => $image) {
            $ext = pathinfo($image['url'], PATHINFO_EXTENSION);
            if(!$ext){
                $img_url=$this->findImg($image['url']);

            }else {
                $img_url=$image['url'];
            }
            $images[] = str_replace(' ', '%20', $img_url);

        }



        $query= $this->db->query("select model,product_id from product where model='".$product['productMainId']."' ");

        $has_variant_query  = $this->db->query("select market_product_id,quantity from market_product where model='".$product['productMainId']."' and code='ty'");



        $variant_data=array();

        if( $has_variant_query->num_rows > 1){

            $url = isset($product['productContentId']) ? $this->model_entegrasyon_market_product->getMarketPlaceUrl('ty', $product['productContentId']) : '';
            //productCode
            $marketplace_product_data = array('sale_status' => $product['approved'] && $product['quantity'] ? 1:0 , 'approval_status' => $product['approved'], 'commission' => 0, 'product_id' => isset($product['productCode']) ? $product['productCode'] : '', 'sale_price' => $product['salePrice'], 'list_price' => $product['listPrice'], 'url' => $url);

            $variant_data = array(
                'image' => $images[0],
                'code' =>'ty',
                'barcode' => $product['barcode'],
                'stock_code' => $product['stockCode'],
                'quantity' => $product['quantity'],
                'sale_price'=>$product['salePrice'],
                'marketplace_data'=>$marketplace_product_data
            );

            if($query->num_rows){
                $variant_data['product_id']=$query->row['product_id'];
            }


            $this->load->model("entegrasyon/product/variant");
            $variant_options=$this->model_entegrasyon_product_variant->getVariantOptionsByCategoryId($product['pimCategoryId']);
            $options=array();

            foreach ($variant_options as  $option) {
                foreach ($product['attributes'] as $attribute) {
                    $res = array_search($option['attribute_name'], $attribute, true);
                    if($res){

                        if($attribute['attributeId']==47){

                            $options[$attribute['attributeId']]=$this->model_entegrasyon_product_variant->addOrGetColorId($attribute['attributeValue']);


                        }else {
                            $options[$attribute['attributeId']]=$attribute['attributeValueId'];

                        }

                    }

                }
            }

            $variant_data['option']=$options;


            //  return array('status'=>true,'product_type'=>2,'variant_data'=>$variant_data);

        }

        $product_data =array();
        $marketplace_product_data =array();
        if($query->num_rows == 0) {

            $product_description = array($language_id => array(
                'name' => $product['title'],
                'description' => $product['description'],
            ));

            $this->load->model('catalog/category');
            $category_info = $this->model_catalog_category->getCategory($product['pimCategoryId']);

            // unset($images[0]);
            $product_variants=array();
            if($variant_data){
                $product_variants[]=$variant_data;
            }

            $totalData=$this->db->query("SELECT sum(quantity) as quantity, sum(sale_status) as sale_status FROM `market_product` where model='".$product['productMainId']."'")->row;
            $product_data = array(
                'model' => $product['productMainId'],
                'barcode' => $product['barcode'],
                'stock_code' => $product['stockCode'],
                'quantity' => $totalData['quantity'],
                'manufacturer_id' => $product['brandId'],
                'manufacturer_name' => $product['brand'],
                'sale_price' => $product['salePrice'],
                'list_price' => $product['listPrice'],
                'shipping' => 1,
                'varianter' =>$has_variant_query->num_rows > 1 ? 1:0,
                'tax' => $product['vatRate'],
                'desi' => isset($product['dimensionalWeight'])?$product['dimensionalWeight']:1,
                'sort_order' => 1,
                'status' => 1,
                'product_description' => $product_description,
                'product_image' => $images,
                'category_id' => $category_info['category_id'],
                'category_name' => $category_info['name'],


            );

            if($product_data['varianter']){
                $product_data['product_variant']=$product_variants;

            }

            $url = isset($product['productContentId']) ? $this->model_entegrasyon_market_product->getMarketPlaceUrl('ty', $product['productContentId']) : '';
            //productCode

            $marketplace_product_data = array('sale_status' =>$totalData['sale_status'] && $totalData['quantity'] ? 1:0 , 'approval_status' => $product['approved'], 'commission' => 0, 'product_id' => isset($product['productCode']) ? $product['productCode'] : '', 'sale_price' => $product['salePrice'], 'list_price' => $product['listPrice'], 'url' => $url);

            $marketplace_product_data['ty_category_id'] = $product['pimCategoryId'] . '|' . $product['categoryName'];
            $marketplace_product_data['product_id'] = $product_id;

        }

        return array('status' => true, 'product_data' => $product_data, 'variant_data' => $variant_data, 'marketplace_product_data' => $marketplace_product_data);



    }

    private function findImg($str)
    {

        preg_match_all('/(http|https):\/\/[^ ]+(\.gif|\.jpg|\.jpeg|\.png)/',$str, $out);

        return $out[0][0];

    }


    public function checkUrl($url)
    {
        //$url='https://cdn.dsmcdn.com//ty5/product/media/images/20200622/12/3284861/61173429/1/1_org.jpg';

        $status=true;
        $handle = curl_init($url);
        curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST,  0);
        /* Get the HTML or whatever is linked in $url. */
        $response = curl_exec($handle);
        /* Check for 404 (file not found). */
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

        if($httpCode != 200 ) {
            /* Handle 404 here. */
            $status=false;

        }

        curl_close($handle);



        return $status;
    }


    public function imageControl($image)
    {


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

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

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



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

                if ($produduct_image->num_rows) {

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

                    $this->db->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->db->query("select * from product_image WHERE image='" . $image . "' ");


                    if ($produduct_image->num_rows)

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

                    $this->db->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;

        }


    }

    private function searchName($name,$attributes)
    {

        foreach ($attributes as $attribute){

            if($this->entegrasyon->replaceSpace($attribute['name'])==$this->entegrasyon->replaceSpace($name)){

                return $attribute['values'];

            }


        }

    }


    private function searchValue($value,$valuesArray)
    {


        foreach ( $valuesArray as $item) {
            $val1=$this->entegrasyon->replaceSpace($item['name']);
            $findMe=$this->entegrasyon->replaceSpace($value);


            $pos=stripos($val1,$findMe);

            //  echo $val1.'-'.$findMe.'<br>';


            if($pos!==false){

                return $item['id'];

            }

        }

    }




}