<?php

class ModelEntegrasyonProductMarketplaceHb 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['images']=$this->getImages($product_data['product_id'],$product_data['main_image']);
        $defaults=$product_data['defaults'];
        $post_data['request_data']=$product_data;
        $send['result']['errors'][]='hata 1';
        $send['result']['errors'][]='hata 2';

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

        $send=$this->entegrasyon->clientConnect($post_data,'add_product','hb',$debug);


        if($send['status']){

            $status=true;
            $message.='Ürün Hepsiburada Mağazanıza Başarıyla Gönderildi, Ürününüz Hepsiburada tarafından inceleme yapıldıktan sonra satışa açılacaktır';

            $data=array('commission'=>$defaults['commission'],'sale_status'=>0,'approval_status'=>0, 'status'=>$send['result']['product_status'],'request_id'=>$send['result']['trackingId'],'product_id'=>$product_data['product_id'],'price'=>$product_data['sale_price'],0);
            $this->entegrasyon->addMarketplaceProduct($product_data['product_id'],$data,'hb');

            if($send['result']['errors']){
                $errors='';
                foreach ($send['result']['errors'] as $error) {

                    $errors.=','.$error;
                }
                $message='Ürün Gönderildi Ancak üründe şu hatalar tespit edildi; '.$errors.' Hepsiburada panelinden hataları düzetiniz.';
            }
            return array('status'=>$status,'message'=>$message,'price'=>$product_data['sale_price'].' TL');


        } else {

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

        }

    }



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

        $market_category_variants= $this->model_entegrasyon_category->getAttributes($product_info['category_id'],'hb',true,true)['result'];



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




        $error=array();




        foreach ($product_variants as $key => $product_variant) {


            foreach ($product_variant['variant_values'] as $index => $variant_value) {


                $find_variant=$this->findVariant($variant_value,$market_category_variants);


                if ($find_variant) {

                    $variant_value=$find_variant;
                    $query = $this->db->query("select * from oc_attribute where LOWER(attribute_name)='" . strtolower($variant_value['attribute_name']) . "' and marketplace_id=2 and varianter=1 ");


                    if ($query->num_rows == 1) {

                        $variant_value['market_attribute_id'] = $query->row['market_attribute_id'];


                        $query2 = $this->db->query("select * from oc_attribute_value where LOWER(name)='" . strtolower($variant_value['name']) . "' and attribute_id='" . $query->row['market_attribute_id'] . "' ");
                        if ($query2->num_rows == 1) {

                            $variant_value['attribute_value_id'] = $query2->row['attribute_value_id'];


                        } else {


                        }


                    } else {


                    }

                    $product_variants[$key]['variant_values'][$index] = $variant_value;

                }else {


                    unset($product_variants[$key]['variant_values'][$index]);
                }



            }


        }


        return $product_variants;

    }

    private function findVariant($variant,$market_variants)
    {



        $result=array();


        foreach ($market_variants as $market_variant) {

            if($variant['hb']==$market_variant['market_attribute_id']){

                $result = $variant;

            }else if($variant['market_attribute_id']==$market_variant['ty']){
                $variant['market_attribute_id']=$market_variant['market_attribute_id'];
                $variant['attribute_name']=$market_variant['attribute_name'];
                $variant['hb']=$market_variant['market_attribute_id'];
                $result = $variant;

            }

        }

        return $result;


    }

    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[] = $this->model_tool_image->resize($product_image['image']);

            //  }
            $i++;


        }

        return $images;

    }




    public function deleteProduct($product_id)
    {

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

        $this->entegrasyon->deleteMarketplaceProduct($product_id,'hb');

        return array('status' => true, 'message' => 'Ürün Entegrasyon Ayarlarından Silindi. Ürünü Trendyol mağazanızın paneline girerek tamamen silebilirsiniz.');


    }


    public function delete_product($product_list)
    {


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

      $results=  $this->hb->delete_product($product_list,$this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('hb'));



        foreach ($product_list as $product) {

            $this->db->query("DELETE FROM market_product where stock_code='".$product['model']."'");

      }



        return array('success'=>count($results['result']),'fail'=>0);


    }

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

        foreach ($products as $product) {


            $success[] = $product['marketplace_product_id'];
            $this->db->query("update market_product SET sale_status=0 where marketplace_product_id='" . $product['marketplace_product_id'] . "' ");


        }



        $result= $this->hb->close_fast($products,$this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('hb'),false);

        

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


            $success[] = $product['marketplace_product_id'];
            $this->db->query("update market_product SET sale_status=1 where marketplace_product_id='" . $product['marketplace_product_id'] . "' ");


        }
        
        $result= $this->hb->open_fast($products,$this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('hb'),false);



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

    }







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

        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);
        $this->load->model('entegrasyon/general');

        $message='';
        $status=true;
        $total=0;
        $products=array();
        $post_data=array('itemcount'=>$data['itemcount'],'on_sale'=>"true",'page'=>$data['page']);

        // $post_data['market']=$this->model_entegrasyon_general->getMarketPlace('hb');
        $this->load->model('tool/entegrasyon_api');

        $debug=false;
        $result=$this->hb->get_products($post_data,$this->model_tool_entegrasyon_api->getEntegrasyonApiInfo('hb'));

    
        if(isset($result['result']['Listings']['Listing'])){

            $total=$result['result']['TotalCount'];

            if(isset($result['result']['Listings']['Listing']['hepsiburadaSku'])){

                $item=$result['result']['Listings']['Listing'];

                $products[]=array(
                    'market_id'=>$item['hepsiburadaSku'],
                    'model'=>$item['merchantSku'],
                    'product_code'=>$item['hepsiburadaSku'],
                    'quantity'=>$item['availableStock'],
                    'stock_code'=>$item['MerchantSku'],
                    'name'=>$item['merchantSku'],
                    'barcode'=>$item['merchantSku'],
                    'list_price'=>$item['price'],
                    'sale_price'=>$item['price'],
                    'sale_status'=>$item['isSalable'],
                    'approval_status'=>$item['hepsiburadaSku']?1:0,
                    'custom_data'=>$item

                );
            }else {
                foreach ($result['result']['Listings']['Listing'] as $item) {
                    if(isset($item['hepsiburadaSku'])){



                        $products[]=array(
                            'market_id'=>$item['hepsiburadaSku'],
                            'model'=>$item['merchantSku'],
                            'barcode'=>$item['merchantSku'],
                            'stock_code'=>$item['merchantSku'],
                            'list_price'=>$item['price'],
                            'quantity'=>$item['availableStock'],
                            'name'=>$item['merchantSku'],
                            'sale_price'=>$item['price'],
                            'sale_status'=>$item['isSalable'],
                            'approval_status'=>$item['hepsiburadaSku']?1:0,
                            'custom_data'=>''

                        );
                    }
                }

            }

        }else {


            $message='Hepsiburada Ürününüz Mevcut değildir';

        }


        return array('status'=>$status,'total'=>$total,'message'=>$message,'products'=>$products);
    }




}
