<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests;
use Illuminate\Support\Str;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Artisan;
use Carbon\Carbon;
use PHPShopify;
use Mail;
use Illuminate\Support\Facades\Storage; 
use App\User;
use App\ShopifyStore;
use App\EbayAccount;
use App\StoreCronJob;
use App\Order ;
use App\CronJob;
use App\Helpers\AppHelper;
use App\Listing;
use App\ListingVariant;
use Sunra\PhpSimple\HtmlDomParser;
use App\Jobs\SyncAccountInventory;
use App\Jobs\CreateProductsFromListings;
use App\Jobs\SyncAccountPrice;
use App\PendingProductPublish;
use App\Jobs\Newpendinginvenoryupdate;
use App\Jobs\SyncShopifyInventory;
use App\Jobs\Handleipnjob;
use App\Jobs\PublishProduct;
use Exception;
use App\Helpers\EbayHelper;
use \DTS\eBaySDK\Constants;
use \DTS\eBaySDK\Trading\Services;
use \DTS\eBaySDK\Trading\Types;
use \DTS\eBaySDK\Trading\Enums;
use Illuminate\Support\Facades\Log;
use DOMDocument;
use \DTS\eBaySDK\Parser;



class ListingController extends Controller{

	public $shopifyStore = null;
	
	public function __construct(){ 
	}
	
	public function index(Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
		//	$per_page = 20;
		  $per_page_limit = $request->input('limit');
			 //if ($per_page_limit !== null && $per_page_limit == 50 || $per_page_limit == 100 ||  $per_page_limit == 200) {
		//             // Set $per_page to $per_page_limit
		//             $per_page = $per_page_limit;
		//         } else {
		//             $per_page = 20;
		//         }
		if ($per_page_limit !== null) {
                // Set $per_page to $per_page_limit
                $per_page = $per_page_limit;
            } else {
                $per_page = 20;
            }
			$sort_by = ($request->input("sort_by")) ? $request->input("sort_by") : "created_at";
			$sort_order = ($request->input("sort_order")) ? $request->input("sort_order") : "desc";

			$link_status = trim($request->input('link_status'));
			$title = trim($request->input("title"));
			$listing_id = trim($request->input("listing_id"));
			$status = trim($request->input("status"));
			$ebay_item_id = trim($request->input("ebay_item_id"));
			$sku = trim($request->input("sku"));

			$conditions = array();
			if($title) $conditions[] = array("title","like","%".$title."%");
			if($listing_id) $conditions[] = array("ebay_item_id","=",$listing_id);
			if($status) $conditions[] = array("status","=",$status);

			$vconditions = array();
			if($ebay_item_id) $vconditions[] = array("ebay_item_id","=",$ebay_item_id);
			if($sku) $vconditions[] = array("sku","=",$sku);

			$listings = array();
			if($link_status == "linked"){
				$conditions[] = array("product_id",">",0);
				if($vconditions){
					$listings = $shopifyStore->listings()->with('variants')->with('product')->whereHas('variants',function($query) use($vconditions){
						$query->where($vconditions);
					})->where($conditions)->orderBy($sort_by,$sort_order)->paginate($per_page);
					if($listings->count() == 0 && $ebay_item_id){
						$conditions[] = array("ebay_item_id","=",$ebay_item_id);
						$listings = $shopifyStore->listings()->with('variants')->with('product')->where($conditions)->orderBy($sort_by,$sort_order)->paginate($per_page);
					}
				}
				else{
					$listings = $shopifyStore->listings()->with('variants')->with('product')->where($conditions)->orderBy($sort_by,$sort_order)->paginate($per_page);
				
				}
			}
			else{
				if($vconditions){
					if($conditions){
						$listings = $shopifyStore->listings()->with('variants')->with('product')->whereHas('variants',function($query) use($vconditions){
							$query->where($vconditions);
						})->where(function($query){
							$query->where("product_id",0)->orWhereNull("product_id");
						})->where($conditions)->orderBy($sort_by,$sort_order)->paginate($per_page);
					}
					else{
						$listings = $shopifyStore->listings()->with('variants')->with('product')->whereHas('variants',function($query) use($vconditions){
							$query->where($vconditions);
						})->where(function($query){
							$query->where("product_id",0)->orWhereNull("product_id");
						})->orderBy($sort_by,$sort_order)->paginate($per_page);
					}

					if($listings->count() == 0 && $ebay_item_id){
						$conditions[] = array("ebay_item_id","=",$ebay_item_id);
						$listings = $shopifyStore->listings()->with('variants')->with('product')->where(function($query){
							$query->where("product_id",0)->orWhereNull("product_id");
						})->where($conditions)->orderBy($sort_by,$sort_order)->paginate($per_page);
					}
				}
				else{
					if($conditions){
						$listings = $shopifyStore->listings()->with('variants')->with('product')->where(function($query){
							$query->where("product_id",0)->orWhereNull("product_id");
						})->where($conditions)->orderBy($sort_by,$sort_order)->paginate($per_page);
					}
					else{
						$listings = $shopifyStore->listings()->with('variants')->with('product')->where(function($query){
							$query->where("product_id",0)->orWhereNull("product_id");
						})->orderBy($sort_by,$sort_order)->paginate($per_page);
					}
				}
			}
			if($listings->count() > 0){
				foreach($listings as $lkey => $listing){
					$listings[$lkey]->listing_data = json_decode($listing->listing_data);
				$listings[$lkey]->title = $listings[$lkey]->listing_data->Title ?? "";

					foreach($listing->variants as $vkey => $variant){
						$listings[$lkey]->variants[$vkey]->listing_variant_data = $variant->listing_variant_data;
						$listings[$lkey]->variants[$vkey]->ebay_item_data = $variant->ebay_item_data;
					}
				}
			}
			return response()->json($listings,200);
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}
	
	
	public function hiteshmali(){
	    echo 'hiteshmali';
	}
	

	public function show($id,Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			$listing = $shopifyStore->listings()->find($id);
			if($listing){
				return response()->json($listing,200);
			}
			else{
				return response()->json(['status' => 'error','msg' => "not found"],404);
			}
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}

	public function fetchebproducts(){
	  
	  	$shopifyStores = ShopifyStore::where('status', "active")->where('user_id',150)->get();
	  	$shopify_store_id = $shopifyStores[0]->id;
	  		$user_id = $shopifyStores[0]->user_id;
		$store_database_name = config('config.store_db_prefix').$shopify_store_id;
		AppHelper::setConnection($store_database_name,$shopifyStores[0]);
     // $listings = $shopifyStores[0]->listings()->with('listingVariants')->get();
     	$listings = $shopifyStores[0]->listings()->with('variants')->get();
		
    	$associativeArray = array();

       foreach ($listings as $listing) {
        $associativeArray[] = array(
          "ebayItemId" => $listing->ebay_item_id,
           "productId" => $listing->product_id
         );
       }

    	$ebayAccount = $shopifyStores[0]->ebayAccounts()->where('user_id',150)->first();

       	$ebay_environment = config('ebay.environment');

		
			$ebayCredentials = array(
				'credentials' => [
					'devId' => config('ebay.'.$ebay_environment.'devid'),
					'appId' => config('ebay.'.$ebay_environment.'appid'),
					'certId' => config('ebay.'.$ebay_environment.'certid'),
				],
				'authToken' => '',
				'oauthUserToken' => '',
				'ruName' => config('ebay.'.$ebay_environment.'RuName')
			);
			$ebay_token = $ebayAccount["access_token"];
			$site_id = (isset($ebayAccount["siteid"])) ? $ebayAccount["siteid"] : 0;
            
		
				$ebayService = new Services\TradingService([
					'credentials' => $ebayCredentials['credentials'],
					'sandbox' => ($ebay_environment == "sandbox" ) ? true : false,
					'siteId' => $site_id
				]);
			
            print("hello");
          	$product_Id_Array = array();
        foreach($associativeArray as $associativeArrays){
              
                    //	print_r($associativeArrays["ebayItemId"]);
                    	$ebay_item_id = $associativeArrays["ebayItemId"];
            	try{  
						$ebayItemRequest = new Types\GetItemRequestType();
						$ebayItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
						$ebayItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
						$ebayItemRequest->ItemID = $ebay_item_id;
						$ebayItemRequest->IncludeItemSpecifics = true;
						sleep(2);

						$ebayItemResponse = $ebayService->getItem($ebayItemRequest);
						$ebayItemData = $ebayItemResponse->toArray();
						$ebayItemData = (isset($ebayItemData["Item"])) ? $ebayItemData["Item"] : [];
						
					//	print_r($ebayItemData);
					
						if($ebayItemData!==[]){
						    print_r("true");
						}else{
						    print_r("false,product_id = " .$associativeArrays["productId"]." ,  ");
						     $product_Id_Array[] = $associativeArrays["productId"];
						     
						  //*****Now we are deleting the values from listing and listing variants table******
						  
						     $shopifyStores[0]->listings()->with('variants')->where('ebay_item_id', $associativeArrays['ebayItemId'])->delete();
						  
						  
						   //*****Deleting value of listing_id from products table and  listing_variant_id from products_variants table******
						   
						   
						    $shopifyStores[0]->products()->where('id', $associativeArrays['productId'])->update(['listing_id' => null, 'status' => 'unpublished']);

						    $shopifyStores[0]->variants()->where('product_id', $associativeArrays['productId'])->update(['listing_variant_id' => null]);

						    // $products = $shopifyStores[0]->products()->where("id",$associativeArrays["productId"])->first();
						     print_r("here is the product_id ".$associativeArrays["productId"]." , ");
						      print_r("here is the account_id ".$ebayAccount["id"]." , "); 
						      print_r("here is the shopify_store_id ".$shopify_store_id." , ");
						       print_r("here is the user_id ".$user_id." , ");
						       
						$pProData = array();
                        $pProData["profile_id"] = 1;
                        $pProData["product_id"] =  $associativeArrays["productId"];
                        $pProData["account_id"] = $ebayAccount["id"];
                        $pProData["store_id"] = $shopify_store_id;
                        $pProData["user_id"] = $user_id;
                        $shopifyStores[0]->pendingProductPublish()->create($pProData);
                      
                      	die();
						}
					}
					catch(\Exception $e){
						report($e);
					}
				
              }
            
                   print_r("here is the product_id  ".$product_Id_Array."  , ");
              
         
          
 
	}

	public function linkProduct(Request $request){
		Log::channel('linkProduct')->info(" enter link product function ");
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			$validationRules = [
				'listing_id' => 'required|numeric',
				'product_id' => 'required|numeric',
				'variants_mapping' => 'required'
			];
			$validator = Validator::make($request->all(),$validationRules);
			if($validator->fails()){
				return response()->json(['status' => 'error', 'msg' => '', 'errors' => $validator->errors()],406);
			}

			$listing_id = $request->input("listing_id");
			$product_id = $request->input("product_id");
			$variants_mapping = $request->input("variants_mapping");

			$listing = $shopifyStore->listings()->with('variants')->with('account')->find($listing_id);
			$product = $shopifyStore->products()->with('variants')->find($product_id);

			if(!$listing || !$product){
				return response()->json(['status' => 'error','msg' => "invalid request"],406);
			}
			else if($listing->product_id || $product->listing_id){
				return response()->json(['status' => 'error','msg' => "listing already connected"],406);
			}
			else{
				$listing->product_id = $product->id;
				$listing->save();

				$product->listing_id = $listing->id;
				// $product->status = "published";
					$product->status = "Linked";
				$product->save();

				$ebayAccount = $listing->account;

				foreach($variants_mapping as $lvar_id => $var_id){
					$lvar_id = (int) $lvar_id;
					$var_id = (int) $var_id;
					if(!$lvar_id || !$var_id) return response()->json(['status' => 'error','msg' => "invalid request"],403);
					foreach($listing->variants as $lvariant){
						// echo "<pre>";
						// print_r($lvariant);
						// echo "</pre>";
						if($lvariant->id == $lvar_id){
							foreach($product->variants as $variant){
								Log::channel('linkProduct')->info(" enter shopify foreachloop " . '');
								// echo "enter shopify foreachloop";
								// echo "<pre>";
								// print_r($variant);
								// echo "</pre>";
								if($variant->id == $var_id){
									$variant->listing_variant_id = $lvar_id;
									$variant->save();
									$lvariant->variant_id = $var_id;
									if($variant->sku != $lvariant->sku) $lvariant->custom_sku = $variant->sku;
									if($lvariant->sku != ''){
										$lvariant->sku = 'ebaylistingmapped'.$lvariant->sku ;
									}else{
										$lvariant->sku = 'ebaylistingmapped';
									}
									$lvariant->custom_sku = $variant->shopify_variant_id; // himanshu changes 26-04-2024
                                  	Log::channel('linkProduct')->info(" hitesh itemSpecifics " . ' yes sir');
									$lvariant->save();
									Log::channel('linkProduct')->info(" linkProduct data save  " . '');
									if($ebayAccount->inventory_sync == 1){
										Log::channel('linkProduct')->info(" enter if condition in inventory_sync  " . '');
										$jobData = array();
										$jobData["quantity"] = $variant->quantity;
										$jobData["sku"] = $lvariant->sku;
										$jobData["ebay_item_id"] = $lvariant->ebay_item_id;
										$jobData["variant_id"] = $variant->id;
										$jobData["type"] = "set";
										$jobData["source"] = "link_product";
										$jobData["account_id"] = $listing->account_id;
										$jobData["store_id"] = $shopifyStore->id;
										$jobData["user_id"] = $shopifyStore->user_id;
									
								 		//SyncAccountInventory::dispatchNow($jobData);
										//SyncAccountInventory::dispatch($jobData)->delay(now()->addMinutes(1));
									}

									if($ebayAccount->price_sync == 1){
										Log::channel('linkProduct')->info(" enter if condition in price_sync  " . '');
										$jobData = array();
										$jobData["price"] = $variant->price;
										$jobData["compare_at_price"] = $variant->compare_at_price;
										$jobData["sku"] = $lvariant->sku;
										$jobData["ebay_item_id"] = $lvariant->ebay_item_id;
										$jobData["variant_id"] = $variant->id;
										$jobData["type"] = "set";
										$jobData["source"] = "link_product";
										$jobData["account_id"] = $listing->account_id;
										$jobData["store_id"] = $shopifyStore->id;
										$jobData["user_id"] = $shopifyStore->user_id;
									
								 		//SyncAccountPrice::dispatchNow($jobData);
										//SyncAccountPrice::dispatch($jobData)->delay(now()->addMinutes(1));
									}
									break;
								}
							}
							break;
						}
					}
				}
			}
			  Log::channel('linkProduct')->info(" hitesh itemSpecifics " . ' listing product linked successfully');
			return response()->json(['status' => 'success','msg' => 'listing product linked successfully'],200);
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}

	public function unLinkProducts(Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			$validationRules = [
				'listing_ids' => 'required'
			];
			$validator = Validator::make($request->all(),$validationRules);
			if($validator->fails()){
				return response()->json(['status' => 'error', 'msg' => '', 'errors' => $validator->errors()],406);
			}

			$listing_ids = $request->input("listing_ids");
			foreach($listing_ids as $listing_id){
				$listing = $shopifyStore->listings()->with('variants')->find($listing_id);
				if($listing && $listing->product_id){
					$product_id = $listing->product_id;
					$product = $shopifyStore->products()->with('variants')->find($product_id);
					if($product && $product->listing_id){
						$product->listing_id = NULL;
						$product->status = "unpublished";
						$product->save();
						foreach($product->variants as $variant){
							$variant->listing_variant_id = NULL;
							$variant->save();
						}				
					}
					$listing->product_id = NULL;
					$listing->save();
					foreach($listing->variants as $lvariant){
					   //  this is string error to mover in sku 
					    if (strpos($lvariant->sku , 'ebaylistingmapped') !== false) {
                          $lvariant->sku =  str_replace('ebaylistingmapped', '', $lvariant->sku);
                          } else if (strpos($lvariant->sku , 'ebaylistingcreated') !== false) {
                          $lvariant->sku =  str_replace('ebaylistingcreated', '', $lvariant->sku);
                          }
						$lvariant->variant_id = NULL;
						if($lvariant->custom_sku) $lvariant->custom_sku = NULL;
						$lvariant->save();
					}
				}
			}
			return response()->json(['status' => 'success','msg' => 'listing product unlinked successfully'],200);
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}

	public function createProduct($listing,$shopifyStore,$shopifyClient){
		if($shopifyStore){
			$errors = array();
	
			$status = "error";
			//$listing = $shopifyStore->listings()->with('variants')->find($listing_id);
			if($listing && !$listing->product_id){
				try{
					$listingData = json_decode($listing->listing_data,true);
					$additionalData = json_decode($listing->additional_data,true);
	
					$itemSpecifics = isset($listingData["ItemSpecifics"]) ? $listingData["ItemSpecifics"] : [];
	
					$productData = array (
						"title" => $listing->title,
						"body_html" => isset($listingData["Description"]) ? $listingData["Description"] : "",
						"metafields_global_title_tag" => $listing->title,
						"metafields_global_description_tag" => $listing->title,
						"published" => "TRUE"
					);
					$options = array();
					$variants = array();
	
					if($itemSpecifics){
						foreach($itemSpecifics["NameValueList"] as $itemSpecific){
							if($itemSpecific["Name"] == "Brand"){
								// $productData["vendor"] = trim('"',$itemSpecific["Value"][0]);
								$productData["vendor"] = $itemSpecific["Value"][0];
							}
							else if($itemSpecific["Name"] == "Type"){
								// $productData["product_type"] = trim('"',$itemSpecific["Value"][0]);
								$productData["product_type"] = $itemSpecific["Value"][0];
							}
						}
					}
	
	
					$variants = array();
					$skuImages = array();
					$skuInventory = array();
					$images = array();
					if($listing->image) $images[] = $listing->image;
	
	
					foreach($listing->variants as $lkey => $variant){
						$sku = $variant->sku;
						$custom_sku = $variant->shopify_variant_id; // himanshu changes 26-04-2024
						print_r('hiteshmalie'.$sku);
						$pvariant = $shopifyStore->variants()->where("sku",$sku)->first();
						if($pvariant){
							$custom_sku = $variant->sku."_".$variant->id;
							$variant->custom_sku = $custom_sku;
							$variant->save();
							$sku = $custom_sku;
							$listing->variants[$lkey]->custom_sku = $custom_sku;
						}
	
						if($variant->image){
							$skuImages[$sku] = $variant->image;
							if(!in_array($variant->image,$images)) $images[] = $variant->image;
						}
	
						$lVarData = json_decode($variant->listing_variant_data,true);
						$ebayItemData = json_decode($variant->ebay_item_data,true);
						$addData = json_decode($variant->additional_data,true);
	
						$opvalues = array();
	
						if(isset($lVarData["VariationSpecifics"]) && $lVarData["VariationSpecifics"]){
							foreach($lVarData["VariationSpecifics"][0]["NameValueList"] as $ebOption){
								$opname = $ebOption["Name"];
								$opval = $ebOption["Value"][0];
	
								if(!in_array($opval,$opvalues)) $opvalues[] = $opval;
								$opfound = false;
								if($options){
									foreach($options as $okey => $option){
										if($option["name"] == $opname){
											if(!in_array($opval,$option["values"])) $options[$okey]["values"][] = $opval;
											$opfound = true;
										}
									}
								}
								if(!$opfound){
									$options[] = array(
										"name" => $opname,
										"values" => array($opval)
									);
								}
							}
						}
	
						$price = 0;
						$quantity = 0;
						$compare_at_price = 0;
						$product_id_val = "";
	
						if(isset($lVarData["StartPrice"]) && $lVarData["StartPrice"]) $price = (float) $lVarData["StartPrice"];
						if(isset($lVarData["Quantity"]) && $lVarData["Quantity"]) $quantity = (int) $lVarData["Quantity"];
						if(isset($lVarData["SellingStatus"]) && $lVarData["SellingStatus"] && isset($lVarData["SellingStatus"]["QuantitySold"])) $quantity = $quantity - (int) $lVarData["SellingStatus"]["QuantitySold"];
	
						$skuInventory[$sku] = $quantity;
	
						$weight = 0;
						$weight_unit = null;
	
	
						if(isset($ebayItemData["ShippingPackageDetails"]) && $ebayItemData["ShippingPackageDetails"] && isset($ebayItemData["ShippingPackageDetails"]["WeightMajor"])){
							$weight = (float) $ebayItemData["ShippingPackageDetails"]["WeightMajor"]["value"];
							$weight_unit = strtolower($ebayItemData["ShippingPackageDetails"]["WeightMajor"]["unit"]);
							if($weight_unit == "lbs") $weight_unit = "lb";
						}
	
						$variantArr = array(
							"price" => $price,
							"sku" => $sku,
							"inventory_policy" => "deny",
							"fulfillment_service" => "manual",
							"inventory_management" => "shopify",
							"taxable" => true,
							"requires_shipping" => "true"
						);
						if($compare_at_price > $price) $variantArr["compare_at_price"] = $compare_at_price;
						if($product_id_val) $variantArr["barcode"] = $product_id_val;
						if($weight_unit && $weight){
							$variantArr["weight"] = $weight;
							$variantArr["weight_unit"] = $weight_unit;
						}
						else if(!$weight_unit && $weight) $variantArr["grams"] = $weight;
	
						if(isset($opvalues[0])) $variantArr["option1"] = $opvalues[0];
						if(isset($opvalues[1])) $variantArr["option2"] = $opvalues[1];
						if(isset($opvalues[2])) $variantArr["option3"] = $opvalues[2];
	
						$variants[] = $variantArr;
					}
	
					if(isset($listingData["PictureDetails"]) && $listingData["PictureDetails"] && isset($listingData["PictureDetails"]["PictureURL"])){
						foreach($listingData["PictureDetails"]["PictureURL"] as $img_url){
							if(!in_array($img_url,$images)) $images[] = $img_url;
						}
					}
	
					if(isset($listingData["Variations"]) && $listingData["Variations"] && isset($listingData["Variations"]["Pictures"]) && $listingData["Variations"]["Pictures"]){
						foreach($listingData["Variations"]["Pictures"][0]["VariationSpecificPictureSet"] as $varPics){
	
							foreach($varPics["PictureURL"] as $img_url){
								if(!in_array($img_url,$images)) $images[] = $img_url;
							}
						}
					}
	
					$productData["variants"] = $variants;
					if($options) $productData["options"] = $options;
	
					$apiResponse = $shopifyClient->Product()->post($productData);
					if(isset($apiResponse["id"]) && $apiResponse["id"]){
						$status = "success";
						$shProduct = $apiResponse;
	
						$sh_pro_id = $shProduct["id"];
						$sh_variants = $shProduct["variants"];
	
						if($images){
							$position = 1;
							foreach($images as $image_url){
								try{
									$imgData = array();
									$imgData["position"] = $position;
									$imgData["src"] = $image_url;
									if($skuImages){
										$varIds = array();
										foreach($sh_variants as $sh_variant){
											$sku = $sh_variant["sku"];
											if(isset($skuImages[$sku]) && $skuImages[$sku] == $image_url){
												$varIds[] = $sh_variant["id"];
											}
										}
										if($varIds) $imgData["variant_ids"] = $varIds;
									}
									$shopifyClient->Product($sh_pro_id)->Image()->post($imgData);
									sleep(1);
								}
								catch(\Exception $e){
									report($e);
									$errors[] = $e->getMessage();
								}
							}
						}
	
						$locations = ($shopifyStore->locations) ? explode(",",$shopifyStore->locations) : array();
						if(!$locations){
							try{
								$shLocations = $shopifyClient->Location()->get();
								if($shLocations){
									foreach($shLocations as $shLocation){
										if($shLocation["active"]) $locations[] = $shLocation["id"];
									}
								}	
							}
							catch(\Exception $e){
								report($e);
								$errors[] = $e->getMessage();
							}
						}
						if($locations){
							foreach($sh_variants as $sh_variant){
								$sku = $sh_variant["sku"];
								$inventory_item_id = $sh_variant["inventory_item_id"];
								if(isset($skuInventory[$sku])){
									$available = $skuInventory[$sku];
									foreach($locations as $location_id){
										try{
											$sdata = array(
												"location_id" => $location_id,
												"inventory_item_id" => $inventory_item_id,
												"available" => $available
											);
											$shopifyClient->InventoryLevel()->set($sdata);
											sleep(1);
										}
										catch(\Exception $e){
											report($e);
											$errors[] = $e->getMessage();
										}
									}
								}
							}
						}
	
						try{
							$shProduct = $shopifyClient->Product($sh_pro_id)->get();
						}
						catch(\Exception $e){
							report($e);
							$errors[] = $e->getMessage();
						}
	
						$productData = array();
						$productData["title"] = $shProduct["title"];
						$productData["image"] = (isset($shProduct["image"]) && $shProduct["image"]) ? $shProduct["image"]["src"] : null;
						$productData["status"] = "published";
						$productData["listing_id"] = $listing->id;
						$productData["shopify_product_id"] = $shProduct["id"];
						$productData["shopify_product_handle"] = $shProduct["handle"];
						$productData["shopify_product_type"] = $shProduct["product_type"];
						$productData["shopify_product_data"] = json_encode($shProduct,JSON_INVALID_UTF8_IGNORE);
						$productData["store_id"] = $shopifyStore->id;
						$productData["user_id"] = $shopifyStore->user_id;
	
						$product = $shopifyStore->products()->create($productData);
						if($product){
							$listing->product_id = $product->id;
							$listing->save();
	
							foreach($shProduct["variants"] as $variant){
								$variantData = array();
	
								if(isset($shProduct["images"]) && $shProduct["images"]){
									$image_id = (isset($variant["image_id"])) ? $variant["image_id"] : null;
									if($image_id){
										foreach($shProduct["images"] as $simage){
											if($simage["id"] == $image_id){
												$variantData["image"] = $simage["src"];
												break;
											}
										}
									}
								}
	
								$variantData["title"] = $variant["title"];
								$variantData["sku"] = $variant["sku"];
								$variantData["price"] = $variant["price"];
								$variantData["compare_at_price"] = $variant["compare_at_price"];
								$variantData["product_id_val"] = $variant["barcode"];
								$variantData["quantity"] = $variant["inventory_quantity"];
								$variantData["shopify_variant_id"] = $variant["id"];
								$variantData["shopify_inventory_item_id"] = $variant["inventory_item_id"];
								$variantData["shopify_product_id"] = $shProduct["id"];
								$variantData["shopify_product_handle"] = $shProduct["handle"];
								$variantData["shopify_variant_data"] = json_encode($variant,JSON_INVALID_UTF8_IGNORE);
								$variantData["product_id"] = $product->id;
	
								$listingVariant = array();
								foreach($listing->variants as $lkey => $lvariant){
									if($lvariant->sku == $variant["sku"] || $lvariant->custom_sku == $variant["sku"]){
										$listingVariant = $lvariant;
										$variantData["listing_variant_id"] = $lvariant->id;
										break;
									}
								}
	
								$variantData["store_id"] = $shopifyStore->id;
								$variantData["user_id"] = $shopifyStore->user_id;
	
								$variant = $product->variants()->create($variantData);
								if(!$variant) $errors[] = "error creating product variant, product id : ".$sh_product_id.", variant id : ".$variant["id"];
								else if($listingVariant){
									$listingVariant->variant_id = $variant->id;
									$listingVariant->save();
								}
							}
						}
						else{
							$errors[] = "error creating product, product id : ".$sh_pro_id;
						}
					}
					else{
						$errors[] = json_encode($apiResponse);
					}
				}
				catch(\Exception $e){
					report($e);
					$errors[] = $e->getMessage();
				}
			}
	
			return ['status' => $status,'errors' => $errors];
		}
	
		return ['status' => 'error','errors' => ["invalid request"]];
	}

	public function createProducts(Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			$validationRules = [
				'listing_ids' => 'required'
			];
			$validator = Validator::make($request->all(),$validationRules);
			if($validator->fails()){
				return response()->json(['status' => 'error', 'msg' => '', 'errors' => $validator->errors()],406);
			}

			// PHPShopify\ShopifySDK::config(array('ShopUrl' => $shopifyStore->shopify_url,'AccessToken' => $shopifyStore->access_token,'ApiVersion' => config('shopify.api_version')));
			// $shopifyClient = new PHPShopify\ShopifySDK;

			$config = array('ShopUrl' => $shopifyStore->shopify_url, 'AccessToken' => $shopifyStore->access_token, 'ApiVersion' => config('shopify.api_version'));
			$shopifyClient = new PHPShopify\ShopifySDK($config);

			$errors = array();

			$succ_count = 0;
			$err_count = 0;
			$listing_ids = $request->input("listing_ids");
			foreach($listing_ids as $listing_id){
				$listing = $shopifyStore->listings()->with('variants')->find($listing_id);
				if($listing && !$listing->product_id){
					try{
						$listingData = json_decode($listing->listing_data,true);
						$additionalData = json_decode($listing->additional_data,true);

						$itemSpecifics = isset($listingData["ItemSpecifics"]) ? $listingData["ItemSpecifics"] : [];
                          Log::info("hitesh product title" . $listing->title);
						$productData = array (
							"title" => $listing->title,
							"body_html" => isset($listingData["Description"]) ? $listingData["Description"] : "",
							"metafields_global_title_tag" => $listing->title,
							"metafields_global_description_tag" => $listing->title,
							"published" => "TRUE"
						);
						$options = array();
						$variants = array();

						if($itemSpecifics){
							foreach($itemSpecifics["NameValueList"] as $itemSpecific){
						     Log::info("hitesh itemSpecifics" . json_encode($itemSpecific,true));
								if($itemSpecific["Name"] == "Brand"){
								      Log::info("hitesh BrandValue" . json_encode($itemSpecific["Value"][0],true));
									$productData["vendor"] = trim($itemSpecific["Value"][0]);
								}
								else if($itemSpecific["Name"] == "Type"){
									$productData["product_type"] = trim($itemSpecific["Value"][0]);
								}
							}
						}


						$variants = array();
						$skuImages = array();
						$skuInventory = array();
						$images = array();
						if($listing->image) $images[] = $listing->image;

						foreach($listing->variants as $lkey => $variant){
							$sku = $variant->sku;
							$custom_sku = "";
							$pvariant = $shopifyStore->variants()->where("sku",$sku)->first();
							if($pvariant){
								$custom_sku = $variant->sku."_".$variant->id;
								$variant->custom_sku = $custom_sku;
								$variant->save();
								$sku = $custom_sku;
								$listing->variants[$lkey]->custom_sku = $custom_sku;
							}

							if($variant->image){
								$skuImages[$sku] = $variant->image;
								if(!in_array($variant->image,$images)) $images[] = $variant->image;
							}

							$lVarData = json_decode($variant->listing_variant_data,true);
							$ebayItemData = json_decode($variant->ebay_item_data,true);
							$addData = json_decode($variant->additional_data,true);
  	                      	Log::info("hitesh productvarients" . json_encode($lVarData,true));
							$opvalues = array();

							if(isset($lVarData["VariationSpecifics"]) && $lVarData["VariationSpecifics"]){
								foreach($lVarData["VariationSpecifics"][0]["NameValueList"] as $ebOption){
									$opname = $ebOption["Name"];
									$opval = $ebOption["Value"][0];

									if(!in_array($opval,$opvalues)) $opvalues[] = $opval;
									$opfound = false;
									if($options){
										foreach($options as $okey => $option){
											if($option["name"] == $opname){
												if(!in_array($opval,$option["values"])) $options[$okey]["values"][] = $opval;
												$opfound = true;
											}
										}
									}
									if(!$opfound){
										$options[] = array(
											"name" => $opname,
											"values" => array($opval)
										);
									}
								}
							}

							$price = 0;
							$quantity = 0;
							$compare_at_price = 0;
							$product_id_val = "";
           
							if(isset($lVarData["StartPrice"]) && $lVarData["StartPrice"]) $price = (float) $lVarData["StartPrice"]['value'];
				// 			if(isset($lVarData["StartPrice"]) && $lVarData["StartPrice"]) $price = (float) $lVarData["StartPrice"];
							Log::info("hitesh price" . json_encode($price,true));
							if(isset($lVarData["Quantity"]) && $lVarData["Quantity"]) $quantity = (int) $lVarData["Quantity"];
							if(isset($lVarData["SellingStatus"]) && $lVarData["SellingStatus"] && isset($lVarData["SellingStatus"]["QuantitySold"])) $quantity = $quantity - $lVarData["SellingStatus"]["QuantitySold"];

							$skuInventory[$sku] = $quantity;

							$weight = 0;
							$weight_unit = null;


							if(isset($ebayItemData["ShippingPackageDetails"]) && $ebayItemData["ShippingPackageDetails"] && isset($ebayItemData["ShippingPackageDetails"]["WeightMajor"])){
								$weight = $ebayItemData["ShippingPackageDetails"]["WeightMajor"]["value"];
								$weight_unit = strtolower($ebayItemData["ShippingPackageDetails"]["WeightMajor"]["unit"]);
								if($weight_unit == "lbs") $weight_unit = "lb";
							}

							$variantArr = array(
								"price" => $price,
								"sku" => $sku,
								"inventory_policy" => "deny",
								"fulfillment_service" => "manual",
								"inventory_management" => "shopify",
								"taxable" => true,
								"requires_shipping" => "true"
							);
							if($compare_at_price > $price) $variantArr["compare_at_price"] = $compare_at_price;
							if($product_id_val) $variantArr["barcode"] = $product_id_val;
							if($weight_unit && $weight){
								$variantArr["weight"] = $weight;
								$variantArr["weight_unit"] = $weight_unit;
							}
							else if(!$weight_unit && $weight) $variantArr["grams"] = $weight;

							if(isset($opvalues[0])) $variantArr["option1"] = $opvalues[0];
							if(isset($opvalues[1])) $variantArr["option2"] = $opvalues[1];
							if(isset($opvalues[2])) $variantArr["option3"] = $opvalues[2];

							$variants[] = $variantArr;
						}

						if(isset($listingData["PictureDetails"]) && $listingData["PictureDetails"] && isset($listingData["PictureDetails"]["PictureURL"])){
							foreach($listingData["PictureDetails"]["PictureURL"] as $img_url){
								if(!in_array($img_url,$images)) $images[] = $img_url;
							}
						}

						if(isset($listingData["Variations"]) && $listingData["Variations"] && isset($listingData["Variations"]["Pictures"]) && $listingData["Variations"]["Pictures"]){
							foreach($listingData["Variations"]["Pictures"][0]["VariationSpecificPictureSet"] as $varPics){

								foreach($varPics["PictureURL"] as $img_url){
									if(!in_array($img_url,$images)) $images[] = $img_url;
								}
							}
						}

						$productData["variants"] = $variants;
						if($options) $productData["options"] = $options;
   	                    	Log::info(" productvarients" . json_encode($productData,true));
						$apiResponse = $shopifyClient->Product()->post($productData);
						if(isset($apiResponse["id"]) && $apiResponse["id"]){
							$shProduct = $apiResponse;

							$sh_pro_id = $shProduct["id"];
							$sh_variants = $shProduct["variants"];

							if($images){
								$position = 1;
								foreach($images as $image_url){
									try{
										$imgData = array();
										$imgData["position"] = $position;
										$imgData["src"] = $image_url;
										if($skuImages){
											$varIds = array();
											foreach($sh_variants as $sh_variant){
												$sku = $sh_variant["sku"];
												if(isset($skuImages[$sku]) && $skuImages[$sku] == $image_url){
													$varIds[] = $sh_variant["id"];
												}
											}
											if($varIds) $imgData["variant_ids"] = $varIds;
										}
										$shopifyClient->Product($sh_pro_id)->Image()->post($imgData);
										sleep(1);
									}
									catch(\Exception $e){
										report($e);
										$errors[] = $e->getMessage();
									}
								}
							}

							$locations = ($shopifyStore->locations) ? explode(",",$shopifyStore->locations) : array();
							if(!$locations){
								try{
									$shLocations = $shopifyClient->Location()->get();
									if($shLocations){
										foreach($shLocations as $shLocation){
											if($shLocation["active"]) $locations[] = $shLocation["id"];
										}
									}	
								}
								catch(\Exception $e){
									report($e);
									$errors[] = $e->getMessage();
								}
							}
							if($locations){
								foreach($sh_variants as $sh_variant){
									$sku = $sh_variant["sku"];
									$inventory_item_id = $sh_variant["inventory_item_id"];
									if(isset($skuInventory[$sku])){
										$available = $skuInventory[$sku];
										foreach($locations as $location_id){
											try{
												$sdata = array(
													"location_id" => $location_id,
													"inventory_item_id" => $inventory_item_id,
													"available" => $available
												);
												$shopifyClient->InventoryLevel()->set($sdata);
												sleep(1);
											}
											catch(\Exception $e){
												report($e);
												$errors[] = $e->getMessage();
											}
										}
									}
								}
							}

							try{
								$shProduct = $shopifyClient->Product($sh_pro_id)->get();
							}
							catch(\Exception $e){
								report($e);
								$errors[] = $e->getMessage();
							}

							$productData = array();
							$productData["title"] = $shProduct["title"];
							 Log::info("hitesh product title2" . $productData["title"]);
							$productData["image"] = (isset($shProduct["image"]) && $shProduct["image"]) ? $shProduct["image"]["src"] : null;
				// 			$productData["status"] = "Published";
				         	$productData["status"] = "Created";
							$productData["listing_id"] = $listing->id;
							$productData["shopify_product_id"] = $shProduct["id"];
							$productData["shopify_product_handle"] = $shProduct["handle"];
							$productData["shopify_product_type"] = $shProduct["product_type"];
							$productData["shopify_product_data"] = json_encode($shProduct,JSON_INVALID_UTF8_IGNORE);
							$productData["store_id"] = $shopifyStore->id;
							$productData["user_id"] = $shopifyStore->user_id;

							$product = $shopifyStore->products()->create($productData);
							if($product){
								$listing->product_id = $product->id;
								$listing->save();

								foreach($shProduct["variants"] as $variant){
									$variantData = array();

									if(isset($shProduct["images"]) && $shProduct["images"]){
										$image_id = (isset($variant["image_id"])) ? $variant["image_id"] : null;
										if($image_id){
											foreach($shProduct["images"] as $simage){
												if($simage["id"] == $image_id){
													$variantData["image"] = $simage["src"];
													break;
												}
											}
										}
									}

									$variantData["title"] = $variant["title"];
									
									$variantData["sku"] = $variant["sku"];
									$variantData["price"] = $variant["price"];
									$variantData["compare_at_price"] = $variant["compare_at_price"];
									$variantData["product_id_val"] = $variant["barcode"];
									$variantData["quantity"] = $variant["inventory_quantity"];
									$variantData["shopify_variant_id"] = $variant["id"];
									$variantData["shopify_inventory_item_id"] = $variant["inventory_item_id"];
									$variantData["shopify_product_id"] = $shProduct["id"];
									$variantData["shopify_product_handle"] = $shProduct["handle"];
									$variantData["shopify_variant_data"] = json_encode($variant,JSON_INVALID_UTF8_IGNORE);
									$variantData["product_id"] = $product->id;

									$listingVariant = array();
									foreach($listing->variants as $lkey => $lvariant){
										if($lvariant->sku == $variant["sku"] || $lvariant->custom_sku == $variant["sku"]){
											$listingVariant = $lvariant;
											$variantData["listing_variant_id"] = $lvariant->id;
											break;
										}
									}

									$variantData["store_id"] = $shopifyStore->id;
									$variantData["user_id"] = $shopifyStore->user_id;

									$variant = $product->variants()->create($variantData);
									if($lvariant->sku != ''){
									$listingVariant->sku = 'ebaylistingcreated'.$lvariant->sku ;
									}else{
									    $listingVariant->sku = 'ebaylistingcreated';
									}
									$listingVariant->custom_sku = $variant->shopify_variant_id; // himanshu changes 26-04-2024
									if(!$variant) $errors[] = "error creating product variant, product id : ".$sh_product_id.", variant id : ".$variant["id"];
									else if($listingVariant){
										$listingVariant->variant_id = $variant->id;
										Log::info("hiteshitemSpecifics" . $variant->id . 'hhhhh');
                                       // $listingVariant->sku = 'mlaiasjfkjsahfhsfh';
										$listingVariant->save();
									}
								}
							}
							else{
								$errors[] = "error creating product, product id : ".$sh_pro_id;
							}
						}
						else{
							$err_count++;
							$errors[] = json_encode($apiResponse);
						}
					}
					catch(\Exception $e){
						report($e);
						$err_count++;
						$errors[] = $e->getMessage();
					}
				}
			}
			
			if($errors) file_put_contents("createProductsErrorShopify_".$shopifyStore->id.".json",json_encode($errors));
			return response()->json(['status' => 'success','msg' => 'listing product created successfully','succ_count' => $succ_count,'err_count' => $err_count],200);
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}

	public function createProductsBulk(Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			$title = trim($request->input("title"));
			$status = trim($request->input("status"));
			$ebay_item_id = trim($request->input("ebay_item_id"));
			$sku = trim($request->input("sku"));

			$conditions = [];
			if($title) $conditions[] = ["title","like","%".$title."%"];
			if($status) $conditions[] = ["status","=",$status];

			$vconditions = [];
			if($ebay_item_id) $vconditions[] = ["ebay_item_id","=",$ebay_item_id];
			if($sku) $vconditions[] = ["sku","=",$sku];
			
			$jobData = [];
			$jobData["conditions"] = $conditions;
			$jobData["vconditions"] = $vconditions;
			$jobData["store_id"] = $shopifyStore->id;
			$jobData["user_id"] = $shopifyStore->user_id;

			CreateProductsFromListings::dispatch($jobData)->delay(now()->addMinutes(1));
			
			return response()->json(['status' => 'success','msg' => "create products request submitted, it will be processed soon."],200);
			
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}

	public function destroy(Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			$validationRules = [
				'listing_ids' => 'required'
			];
			$validator = Validator::make($request->all(),$validationRules);
			if($validator->fails()){
				return response()->json(['status' => 'error', 'msg' => '', 'errors' => $validator->errors()],406);
			}

			$listing_ids = $request->input("listing_ids");
			foreach($listing_ids as $listing_id){
				$listing = $shopifyStore->listings()->with('variants')->find($listing_id);
				if($listing && $listing->product_id){
					$product_id = $listing->product_id;
					$product = $shopifyStore->products()->with('variants')->find($product_id);
					if($product && $product->listing_id){
						$product->listing_id = NULL;
						$product->status = "unpublished";
						$product->save();
						foreach($product->variants as $variant){
							$variant->listing_variant_id = NULL;
							$variant->save();
						}				
					}
				}
				if($listing) $listing->delete();
			}
			return response()->json(['status' => 'success','msg' => 'listing deleted successfully'],200);
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}

	public function submitListingsImportRequest(Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			try{
				$ebayAccounts = $shopifyStore->ebayAccounts()->where("is_valid",1)->get();
				if($ebayAccounts->count() > 0){
					foreach($ebayAccounts as $ebayAccount){
						$ebayAccount->import_products = 1;
						$ebayAccount->save();
					}
					return response()->json(['status' => 'success','msg' => "Import request submitted. It will be processed soon."],200);
				}
				else{
					return response()->json(['status' => 'error','msg' => "invalid ebay keys"],406);
				}
			}
			catch(\Exception $e){
				report($e);
				return response()->json(['status' => 'error','msg' => $e->getMessage()],406);
			}
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}
	
    public function importEbayProducts(){
    	Log::channel('importlistings')->info("entered in ImportEbayProducts method");
    	$cronJob = CronJob::where('type', 'import_account_products')->first();
    	if ($cronJob && ($cronJob->flag == 1 || $cronJob->do_stop == 1)) {
    		return response()->json(['status' => 'error', 'msg' => "cron already running"], 406);
    	} else {
    		$cronJob->flag = 1;
    		$cronJob->started_at = date("Y-m-d H:i:s");
    		$cronJob->ended_at = NULL;
    		$cronJob->last_updated_at = date("Y-m-d H:i:s");
    		$cronJob->save();
    	}
   
    	$importconditions[] = array("import_products","=",1);
     	$shopifyStores = ShopifyStore::where('status', "active")->whereHas('ebayAccounts',function($query) use($importconditions){$query->where($importconditions);})->get();
       
    		 foreach ($shopifyStores as $shopifyStore) {
    					  Log::channel('importlistings')->info("ImportEbayProducts method filter  shopify store user id ".$shopifyStore->user_id );
    				// 	  echo "<pre>";
    				// 	  print_r($shopifyStore);
    				// 	  echo "</pre>";
    					  $ebayAccounts = $shopifyStore->ebayAccounts()->where("is_valid", 1)->where("import_products", 1)->get();
    			foreach ($ebayAccounts as $ebayAccount) {
    				$ebay_token = $ebayAccount->access_token;
    				Log::channel('importlistings')->info("Here is the ebay token ".$ebay_token );
    				$site_id = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
    				
    			if ($shopifyStore->user_id == 2)	$ebay_environment = "sandbox";
    			else $ebay_environment = config('ebay.environment');
    			
					$ebayCredentials = array(
        				'credentials' => [
        					'devId' => config('ebay.' . $ebay_environment . 'devid'),
        					'appId' => config('ebay.' . $ebay_environment . 'appid'),
        					'certId' => config('ebay.' . $ebay_environment . 'certid'),
        				],
        				'authToken' => '',
        				'oauthUserToken' => '',
        				'ruName' => config('ebay.' . $ebay_environment . 'RuName')
    			    );
    				$ebayService = new Services\TradingService([
						'credentials' => $ebayCredentials['credentials'],
						'sandbox' => ($ebay_environment == "sandbox") ? true : false,
						'siteId' => $site_id
					]);
					 $ebConfig = array('production' => 
					 array('credentials' => array(
    					'devId' =>  config('ebay.' . $ebay_environment . 'devid'),
    					'appId' => config('ebay.' . $ebay_environment . 'appid'),
    					'certId' =>config('ebay.' . $ebay_environment . 'certid')),
    				 ));
                    $service = new Services\TradingService([
                        'credentials' => $ebConfig['production']['credentials'],
                        'sandbox'     => false,
                        'siteId'      => $site_id
	                ]);	
					$request1 = new Types\GetTokenStatusRequestType();
					$request1->RequesterCredentials = new Types\CustomSecurityHeaderType();
					$request1->RequesterCredentials->eBayAuthToken = $ebay_token;
					$response1 = $service->getTokenStatus($request1);
					Log::channel('importlistings')->info("ImportEbayProducts method ebay token status store user id ".$shopifyStore->user_id." is ".( $response1) );
					if($response1->Ack !== 'Failure') 
					{
					    if(!isset($response1->TokenStatus))
					    {				
						   Log::channel('importlistings')->info("token status not found");
					    }
					    $tokenStatus = $response1->TokenStatus;
					    //echo "status is ".   $tokenStatus->Status. " for  ".$user_id."\n";
    					if( $tokenStatus->Status == 'Active')
    					{
    						Log::channel('importlistings')->info("token status is active for ->" .json_encode($shopifyStore,true));
    						$this->fetchebayproducts($shopifyStore,$ebayAccount,$ebay_token,$service,$cronJob,$ebayService);    						
    						$ebayAccount->import_products = 0;
    						$ebayAccount->save();
    					}else{
    						Log::channel('importlistings')->info("token status is inactive"); 
    						$ebayAccount->import_products = 0;
    						$ebayAccount->save();
    						//TODO: we would send an email for reauthorization
    					}
					}else{
					    
					    // error log expain 
						 Log::channel('importlistings')->info("response not correct");
					}	
    			}
    		 }
    			 //todo: write code to update items which are not on ebay now mark them as deleted.
    	$cronJob->flag = 0;
    	$cronJob->ended_at = date("Y-m-d H:i:s");
    	$cronJob->last_updated_at = date("Y-m-d H:i:s");
    	$cronJob->save();
    	Log::channel('importlistings')->info("complete process done");
    	return response()->json(['status' => 'success', 'msg' => "done"], 200);
    }
		
    public function fetchebayproducts($shopifyStore,$ebayAccount, $ebay_token,$service,$cronJob,$ebayService) {

    	$existing_items_in_db = array(); // check active or inactive if parentID found in db so we will update itenID in DB for relisted ITEM
     	$Relisted_items_from_ebay = array(); // item relisted but not in DB so we add in DB
    	$Not_Relisted_found_in_db = array(); // continue
    	$Not_Relisted_not_found_in_db = array(); // so we will add in db
    	$Products_from_eBay = array(); // conpare in db and ebay and if item is ended on ebay and not linked with or app so we will delete from on app

    	// PHPShopify\ShopifySDK::config(array('ShopUrl' => $shopifyStore->shopify_url, 'AccessToken' => $shopifyStore->access_token, 'ApiVersion' => config('shopify.api_version')));

		$config = array('ShopUrl' => $shopifyStore->shopify_url, 'AccessToken' => $shopifyStore->access_token, 'ApiVersion' => config('shopify.api_version'));
		$shopifyClient = new PHPShopify\ShopifySDK($config);
    
    	Log::channel('importlistings')->info("ImportEbayProducts method  shopify conection stop store  id " . $shopifyStore->id);
    	// $shopifyClient = new PHPShopify\ShopifySDK;
    	$errors = array();
    	$shopify_store_id = $shopifyStore->id;
    	$store_database_name = config('config.store_db_prefix') . $shopify_store_id;
    	Log::channel('importlistings')->info("ImportEbayProducts method  shopify store  id " . $shopifyStore->id);
    	AppHelper::setConnection($store_database_name, $shopifyStore);
    	Log::channel('importlistings')->info("Entering in try method of ImportEbayProducts method  shopify store  id " . $shopifyStore->id);
    	Log::channel('importlistings')->info("ebay token status is Active for store id " . $shopifyStore->id);
		// 	Log::channel('importlistings')->info("Finding existing items in db for ebay account " . $ebayAccount->sellerid);
			// $existing_items_in_db = $shopifyStore->listings()->where("status", "published")->find("ebay_item_id");
		// 	$existing_items_in_db = $shopifyStore->listings()->where("status", "published")->get();
		// 	Log::channel('importlistings')->info("existing items in db " . json_encode($existing_items_in_db));
    	//todo change this
    	Log::channel('importlistings')->info("starting get my ebay selling request type for " . $shopifyStore->user_id);
    	
    	
    	$request = new Types\GetMyeBaySellingRequestType();
    	$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
    	$request->RequesterCredentials->eBayAuthToken = $ebay_token;
    	$request->ActiveList = new Types\ItemListCustomizationType();
    	$request->ActiveList->Include = true;
    	$request->ActiveList->Pagination = new Types\PaginationType();
    	$request->ActiveList->Pagination->EntriesPerPage = 100;
    	$request->OutputSelector = array("PaginationResult", "ItemID", "ListingType");
    	$pageNum = 1;
    	//sleep(5);
    	do {
    		$request->ActiveList->Pagination->PageNumber = $pageNum;
    		sleep(5);
    		try {
    			Log::channel('importlistings')->info("getting ebayResponse");
    			$ebayResponse = $service->getMyeBaySelling($request);
    			$ebayResponse = $ebayResponse->toArray();

				
    			//Log::channel('importlistings')->info("getting ebayResponse" . json_encode($ebayResponse));
    			//sleep(5);
    		
    		}
    		catch(Exception $e) {
    			sleep(5);
    			Log::error("Error fetching eBay products: " . $e->getMessage());
    			continue;
    		}
    		$cronJob2 = AppHelper::getCronJob($cronJob->type);
    		if ($cronJob2 && $cronJob2->do_stop) break;
    		Log::channel('importlistings')->info("ImportEbayProducts method  seller list is sent with item ids ");
    		if ($ebayResponse["Ack"] !== 'Failure' && isset($ebayResponse["ActiveList"]["ItemArray"]["Item"])) {
    			Log::channel('importlistings')->info("ebay response is success for item   ");
    			foreach ($ebayResponse["ActiveList"]["ItemArray"]["Item"] as $product) {
    			   Log::channel('importlistings')->info("ebay product detail is here ->   " . json_encode($product,true));
    				$itemId = $product["ItemID"];
    				$Products_from_eBay[] = $product["ItemID"];
    				Log::channel('importlistings')->info("ebay response is successful item id is this " . $itemId);
    				$listingType = $product["ListingType"];
    				Log::channel('importlistings')->info("ebay response is successful listing Type thisssssssssss" . $listingType);
    				$Active_items_from_ebay = $ebayResponse;
    				Log::channel('importlistings')->info("111111111111111111111111111111111111   " . $product["ItemID"]);
    				$cronJob2 = AppHelper::getCronJob($cronJob->type);
    				if ($cronJob2 && $cronJob2->do_stop) break;
    				$cronJob->last_updated_at = date("Y-m-d H:i:s");
    				$cronJob->save();
    				Log::channel('importlistings')->info("222222222222222222222222222222   " . $product["ItemID"]);
    				try {
    					Log::channel('importlistings')->info("3333333333333333333333333333333333   " . $product["ItemID"]);
    					$item_id = (string)$product["ItemID"];
    					$ebayItemRequest = new Types\GetItemRequestType();
    					$ebayItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
    					$ebayItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
    					$ebayItemRequest->ItemID = $item_id;
    					$ebayItemRequest->IncludeItemSpecifics = true;
    					Log::channel('importlistings')->info("5555555555555555555555   " . $product["ItemID"]);
    					sleep(2);
    					$ebayItemResponse = $service->getItem($ebayItemRequest);
    					$ebayItemResponse = $ebayItemResponse->toArray();

						// echo "<pre>";
						// print_r($ebayItemResponse);
						// echo "</pre>";
						// dd($ebayItemResponse);
    					
    					Log::channel('importlistings')->info("ebay item response for 3333333333333333334444444444444   " . $product["ItemID"]);
    					if (isset($ebayItemResponse["Item"]) && $ebayItemResponse["Item"]) {
    						$ebayItem = $ebayItemResponse["Item"];
    					}
    					// Log::channel('importlistings')->info("  Here is the ebay Itemmmmmm ".json_encode($ebayItem,true) );
    					Log::channel('importlistings')->info("finding relistParentID for this listing Type ->" . $listingType);
    					$relistParentID = isset($ebayItem["RelistParentID"]) ? (string)$ebayItem["RelistParentID"] : "";
    					if ($relistParentID) {
    						Log::channel('importlistings')->info("item is relisted so we would update the info in db ");
    						// add this in array of relisted item ids
    						//$listing = array_search($relistParentID, $existing_items_in_db);
    						$listing = $shopifyStore->listings()->with('variants')->where('ebay_item_id', $relistParentID)->first();
    						if ($listing) {
    							Log::channel('importlistings')->info("item found in listing in db and parent item id is in db");
                                $this->ProcessRelisteditem($site_id,$ebay_token,$relistParentID,$item_id,$shopify_store_id);
    							$Relisted_items_from_ebay = $relistParentID;
    						}else{
                                $listingindb = $shopifyStore->listings()->with('variants')->where('ebay_item_id', $item_id)->first();
                                if (!$listingindb) {
									$this->insertebproducts($shopifyStore,$ebayAccount,$item_id,$ebayItem);
									Log::channel('importlistings')->info("item is relisted but not found in DB");
								}
								else {
									Log::channel('importlistings')->info("item is relisted but  found in DB so we would not add it");
								}								
							}
    					} else {
							// RelistParentID not found means new item
							// $endTime = date("Y-m-d", strtotime($ebayItem["ListingDetails"]["EndTime"]));
							// $dateToday = date("Y-m-d");
							// if (strtotime($endTime) <= strtotime($dateToday))
							// 	continue;
							Log::channel('importlistings')->info("item is not relisted and new we would check it in db " . $item_id);
							$listing = $shopifyStore->listings()->where('ebay_item_id', $item_id)->first();
							if ($listing) {
								Log::channel('importlistings')->info(" item is not relisted and found in db " . $item_id);
								$Not_Relisted_found_in_db = $listing;
							} else {
								Log::channel('importlistings')->info(" item not in DB and not relisted " . $item_id);
								$this->insertebproducts($shopifyStore,$ebayAccount,$item_id,$ebayItem);
							}
						}
    					Log::channel('importlistings')->info("relistParentID not found for this listing Typeeee" . $listingType);
    					Log::channel('importlistings')->info("listing not found where ebay item id unpublished for item id" . $item_id);
    				}
    				catch(Exception $e) {
    					$errors[] = array("errortype" => "Exception Product Loop", "line" => $e->getLine(), "msg" => $e->getMessage(), "item_id" => $item_id, "store_id" => $shopifyStore->id, "account_id" => $ebayAccount->id);
    				}
					Log::channel('importlistings')->info("product loop end");
    			}
    			Log::channel('importlistings')->info("importlistings Products_from_eBay " . json_encode($Products_from_eBay, true));
    			//	$Re_verify_listings = $shopifyStore->listings()->whereNotIn('ebay_item_id', $Products_from_eBay)->get();
    			$Re_verify_listings = $shopifyStore->listings()->whereNotIn('ebay_item_id', $Products_from_eBay)->pluck('ebay_item_id');
    			Log::channel('importlistings')->info("importlistings Re_verify_listings products" . json_encode($Re_verify_listings, true));
    			foreach ($Re_verify_listings as $Re_verify_listing) {
    			    Log::channel('importlistings')->info("inside foreach loop Re_verify_listing");
    				$item_id = (string)$Re_verify_listing;
    				$ebayItemRequest = new Types\GetItemRequestType();
    				$ebayItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
    				$ebayItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
    				$ebayItemRequest->ItemID = $item_id;
    				$ebayItemRequest->IncludeItemSpecifics = true;
    				sleep(2);
    				// $ebayItemResponse = $ebayService->getItem($ebayItemRequest);
    				$ebayItemResponse = $service->getItem($ebayItemRequest);
    				$ebayItemResponse = $ebayItemResponse->toArray();
    				if (isset($ebayItemResponse["Item"]) && $ebayItemResponse["Item"]) {
    					$ebayItem = $ebayItemResponse["Item"];
    				}
    				Log::channel('importlistings')->info("ListingStatus -> " . json_encode($ebayItem['SellingStatus']['ListingStatus'], true) . " for ebay item id " . $item_id);
    				if ($ebayItem['SellingStatus']['ListingStatus'] == "Completed") {
    					$shopifyStore->listings()->where('ebay_item_id', $item_id)->update(['status' => 'Ended']);
						//TODO:if it s unlinked we would delete it from db.
    					Log::channel('importlistings')->info("Successfully mark ended in listing for ended product ");
    				}
    			}
    			//	$shopifyStore->listings()->whereNotIn('ebay_item_id', $Products_from_eBay)->update(['status' => 'Ended']);
    			
    		} else {
    			Log::channel('importlistings')->info("ebay response is failure for item ids ");
    			$errmsg = "";
    			if (isset($response->Errors)) {
    				foreach ($ebayResponse->Errors as $error) {
    					$errmsg = $errmsg . " :: " . $error->LongMessage;
    				}
    			}
    			// verifyToken($user_id, $token, $siteid);
    			// addlog("Error in getting active listings of user. user_id - ".$user_id.", Error - ".$errmsg, "ERROR");
    			
    		}
    		$pageNum+= 1;
    		/*if($user_id != 13117 && $pageNum > 50){
    		break;
    		}*/
    	}
    	while (isset($ebayResponse["ActiveList"]) && $pageNum <= $ebayResponse["ActiveList"]["PaginationResult"]["TotalNumberOfPages"]);
    	Log::channel('importlistings')->info("current products in ebay are " . sizeof($Products_from_eBay));
    }
    
	function remove_emoji($text){
		return preg_replace('/[\x{1F3F4}](?:\x{E0067}\x{E0062}\x{E0077}\x{E006C}\x{E0073}\x{E007F})|[\x{1F3F4}](?:\x{E0067}\x{E0062}\x{E0073}\x{E0063}\x{E0074}\x{E007F})|[\x{1F3F4}](?:\x{E0067}\x{E0062}\x{E0065}\x{E006E}\x{E0067}\x{E007F})|[\x{1F3F4}](?:\x{200D}\x{2620}\x{FE0F})|[\x{1F3F3}](?:\x{FE0F}\x{200D}\x{1F308})|[\x{0023}\x{002A}\x{0030}\x{0031}\x{0032}\x{0033}\x{0034}\x{0035}\x{0036}\x{0037}\x{0038}\x{0039}](?:\x{FE0F}\x{20E3})|[\x{1F441}](?:\x{FE0F}\x{200D}\x{1F5E8}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F467}\x{200D}\x{1F467})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F467}\x{200D}\x{1F466})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F467})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F466}\x{200D}\x{1F466})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F466})|[\x{1F468}](?:\x{200D}\x{1F468}\x{200D}\x{1F467}\x{200D}\x{1F467})|[\x{1F468}](?:\x{200D}\x{1F468}\x{200D}\x{1F466}\x{200D}\x{1F466})|[\x{1F468}](?:\x{200D}\x{1F468}\x{200D}\x{1F467}\x{200D}\x{1F466})|[\x{1F468}](?:\x{200D}\x{1F468}\x{200D}\x{1F467})|[\x{1F468}](?:\x{200D}\x{1F468}\x{200D}\x{1F466})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F469}\x{200D}\x{1F467}\x{200D}\x{1F467})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F469}\x{200D}\x{1F466}\x{200D}\x{1F466})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F469}\x{200D}\x{1F467}\x{200D}\x{1F466})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F469}\x{200D}\x{1F467})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F469}\x{200D}\x{1F466})|[\x{1F469}](?:\x{200D}\x{2764}\x{FE0F}\x{200D}\x{1F469})|[\x{1F469}\x{1F468}](?:\x{200D}\x{2764}\x{FE0F}\x{200D}\x{1F468})|[\x{1F469}](?:\x{200D}\x{2764}\x{FE0F}\x{200D}\x{1F48B}\x{200D}\x{1F469})|[\x{1F469}\x{1F468}](?:\x{200D}\x{2764}\x{FE0F}\x{200D}\x{1F48B}\x{200D}\x{1F468})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F9B3})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F9B3})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F9B3})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F9B3})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F9B3})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F9B3})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F9B2})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F9B2})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F9B2})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F9B2})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F9B2})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F9B2})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F9B1})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F9B1})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F9B1})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F9B1})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F9B1})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F9B1})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F9B0})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F9B0})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F9B0})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F9B0})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F9B0})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F9B0})|[\x{1F575}\x{1F3CC}\x{26F9}\x{1F3CB}](?:\x{FE0F}\x{200D}\x{2640}\x{FE0F})|[\x{1F575}\x{1F3CC}\x{26F9}\x{1F3CB}](?:\x{FE0F}\x{200D}\x{2642}\x{FE0F})|[\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{1F3FF}\x{200D}\x{2640}\x{FE0F})|[\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{1F3FE}\x{200D}\x{2640}\x{FE0F})|[\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{1F3FD}\x{200D}\x{2640}\x{FE0F})|[\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{1F3FC}\x{200D}\x{2640}\x{FE0F})|[\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{1F3FB}\x{200D}\x{2640}\x{FE0F})|[\x{1F46E}\x{1F9B8}\x{1F9B9}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F9DE}\x{1F9DF}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F46F}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93C}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{200D}\x{2640}\x{FE0F})|[\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{1F3FF}\x{200D}\x{2642}\x{FE0F})|[\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{1F3FE}\x{200D}\x{2642}\x{FE0F})|[\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{1F3FD}\x{200D}\x{2642}\x{FE0F})|[\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{1F3FC}\x{200D}\x{2642}\x{FE0F})|[\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{1F3FB}\x{200D}\x{2642}\x{FE0F})|[\x{1F46E}\x{1F9B8}\x{1F9B9}\x{1F482}\x{1F477}\x{1F473}\x{1F471}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F9DE}\x{1F9DF}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F46F}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93C}\x{1F93D}\x{1F93E}\x{1F939}](?:\x{200D}\x{2642}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F692})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F692})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F692})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F692})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F692})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F692})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F680})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F680})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F680})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F680})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F680})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F680})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{2708}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{2708}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{2708}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{2708}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{2708}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{200D}\x{2708}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F3A8})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F3A8})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F3A8})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F3A8})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F3A8})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F3A8})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F3A4})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F3A4})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F3A4})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F3A4})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F3A4})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F3A4})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F4BB})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F4BB})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F4BB})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F4BB})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F4BB})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F4BB})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F52C})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F52C})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F52C})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F52C})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F52C})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F52C})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F4BC})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F4BC})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F4BC})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F4BC})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F4BC})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F4BC})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F3ED})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F3ED})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F3ED})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F3ED})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F3ED})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F3ED})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F527})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F527})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F527})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F527})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F527})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F527})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F373})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F373})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F373})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F373})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F373})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F373})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F33E})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F33E})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F33E})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F33E})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F33E})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F33E})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{2696}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{2696}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{2696}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{2696}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{2696}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{200D}\x{2696}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F3EB})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F3EB})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F3EB})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F3EB})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F3EB})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F3EB})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{1F393})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{1F393})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{1F393})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{1F393})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{1F393})|[\x{1F468}\x{1F469}](?:\x{200D}\x{1F393})|[\x{1F468}\x{1F469}](?:\x{1F3FF}\x{200D}\x{2695}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FE}\x{200D}\x{2695}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FD}\x{200D}\x{2695}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FC}\x{200D}\x{2695}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{1F3FB}\x{200D}\x{2695}\x{FE0F})|[\x{1F468}\x{1F469}](?:\x{200D}\x{2695}\x{FE0F})|[\x{1F476}\x{1F9D2}\x{1F466}\x{1F467}\x{1F9D1}\x{1F468}\x{1F469}\x{1F9D3}\x{1F474}\x{1F475}\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F934}\x{1F478}\x{1F473}\x{1F472}\x{1F9D5}\x{1F9D4}\x{1F471}\x{1F935}\x{1F470}\x{1F930}\x{1F931}\x{1F47C}\x{1F385}\x{1F936}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F483}\x{1F57A}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F6C0}\x{1F6CC}\x{1F574}\x{1F3C7}\x{1F3C2}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}\x{1F933}\x{1F4AA}\x{1F9B5}\x{1F9B6}\x{1F448}\x{1F449}\x{261D}\x{1F446}\x{1F595}\x{1F447}\x{270C}\x{1F91E}\x{1F596}\x{1F918}\x{1F919}\x{1F590}\x{270B}\x{1F44C}\x{1F44D}\x{1F44E}\x{270A}\x{1F44A}\x{1F91B}\x{1F91C}\x{1F91A}\x{1F44B}\x{1F91F}\x{270D}\x{1F44F}\x{1F450}\x{1F64C}\x{1F932}\x{1F64F}\x{1F485}\x{1F442}\x{1F443}](?:\x{1F3FF})|[\x{1F476}\x{1F9D2}\x{1F466}\x{1F467}\x{1F9D1}\x{1F468}\x{1F469}\x{1F9D3}\x{1F474}\x{1F475}\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F934}\x{1F478}\x{1F473}\x{1F472}\x{1F9D5}\x{1F9D4}\x{1F471}\x{1F935}\x{1F470}\x{1F930}\x{1F931}\x{1F47C}\x{1F385}\x{1F936}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F483}\x{1F57A}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F6C0}\x{1F6CC}\x{1F574}\x{1F3C7}\x{1F3C2}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}\x{1F933}\x{1F4AA}\x{1F9B5}\x{1F9B6}\x{1F448}\x{1F449}\x{261D}\x{1F446}\x{1F595}\x{1F447}\x{270C}\x{1F91E}\x{1F596}\x{1F918}\x{1F919}\x{1F590}\x{270B}\x{1F44C}\x{1F44D}\x{1F44E}\x{270A}\x{1F44A}\x{1F91B}\x{1F91C}\x{1F91A}\x{1F44B}\x{1F91F}\x{270D}\x{1F44F}\x{1F450}\x{1F64C}\x{1F932}\x{1F64F}\x{1F485}\x{1F442}\x{1F443}](?:\x{1F3FE})|[\x{1F476}\x{1F9D2}\x{1F466}\x{1F467}\x{1F9D1}\x{1F468}\x{1F469}\x{1F9D3}\x{1F474}\x{1F475}\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F934}\x{1F478}\x{1F473}\x{1F472}\x{1F9D5}\x{1F9D4}\x{1F471}\x{1F935}\x{1F470}\x{1F930}\x{1F931}\x{1F47C}\x{1F385}\x{1F936}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F483}\x{1F57A}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F6C0}\x{1F6CC}\x{1F574}\x{1F3C7}\x{1F3C2}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}\x{1F933}\x{1F4AA}\x{1F9B5}\x{1F9B6}\x{1F448}\x{1F449}\x{261D}\x{1F446}\x{1F595}\x{1F447}\x{270C}\x{1F91E}\x{1F596}\x{1F918}\x{1F919}\x{1F590}\x{270B}\x{1F44C}\x{1F44D}\x{1F44E}\x{270A}\x{1F44A}\x{1F91B}\x{1F91C}\x{1F91A}\x{1F44B}\x{1F91F}\x{270D}\x{1F44F}\x{1F450}\x{1F64C}\x{1F932}\x{1F64F}\x{1F485}\x{1F442}\x{1F443}](?:\x{1F3FD})|[\x{1F476}\x{1F9D2}\x{1F466}\x{1F467}\x{1F9D1}\x{1F468}\x{1F469}\x{1F9D3}\x{1F474}\x{1F475}\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F934}\x{1F478}\x{1F473}\x{1F472}\x{1F9D5}\x{1F9D4}\x{1F471}\x{1F935}\x{1F470}\x{1F930}\x{1F931}\x{1F47C}\x{1F385}\x{1F936}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F483}\x{1F57A}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F6C0}\x{1F6CC}\x{1F574}\x{1F3C7}\x{1F3C2}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}\x{1F933}\x{1F4AA}\x{1F9B5}\x{1F9B6}\x{1F448}\x{1F449}\x{261D}\x{1F446}\x{1F595}\x{1F447}\x{270C}\x{1F91E}\x{1F596}\x{1F918}\x{1F919}\x{1F590}\x{270B}\x{1F44C}\x{1F44D}\x{1F44E}\x{270A}\x{1F44A}\x{1F91B}\x{1F91C}\x{1F91A}\x{1F44B}\x{1F91F}\x{270D}\x{1F44F}\x{1F450}\x{1F64C}\x{1F932}\x{1F64F}\x{1F485}\x{1F442}\x{1F443}](?:\x{1F3FC})|[\x{1F476}\x{1F9D2}\x{1F466}\x{1F467}\x{1F9D1}\x{1F468}\x{1F469}\x{1F9D3}\x{1F474}\x{1F475}\x{1F46E}\x{1F575}\x{1F482}\x{1F477}\x{1F934}\x{1F478}\x{1F473}\x{1F472}\x{1F9D5}\x{1F9D4}\x{1F471}\x{1F935}\x{1F470}\x{1F930}\x{1F931}\x{1F47C}\x{1F385}\x{1F936}\x{1F9D9}\x{1F9DA}\x{1F9DB}\x{1F9DC}\x{1F9DD}\x{1F64D}\x{1F64E}\x{1F645}\x{1F646}\x{1F481}\x{1F64B}\x{1F647}\x{1F926}\x{1F937}\x{1F486}\x{1F487}\x{1F6B6}\x{1F3C3}\x{1F483}\x{1F57A}\x{1F9D6}\x{1F9D7}\x{1F9D8}\x{1F6C0}\x{1F6CC}\x{1F574}\x{1F3C7}\x{1F3C2}\x{1F3CC}\x{1F3C4}\x{1F6A3}\x{1F3CA}\x{26F9}\x{1F3CB}\x{1F6B4}\x{1F6B5}\x{1F938}\x{1F93D}\x{1F93E}\x{1F939}\x{1F933}\x{1F4AA}\x{1F9B5}\x{1F9B6}\x{1F448}\x{1F449}\x{261D}\x{1F446}\x{1F595}\x{1F447}\x{270C}\x{1F91E}\x{1F596}\x{1F918}\x{1F919}\x{1F590}\x{270B}\x{1F44C}\x{1F44D}\x{1F44E}\x{270A}\x{1F44A}\x{1F91B}\x{1F91C}\x{1F91A}\x{1F44B}\x{1F91F}\x{270D}\x{1F44F}\x{1F450}\x{1F64C}\x{1F932}\x{1F64F}\x{1F485}\x{1F442}\x{1F443}](?:\x{1F3FB})|[\x{1F1E6}\x{1F1E7}\x{1F1E8}\x{1F1E9}\x{1F1F0}\x{1F1F2}\x{1F1F3}\x{1F1F8}\x{1F1F9}\x{1F1FA}](?:\x{1F1FF})|[\x{1F1E7}\x{1F1E8}\x{1F1EC}\x{1F1F0}\x{1F1F1}\x{1F1F2}\x{1F1F5}\x{1F1F8}\x{1F1FA}](?:\x{1F1FE})|[\x{1F1E6}\x{1F1E8}\x{1F1F2}\x{1F1F8}](?:\x{1F1FD})|[\x{1F1E6}\x{1F1E7}\x{1F1E8}\x{1F1EC}\x{1F1F0}\x{1F1F2}\x{1F1F5}\x{1F1F7}\x{1F1F9}\x{1F1FF}](?:\x{1F1FC})|[\x{1F1E7}\x{1F1E8}\x{1F1F1}\x{1F1F2}\x{1F1F8}\x{1F1F9}](?:\x{1F1FB})|[\x{1F1E6}\x{1F1E8}\x{1F1EA}\x{1F1EC}\x{1F1ED}\x{1F1F1}\x{1F1F2}\x{1F1F3}\x{1F1F7}\x{1F1FB}](?:\x{1F1FA})|[\x{1F1E6}\x{1F1E7}\x{1F1EA}\x{1F1EC}\x{1F1ED}\x{1F1EE}\x{1F1F1}\x{1F1F2}\x{1F1F5}\x{1F1F8}\x{1F1F9}\x{1F1FE}](?:\x{1F1F9})|[\x{1F1E6}\x{1F1E7}\x{1F1EA}\x{1F1EC}\x{1F1EE}\x{1F1F1}\x{1F1F2}\x{1F1F5}\x{1F1F7}\x{1F1F8}\x{1F1FA}\x{1F1FC}](?:\x{1F1F8})|[\x{1F1E6}\x{1F1E7}\x{1F1E8}\x{1F1EA}\x{1F1EB}\x{1F1EC}\x{1F1ED}\x{1F1EE}\x{1F1F0}\x{1F1F1}\x{1F1F2}\x{1F1F3}\x{1F1F5}\x{1F1F8}\x{1F1F9}](?:\x{1F1F7})|[\x{1F1E6}\x{1F1E7}\x{1F1EC}\x{1F1EE}\x{1F1F2}](?:\x{1F1F6})|[\x{1F1E8}\x{1F1EC}\x{1F1EF}\x{1F1F0}\x{1F1F2}\x{1F1F3}](?:\x{1F1F5})|[\x{1F1E6}\x{1F1E7}\x{1F1E8}\x{1F1E9}\x{1F1EB}\x{1F1EE}\x{1F1EF}\x{1F1F2}\x{1F1F3}\x{1F1F7}\x{1F1F8}\x{1F1F9}](?:\x{1F1F4})|[\x{1F1E7}\x{1F1E8}\x{1F1EC}\x{1F1ED}\x{1F1EE}\x{1F1F0}\x{1F1F2}\x{1F1F5}\x{1F1F8}\x{1F1F9}\x{1F1FA}\x{1F1FB}](?:\x{1F1F3})|[\x{1F1E6}\x{1F1E7}\x{1F1E8}\x{1F1E9}\x{1F1EB}\x{1F1EC}\x{1F1ED}\x{1F1EE}\x{1F1EF}\x{1F1F0}\x{1F1F2}\x{1F1F4}\x{1F1F5}\x{1F1F8}\x{1F1F9}\x{1F1FA}\x{1F1FF}](?:\x{1F1F2})|[\x{1F1E6}\x{1F1E7}\x{1F1E8}\x{1F1EC}\x{1F1EE}\x{1F1F2}\x{1F1F3}\x{1F1F5}\x{1F1F8}\x{1F1F9}](?:\x{1F1F1})|[\x{1F1E8}\x{1F1E9}\x{1F1EB}\x{1F1ED}\x{1F1F1}\x{1F1F2}\x{1F1F5}\x{1F1F8}\x{1F1F9}\x{1F1FD}](?:\x{1F1F0})|[\x{1F1E7}\x{1F1E9}\x{1F1EB}\x{1F1F8}\x{1F1F9}](?:\x{1F1EF})|[\x{1F1E6}\x{1F1E7}\x{1F1E8}\x{1F1EB}\x{1F1EC}\x{1F1F0}\x{1F1F1}\x{1F1F3}\x{1F1F8}\x{1F1FB}](?:\x{1F1EE})|[\x{1F1E7}\x{1F1E8}\x{1F1EA}\x{1F1EC}\x{1F1F0}\x{1F1F2}\x{1F1F5}\x{1F1F8}\x{1F1F9}](?:\x{1F1ED})|[\x{1F1E6}\x{1F1E7}\x{1F1E8}\x{1F1E9}\x{1F1EA}\x{1F1EC}\x{1F1F0}\x{1F1F2}\x{1F1F3}\x{1F1F5}\x{1F1F8}\x{1F1F9}\x{1F1FA}\x{1F1FB}](?:\x{1F1EC})|[\x{1F1E6}\x{1F1E7}\x{1F1E8}\x{1F1EC}\x{1F1F2}\x{1F1F3}\x{1F1F5}\x{1F1F9}\x{1F1FC}](?:\x{1F1EB})|[\x{1F1E6}\x{1F1E7}\x{1F1E9}\x{1F1EA}\x{1F1EC}\x{1F1EE}\x{1F1EF}\x{1F1F0}\x{1F1F2}\x{1F1F3}\x{1F1F5}\x{1F1F7}\x{1F1F8}\x{1F1FB}\x{1F1FE}](?:\x{1F1EA})|[\x{1F1E6}\x{1F1E7}\x{1F1E8}\x{1F1EC}\x{1F1EE}\x{1F1F2}\x{1F1F8}\x{1F1F9}](?:\x{1F1E9})|[\x{1F1E6}\x{1F1E8}\x{1F1EA}\x{1F1EE}\x{1F1F1}\x{1F1F2}\x{1F1F3}\x{1F1F8}\x{1F1F9}\x{1F1FB}](?:\x{1F1E8})|[\x{1F1E7}\x{1F1EC}\x{1F1F1}\x{1F1F8}](?:\x{1F1E7})|[\x{1F1E7}\x{1F1E8}\x{1F1EA}\x{1F1EC}\x{1F1F1}\x{1F1F2}\x{1F1F3}\x{1F1F5}\x{1F1F6}\x{1F1F8}\x{1F1F9}\x{1F1FA}\x{1F1FB}\x{1F1FF}](?:\x{1F1E6})|[\x{00A9}\x{00AE}\x{203C}\x{2049}\x{2122}\x{2139}\x{2194}-\x{2199}\x{21A9}-\x{21AA}\x{231A}-\x{231B}\x{2328}\x{23CF}\x{23E9}-\x{23F3}\x{23F8}-\x{23FA}\x{24C2}\x{25AA}-\x{25AB}\x{25B6}\x{25C0}\x{25FB}-\x{25FE}\x{2600}-\x{2604}\x{260E}\x{2611}\x{2614}-\x{2615}\x{2618}\x{261D}\x{2620}\x{2622}-\x{2623}\x{2626}\x{262A}\x{262E}-\x{262F}\x{2638}-\x{263A}\x{2640}\x{2642}\x{2648}-\x{2653}\x{2660}\x{2663}\x{2665}-\x{2666}\x{2668}\x{267B}\x{267E}-\x{267F}\x{2692}-\x{2697}\x{2699}\x{269B}-\x{269C}\x{26A0}-\x{26A1}\x{26AA}-\x{26AB}\x{26B0}-\x{26B1}\x{26BD}-\x{26BE}\x{26C4}-\x{26C5}\x{26C8}\x{26CE}-\x{26CF}\x{26D1}\x{26D3}-\x{26D4}\x{26E9}-\x{26EA}\x{26F0}-\x{26F5}\x{26F7}-\x{26FA}\x{26FD}\x{2702}\x{2705}\x{2708}-\x{270D}\x{270F}\x{2712}\x{2714}\x{2716}\x{271D}\x{2721}\x{2728}\x{2733}-\x{2734}\x{2744}\x{2747}\x{274C}\x{274E}\x{2753}-\x{2755}\x{2757}\x{2763}-\x{2764}\x{2795}-\x{2797}\x{27A1}\x{27B0}\x{27BF}\x{2934}-\x{2935}\x{2B05}-\x{2B07}\x{2B1B}-\x{2B1C}\x{2B50}\x{2B55}\x{3030}\x{303D}\x{3297}\x{3299}\x{1F004}\x{1F0CF}\x{1F170}-\x{1F171}\x{1F17E}-\x{1F17F}\x{1F18E}\x{1F191}-\x{1F19A}\x{1F201}-\x{1F202}\x{1F21A}\x{1F22F}\x{1F232}-\x{1F23A}\x{1F250}-\x{1F251}\x{1F300}-\x{1F321}\x{1F324}-\x{1F393}\x{1F396}-\x{1F397}\x{1F399}-\x{1F39B}\x{1F39E}-\x{1F3F0}\x{1F3F3}-\x{1F3F5}\x{1F3F7}-\x{1F3FA}\x{1F400}-\x{1F4FD}\x{1F4FF}-\x{1F53D}\x{1F549}-\x{1F54E}\x{1F550}-\x{1F567}\x{1F56F}-\x{1F570}\x{1F573}-\x{1F57A}\x{1F587}\x{1F58A}-\x{1F58D}\x{1F590}\x{1F595}-\x{1F596}\x{1F5A4}-\x{1F5A5}\x{1F5A8}\x{1F5B1}-\x{1F5B2}\x{1F5BC}\x{1F5C2}-\x{1F5C4}\x{1F5D1}-\x{1F5D3}\x{1F5DC}-\x{1F5DE}\x{1F5E1}\x{1F5E3}\x{1F5E8}\x{1F5EF}\x{1F5F3}\x{1F5FA}-\x{1F64F}\x{1F680}-\x{1F6C5}\x{1F6CB}-\x{1F6D2}\x{1F6E0}-\x{1F6E5}\x{1F6E9}\x{1F6EB}-\x{1F6EC}\x{1F6F0}\x{1F6F3}-\x{1F6F9}\x{1F910}-\x{1F93A}\x{1F93C}-\x{1F93E}\x{1F940}-\x{1F945}\x{1F947}-\x{1F970}\x{1F973}-\x{1F976}\x{1F97A}\x{1F97C}-\x{1F9A2}\x{1F9B0}-\x{1F9B9}\x{1F9C0}-\x{1F9C2}\x{1F9D0}-\x{1F9FF}]/u', '', $text);
	}

	
	public function insertebproducts($shopifyStore,$ebayAccount,$item_id,$ebayItem){
		Log::channel('importlistings')->info(" item is not relisted and not  in db so we would  add it " . $item_id);
		if (!isset($ebayItem["SKU"]) || !$ebayItem["SKU"]) $ebayItem["SKU"] = "eb_" . mt_rand(10, 999) . "_" . uniqid();
		$sku = $ebayItem["SKU"];
		if (!$sku) $sku = "eb_" . $item_id;
		$listing_title = $ebayItem["Title"];
		$images = (isset($ebayItem["PictureDetails"]["PictureURL"])) ? $ebayItem["PictureDetails"]["PictureURL"] : array();
		if (!$images && isset($ebayItem["Variations"]) && $ebayItem["Variations"] && isset($ebayItem["Variations"]["Pictures"]) && $ebayItem["Variations"]["Pictures"]) {
			$images = $ebayItem["Variations"]["Pictures"][0]["VariationSpecificPictureSet"][0]["PictureURL"];
		}
		$listingData = array();
		// 		$listingData["title"] = mb_convert_encoding($listing_title, 'ISO-8859-1', 'utf-8'); by hiteshmali
     $listingData["title"] = $this->remove_emoji($listing_title); // by hiteshmali
		$listingData["image"] = ($images) ? $images[0] : null;
		$listingData["status"] = "published";
		$listingData["ebay_item_id"] = $item_id;
		$listingData["sku"] = $sku;
		$listingData["listing_data"] = json_encode($ebayItem);
		$listingData["listing_url"] = "https://www.ebay.com/itm/" . $item_id;
		$listingData["account_id"] = $ebayAccount->id;
		$listingData["store_id"] = $shopifyStore->id;
		$listingData["user_id"] = $shopifyStore->user_id;
		$listing = $shopifyStore->listings()->create($listingData);
		//$listing_id = $listing->id;
		$variations = (isset($ebayItem["Variations"]) && isset($ebayItem["Variations"]["Variation"])) ? $ebayItem["Variations"]["Variation"] : array();
		$options = array();
		if ($variations) {
			$nameValueList = $variations[0]["VariationSpecifics"][0]["NameValueList"];
			foreach ($nameValueList as $nameValue) {
				if ($nameValue["Value"]) $options[] = $nameValue["Name"];
			}
			$skuvarc = 1;
			foreach ($variations as $variation) {
				$pvsku = $sku . "_" . $skuvarc;
				if (isset($variation["SKU"]) && $variation["SKU"]) $pvsku = $variation["SKU"];
				$optionsvalue = array();
				$nameValueList = $variation["VariationSpecifics"][0]["NameValueList"];
				foreach ($nameValueList as $nameValue) $optionsvalue[] = $nameValue["Value"][0];
				$vimage = null;
				if (isset($ebayItem["Variations"]["Pictures"]) && $ebayItem["Variations"]["Pictures"]) {
					$variationSpecificName = $ebayItem["Variations"]["Pictures"][0]["VariationSpecificName"];
					foreach ($ebayItem["Variations"]["Pictures"][0]["VariationSpecificPictureSet"] as $picture) {
						foreach ($nameValueList as $nameValue) {
							if ($nameValue["Name"] == $variationSpecificName && $picture["VariationSpecificValue"] == $nameValue["Value"][0]) {
								$vimage = $picture["PictureURL"][0];
								break;
							}
						}
						if ($vimage) break;
					}
				}
				$variant_title = implode(" ", $optionsvalue);
				$variantData = array();
				$variantData["title"] = mb_convert_encoding($variant_title, 'ISO-8859-1', 'utf-8');
				$variantData["ebay_item_id"] = $item_id;
				$variantData["sku"] = $pvsku;
				$variantData["image"] = $vimage;
				$variantData["listing_variant_data"] = json_encode($variation);
				$variantData["ebay_item_data"] = json_encode($ebayItem);
				$variantData["listing_id"] = $listing->id;
				$variantData["account_id"] = $ebayAccount->id;
				$variantData["store_id"] = $shopifyStore->id;
				$variantData["user_id"] = $shopifyStore->user_id;
				$lvariant = $listing->variants()->create($variantData);
			}
		} else {
			$variant_title = "Default Variant";
			$variantData = array();
			$variantData["title"] = mb_convert_encoding($variant_title, 'ISO-8859-1', 'utf-8');
			$variantData["ebay_item_id"] = $item_id;
			$variantData["sku"] = $sku;
			$variantData["image"] = null;
			$variantData["listing_variant_data"] = json_encode($ebayItem);
			$variantData["ebay_item_data"] = json_encode($ebayItem);
			$variantData["listing_id"] = $listing->id;
			$variantData["account_id"] = $ebayAccount->id;
			$variantData["store_id"] = $shopifyStore->id;
			$variantData["user_id"] = $shopifyStore->user_id;
			$lvariant = $listing->variants()->create($variantData);
		}
		Log::channel('importlistings')->info("item is saved in db now ->" . $item_id);
	}
	
	

				  
	public function ProcessRelisteditem($site_id,$ebay_token,$relistParentID,$item_id,$shopify_store_id,$res){
	   
        Log::channel('importlistings')->info(" enter in ProcessRelisteditem item_id ".$item_id);
        Log::channel('importlistings')->info(" enter in ProcessRelisteditem relistParentID ".$relistParentID);
        Log::channel('importlistings')->info(" enter in ProcessRelisteditem ");
        
		$ebay_environment = config('ebay.environment');

		$ebayCredentials = array(
			'credentials' => [
				'devId' => config('ebay.' . $ebay_environment . 'devid'),
				'appId' => config('ebay.' . $ebay_environment . 'appid'),
				'certId' => config('ebay.' . $ebay_environment . 'certid'),
			],
			'authToken' => '',
			'oauthUserToken' => '',
			'ruName' => config('ebay.' . $ebay_environment . 'RuName')
		);
		
		$ebayService = new Services\TradingService([
			'credentials' => $ebayCredentials['credentials'],
			'sandbox' => ($ebay_environment == "sandbox") ? true : false,
			'siteId' => $site_id
		]);

        $ebConfig = array('production' => 
          array('credentials' => array(
         'devId' =>  config('ebay.' . $ebay_environment . 'devid'),
         'appId' => config('ebay.' . $ebay_environment . 'appid'),
         'certId' =>config('ebay.' . $ebay_environment . 'certid')),
        ));


        $service = new Services\TradingService([
            'credentials' => $ebConfig['production']['credentials'],
            'sandbox'     => false,
            'siteId'      => $site_id
	    ]);	

		    
		$ebayItemRequest = new Types\GetItemRequestType();
		$ebayItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
		$ebayItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
		$ebayItemRequest->ItemID = $relistParentID;
		$ebayItemRequest->IncludeItemSpecifics = true;

		sleep(2);
		$ebayItemResponse = $ebayService->getItem($ebayItemRequest);
		
		Log::channel('importlistings')->info(" enter in ProcessRelisteditem ".$ebayItemResponse);
												
		    $ebayItemResponse = $ebayItemResponse->toArray();
		    
		    Log::channel('importlistings')->info(" enter in ProcessRelisteditem in array ".$ebayItemResponse);
		    
			if (isset($ebayItemResponse["Item"]) && $ebayItemResponse["Item"]) {
			    
				$ebayItem = $ebayItemResponse["Item"];

				$relistedItemID = (isset($ebayItem["ListingDetails"]["RelistedItemID"])) ? (string) $ebayItem["ListingDetails"]["RelistedItemID"] : "";
				
			//	$shopifyStore = ShopifyStore::where('status',"active")->whereIn("id",$shopify_store_id)->get();
				$shopifyStore = ShopifyStore::where('status',"active")->where("id",$shopify_store_id)->get();
				$shopify_store_id = $shopifyStore->id;
				$store_database_name = config('config.store_db_prefix').$shopify_store_id;
				AppHelper::setConnection($store_database_name,$shopifyStore);
				$listing = $shopifyStore->listings()->with('variants')->where('ebay_item_id', $relistParentID)->first();
                Log::channel('importlistings')->info(" enter in ProcessRelisteditem listing ".$listing);
				if ($relistedItemID == $item_id) {
					// $shopifyStore->listing()->update(['ebay_item_id' => $item_id])->where('product_id', $productId);

					$listing->ebay_item_id = $item_id;
					$listing->save();
					$listingVariants = $listing->variants;
					if ($listingVariants->count() > 0) {
						foreach ($listingVariants as $listingVariant) {
							$listingVariant->ebay_item_id = $item_id;
							$listingVariant->save();
						}
					}
					 Log::info("item is relisted ans data updated in db ".$item_id );
				}
			}

		return  "success";
	}
	
	public function ProcessCreateEbayItem($site_id,$ebay_token,$item_id,$shopify_store_id,$ebayItem,$ebayAccountid){
		
		$shopifyStore = ShopifyStore::where('status',"active")->whereIn("id",$shopify_store_id)->get();
		$shopify_store_id = $shopifyStore->id;
		$store_database_name = config('config.store_db_prefix').$shopify_store_id;
		AppHelper::setConnection($store_database_name,$shopifyStore);
		
		$listing = $shopifyStore->listings()->where('ebay_item_id', $item_id)->first();
		
		if ($listing) {
			Log::info(" item is not relisted and found in db ".$item_id );
			return  "item is not relisted and found in db";
	   }else{
			 if (!isset($ebayItem["SKU"]) || !$ebayItem["SKU"])
			 $ebayItem["SKU"] = "eb_" . mt_rand(10, 999) . "_" . uniqid();

			 $sku = $ebayItem["SKU"];
			 if (!$sku)
				 $sku = "eb_" . $item_id;

			 $listing_title = $ebayItem["Title"];

			 $images = (isset($ebayItem["PictureDetails"]["PictureURL"])) ? $ebayItem["PictureDetails"]["PictureURL"] : array();

			 if (!$images && isset($ebayItem["Variations"]) && $ebayItem["Variations"] && isset($ebayItem["Variations"]["Pictures"]) && $ebayItem["Variations"]["Pictures"]) {
				 $images = $ebayItem["Variations"]["Pictures"][0]["VariationSpecificPictureSet"][0]["PictureURL"];
			 }

			 $listingData = array();
			 $listingData["title"] = mb_convert_encoding($listing_title, 'ISO-8859-1', 'utf-8');
			 $listingData["image"] = ($images) ? $images[0] : null;
			 $listingData["status"] = "published";
			 $listingData["ebay_item_id"] = $item_id;
			 $listingData["sku"] = $sku;
			 $listingData["listing_data"] = json_encode($ebayItem);
			 $listingData["listing_url"] = "https://www.ebay.com/itm/" . $item_id;
			 $listingData["account_id"] = $ebayAccountid;
			 $listingData["store_id"] = $shopifyStore->id;
			 $listingData["user_id"] = $shopifyStore->user_id;

			 $listing = $shopifyStore->listings()->create($listingData);

			 //$listing_id = $listing->id;

			 $variations = (isset($ebayItem["Variations"]) && isset($ebayItem["Variations"]["Variation"])) ? $ebayItem["Variations"]["Variation"] : array();


			 $options = array();
			 if ($variations) {
				 $nameValueList = $variations[0]["VariationSpecifics"][0]["NameValueList"];
				 foreach ($nameValueList as $nameValue) {
					 if ($nameValue["Value"])
						 $options[] = $nameValue["Name"];
				 }
				 $skuvarc = 1;
				 foreach ($variations as $variation) {
					 $pvsku = $sku . "_" . $skuvarc;
					 if (isset($variation["SKU"]) && $variation["SKU"])
						 $pvsku = $variation["SKU"];

					 $optionsvalue = array();
					 $nameValueList = $variation["VariationSpecifics"][0]["NameValueList"];
					 foreach ($nameValueList as $nameValue)
						 $optionsvalue[] = $nameValue["Value"][0];
					 $vimage = null;

					 if (isset($ebayItem["Variations"]["Pictures"]) && $ebayItem["Variations"]["Pictures"]) {
						 $variationSpecificName = $ebayItem["Variations"]["Pictures"][0]["VariationSpecificName"];
						 foreach ($ebayItem["Variations"]["Pictures"][0]["VariationSpecificPictureSet"] as $picture) {

							 foreach ($nameValueList as $nameValue) {
								 if ($nameValue["Name"] == $variationSpecificName && $picture["VariationSpecificValue"] == $nameValue["Value"][0]) {
									 $vimage = $picture["PictureURL"][0];
									 break;
								 }
							 }
							 if ($vimage)
								 break;
						 }
					 }

					 $variant_title = implode(" ", $optionsvalue);
					 $variantData = array();
					 $variantData["title"] = mb_convert_encoding($variant_title, 'ISO-8859-1', 'utf-8');
					 $variantData["ebay_item_id"] = $item_id;
					 $variantData["sku"] = $pvsku;
					 $variantData["image"] = $vimage;
					 $variantData["listing_variant_data"] = json_encode($variation);
					 $variantData["ebay_item_data"] = json_encode($ebayItem);
					 $variantData["listing_id"] = $listing->id;
					 $variantData["account_id"] = $ebayAccountid;
					 $variantData["store_id"] = $shopifyStore->id;
					 $variantData["user_id"] = $shopifyStore->user_id;
					 $lvariant = $listing->variants()->create($variantData);
				 }
			 } else {
				 $variant_title = "Default Variant";
				 $variantData = array();
				 $variantData["title"] = mb_convert_encoding($variant_title, 'ISO-8859-1', 'utf-8');
				 $variantData["ebay_item_id"] = $item_id;
				 $variantData["sku"] = $sku;
				 $variantData["image"] = null;
				 $variantData["listing_variant_data"] = json_encode($ebayItem);
				 $variantData["ebay_item_data"] = json_encode($ebayItem);
				 $variantData["listing_id"] = $listing->id;
				 $variantData["account_id"] = $ebayAccountid;
				 $variantData["store_id"] = $shopifyStore->id;
				 $variantData["user_id"] = $shopifyStore->user_id;
				 $lvariant = $listing->variants()->create($variantData);
			 }
			 Log::info(" item is saved in db now ".$item_id );
		 
			 return  "success";
	   	}	
	}

    
	public function addUpdateEbayItem($pendingPublish,$ebayAccount,$shopifyStore,$ebayService = null){
         
	    Log::info("Entered in add updated ebay item");
	    // Log::info($shopifyStore);
		try{
			$ebay_environment = config('ebay.environment');

			if($shopifyStore->user_id == 2) $ebay_environment = "sandbox";

			$ebayCredentials = array(
				'credentials' => [
					'devId' => config('ebay.'.$ebay_environment.'devid'),
					'appId' => config('ebay.'.$ebay_environment.'appid'),
					'certId' => config('ebay.'.$ebay_environment.'certid'),
				],
				'authToken' => '',
				'oauthUserToken' => '',
				'ruName' => config('ebay.'.$ebay_environment.'RuName')
			);
			$ebay_token = $ebayAccount->access_token;
			$site_id = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;

			if(!$ebayService){
				$ebayService = new Services\TradingService([
					'credentials' => $ebayCredentials['credentials'],
					'sandbox' => ($ebay_environment == "sandbox" ) ? true : false,
					'siteId' => $site_id
				]);
			}
            
            Log::info("fetching product details from products table for product table ".$pendingPublish->product_id);
            
			$product = $shopifyStore->products()->with('variants')->with('productData')->find($pendingPublish->product_id);
			
			$profile = $shopifyStore->profiles()->with('template')->with('returnProfile')->with('shippingProfile')->with('paymentProfile')->with('storeCategory')->with('category1')->with('category2')->find($pendingPublish->profile_id);
			if($product && $profile && $profile->category1){
			     Log::info("product details and profile details found from db for product id ".$pendingPublish->product_id);
            //  Log::info($profile->shippingProfile);
				$productData = [];
				if($product->productData->count() > 0){
					foreach($product->productData as $proData){
						if($proData->profile_id == $profile->id){
							$productData = $proData;
							break ;
						}
					}
					if(!$productData){
						foreach($product->productData as $proData){
							if(!$proData->profile_id){
								$productData = $proData;
								break;
							}
						}
					}
					if($productData) $productData->item_specific_values = json_decode($productData->item_specific_values);
				}

				$listing = [];
				
				 Log::info("finding product in listing for listing id  ".$product->listing_id);
				  
				if($product->listing_id) $listing = $shopifyStore->listings()->with('variants')->find($product->listing_id);

				$shProduct = json_decode($product->shopify_product_data,true);

				
				$option1name = (isset($shProduct["options"][0]["name"])) ? strtolower($shProduct["options"][0]["name"]) : NULL;
				$option2name = (isset($shProduct["options"][1]["name"])) ? strtolower($shProduct["options"][1]["name"]) : NULL;
				$option3name = (isset($shProduct["options"][2]["name"])) ? strtolower($shProduct["options"][2]["name"]) : NULL;


				$option1name_l = strtolower($option1name);
				$option2name_l = strtolower($option2name);
				$option3name_l = strtolower($option3name);

				$tags = $shProduct["tags"];
				$variants = $product->variants;
				$shVariants = $shProduct["variants"];

				$listing_format = $profile->listing_format;

				$ebayRequest = ($listing_format == "auction") ? new Types\AddItemRequestType() : new Types\AddFixedPriceItemRequestType();
				if($listing) $ebayRequest = ($listing_format == "auction") ? new Types\ReviseItemRequestType() : new Types\ReviseFixedPriceItemRequestType();

				$ebayRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
				$ebayRequest->RequesterCredentials->eBayAuthToken = $ebay_token;


				$ebayItem = new Types\ItemType();
               $ebayItem = $this->getEbayItem($listing, $profile, $shProduct, $productData, $listing_format,$ebayItem);
                $listing_title = $ebayItem->Title;


				//$ebayCategory1 = EbayCategory::where("category_id",$ebayData->ebay_category_1)->first();
				//$ebayCategory2 = EbayCategory::where("category_id",$ebayData->ebay_category_2)->first();

                 $ebayItem = $this->getEbayategory($listing, $profile, $shProduct, $productData, $ebayItem, $site_id, $shopifyStore);


			
				$item_specifics = ($profile->item_specifics) ? json_decode($profile->item_specifics,true) : null;

				$vendor = $shProduct["vendor"];
				$manuf_part_no = ($variants[0]->sku) ? $variants[0]->sku : $shVariants[0]["sku"];
               Log::info("variant info for [0]".json_encode($variants[0]->shopify_variant_id,true));
               Log::info("SHvariant info for [0]".json_encode($shVariants[0],true));
				if($productData && $productData->item_specific_values){
					if(isset($productData->item_specific_values->brand) && $productData->item_specific_values->brand){
						$vendor = $productData->item_specific_values->brand;
					}

					if(isset($productData->item_specific_values->mpn) && $productData->item_specific_values->mpn){
						$manuf_part_no = $productData->item_specific_values->mpn;
					}
				}

				
				if($vendor || $manuf_part_no || $item_specifics){
					$itemSpecificsSet = new Types\NameValueListArrayType();

					// if($vendor){
					// 	$itemSpecificNameValue = new Types\NameValueListType();
					// 	$itemSpecificNameValue->Name = 'Brand';
					// 	$itemSpecificNameValue->Value = array($vendor);
					// 	$itemSpecificsSet->NameValueList[] = $itemSpecificNameValue;
					// }

					if($manuf_part_no){
						$itemSpecificNameValue = new Types\NameValueListType();
						$itemSpecificNameValue->Name = 'MPN';
						$itemSpecificNameValue->Value = array($manuf_part_no);
						$itemSpecificsSet->NameValueList[] = $itemSpecificNameValue;
					}

					if ($item_specifics) {
						foreach ($item_specifics as $item_specific_key => $item_specific_value) {
							$item_specific_key_l = strtolower($item_specific_key);
							if ($item_specific_key_l == $option1name_l || $item_specific_key_l == $option2name_l || $item_specific_key_l == $option3name_l) continue;
							//TODO:If brand is already has been taken we need to skip it here if $item_specific_key_l == brand
							$item_specific_value = trim($item_specific_value);
							if ($item_specific_value !== "") {

								if (isset($vendor['item_specific_values']) && isset($vendor['item_specific_values']['brand'])) {
									$item_specific_value = $vendor['item_specific_values']['brand'];
									$itemSpecificNameValue = new Types\NameValueListType();
									$itemSpecificNameValue->Name = 'Brand';
									$itemSpecificNameValue->Value = array($item_specific_value);
									$itemSpecificsSet->NameValueList[] = $itemSpecificNameValue;
								} else {
									// Fetch data from profile table
									$itemSpecificNameValue = new Types\NameValueListType();
									$itemSpecificNameValue->Name = $item_specific_key;
									$itemSpecificNameValue->Value = array($item_specific_value);
									$itemSpecificsSet->NameValueList[] = $itemSpecificNameValue;
								}								

							}
						}
					}

                    Log::info("add updated method item specific".$itemSpecificsSet);
					$ebayItem->ItemSpecifics = $itemSpecificsSet;
				}


				$ebayImagesMappings = array();
				
				$extraImages = array();
				$hasVariantImages = false;
				$addedVariantImages = array();

				$listdetailsadded = false;

				$skipImages = [];
                Log::info("code is running on the line1725 in add updated method");
                
                $option1Name = $option1name;
					$option2Name = $option2name;
					$option3Name = $option3name;
				if($option1name && (count($shVariants) > 1 || $shVariants[0]["option1"] != "Default Title") && $shVariants[0]["option1"] && $listing_format != "auction"){

					$ebayItem->Variations = new Types\VariationsType();
					$option1Name = $option1name;
					$option1Values = array();

					$option2Name = $option2name;
					$option2Values = array();

					$option3Name = $option3name;
					$option3Values = array();
					
                     Log::info("code is running on the line 1737 in add updated method");
                     
					foreach($shVariants as $shVariant){
						$pvariant = [];
						foreach($variants as $variant){
							if($variant->shopify_variant_id == $shVariant["id"]){
								$pvariant = $variant;
								break;
							}
						}

						if(!$pvariant) continue;

						if($shVariant["option1"] && !in_array($shVariant["option1"],$option1Values)){
							$option1Values[] = $shVariant["option1"];
						}
						if($shVariant["option2"] && !in_array($shVariant["option2"],$option2Values)){
							$option2Values[] = $shVariant["option2"];
						}
						if($shVariant["option3"] && !in_array($shVariant["option3"],$option3Values)){
							$option3Values[] = $shVariant["option3"];
						}
					}
					$variationSpecificsSet = new Types\NameValueListArrayType();
                         Log::info("code is running on the line 1760 in add updated method");
					$optionNameValue = new Types\NameValueListType();
					$optionNameValue->Name = $option1Name;
					$optionNameValue->Value = $option1Values;
					$variationSpecificsSet->NameValueList[] = $optionNameValue;

					if($option2Name && $option2Values){
						$optionNameValue = new Types\NameValueListType();
						$optionNameValue->Name = $option2Name;
						$optionNameValue->Value = $option2Values;
						$variationSpecificsSet->NameValueList[] = $optionNameValue;

						if($option3Name && $option3Values){
							$optionNameValue = new Types\NameValueListType();
							$optionNameValue->Name = $option3Name;
							$optionNameValue->Value = $option3Values;
							$variationSpecificsSet->NameValueList[] = $optionNameValue;
						}
					}
					$ebayItem->Variations->VariationSpecificsSet = $variationSpecificsSet;
                  
                   Log::info("add updated method  vart  item specific".$variationSpecificsSet);
					$voptionname = $option1Name;
					if(strtolower($option2Name) == "color" || strtolower($option2Name) == "colour") $voptionname = $option2Name;
					else if(strtolower($option3Name) == "color" || strtolower($option3Name) == "colour") $voptionname = $option3Name;

					$imageOptions = [];

					foreach($shVariants as $shVariant){
                    Log::info("pvariant info for ->".json_encode($shVariant,true));
						$pvariant = [];
						foreach($variants as $variant){
							if($variant->shopify_variant_id == $shVariant["id"]){
								$pvariant = $variant;
								break;
							}
						}

						if(!$pvariant) continue;


						$itemVariation = new Types\VariationType();
			    	// 		$itemVariation->SKU = $pvariant->sku;
			        	Log::info("sku is shopify variant id and that is-> ".$pvariant->shopify_variant_id);
						$itemVariation->SKU = strval($pvariant->shopify_variant_id);
                        
                 $itemVariation = $this->priceandquntity($pvariant, $ebayAccount, $shopifyStore, $itemVariation);
                 
                     Log::info("code is running on the line 1845");
						if($profile->product_id_type && $pvariant->product_id_val && $ebay_environment != "sandbox"){
							$itemVariation->VariationProductListingDetails = new Types\VariationProductListingDetailsType();
							if($profile->product_id_type == "ISBN"){
								$itemVariation->VariationProductListingDetails->ISBN = $pvariant->product_id_val;
								
							}
							else if($profile->product_id_type == "UPC"){
							     Log::info("product_id_type is upc ");
							    if($shopifyStore->user_id == 1013 || $shopifyStore->user_id == 1402  ||  $shopifyStore->user_id == 1555   || $shopifyStore->user_id == 1444  || $shopifyStore->user_id == 1468 || $shopifyStore->user_id == 1469 ){
							         $itemVariation->VariationProductListingDetails->UPC = "";
							    }else{
							  $itemVariation->VariationProductListingDetails->UPC = $pvariant->product_id_val;
							    }
							
							}
							else if($profile->product_id_type == "EAN"){
							     Log::info("product_id_type is EAN ");
								$itemVariation->VariationProductListingDetails->EAN = $pvariant->product_id_val;
								 Log::info("product_id_type is the EAN ".$pvariant->product_id_val);
							}
							else if($profile->product_id_type == "MPN" && $vendor){
							     Log::info("product_id_type is the MPN ".$pvariant->product_id_val);
								$brandMPN = new Types\BrandMPNType();
								$brandMPN->Brand = $vendor;
								$brandMPN->MPN = $pvariant->product_id_val;
								$itemVariation->VariationProductListingDetails->BrandMPN = $brandMPN;
							}
						}

						
						$variationSpecifics = new Types\NameValueListArrayType();
						
						$optionNameValue = new Types\NameValueListType();
						$optionNameValue->Name = $option1Name;
						$optionNameValue->Value = [$shVariant["option1"]];
						$variationSpecifics->NameValueList[] = $optionNameValue;

						if($shVariant["option2"] && $option2Name){
							$optionNameValue = new Types\NameValueListType();
							$optionNameValue->Name = $option2Name;
							$optionNameValue->Value = [$shVariant["option2"]];
							$variationSpecifics->NameValueList[] = $optionNameValue;

							if($shVariant["option3"] && $option3Name){
								$optionNameValue = new Types\NameValueListType();
								$optionNameValue->Name = $option3Name;
								$optionNameValue->Value = [$shVariant["option3"]];
								$variationSpecifics->NameValueList[] = $optionNameValue;
							}
						}
						$itemVariation->VariationSpecifics[] = $variationSpecifics;
						$ebayItem->Variations->Variation[] = $itemVariation;


						if($pvariant->image){							
							$voption = $shVariant["option1"];
							if($shVariant["option2"] && (strtolower($option2Name) == "color" || strtolower($option2Name) == "colour")){
								$voption = $shVariant["option2"];
							}
							else if($shVariant["option3"] && (strtolower($option3Name) == "color" || strtolower($option3Name) == "colour")){
								$voption = $shVariant["option3"];
							}

							$opfound = false;
							foreach($imageOptions as $imageOption){
								if($imageOption["value"] == $voption){
									$opfound = true;
									break;
								}
							}
							if(!$opfound){
								$imageOptions[] = ["value" => $voption, "image" => $pvariant->image];
								$skipImages[] = $pvariant->image;
							}
						}
					}
					
					if($voptionname && $imageOptions){
						$pictures = new Types\PicturesType();
						$pictures->VariationSpecificName = $voptionname;
						foreach($imageOptions as $imageOption){
							$pictureSet = new Types\VariationSpecificPictureSetType();
							$pictureSet->VariationSpecificValue = $imageOption["value"];
							$pictureSet->PictureURL[] = $imageOption["image"];
							$pictures->VariationSpecificPictureSet[] = $pictureSet;
						}
						$ebayItem->Variations->Pictures[] = $pictures;
					}					
				}
				else{
                    Log::info("product is single variant ");
                    
					$pvariant = $variants[0];

                    $ebayItem = $this->priceandquntity($pvariant, $ebayAccount, $shopifyStore, $ebayItem);


					if ($shopifyStore->id == 1582) {
						log::info(" shopify store id is 1582s setting time ");
						$ebayItem->ScheduleTime = new \DateTime('2024-06-20T10:00:00');

						//$item->ScheduleTime = new \DateTime('2024-06-20T10:00:00'); 
					}

					 Log::info("sku is shopify variant id in single variant for->".$pvariant->shopify_variant_id);
					$ebayItem->SKU = strval($pvariant->shopify_variant_id);

					if(isset($item_specifics["buy_it_now_price"]) && $item_specifics["buy_it_now_price"] > 0){
						$ebayItem->BuyItNowPrice = new Types\AmountType(['value' => $item_specifics["buy_it_now_price"]]);	
					}

					if($profile->product_id_type && $pvariant->product_id_val && $ebay_environment != "sandbox"){
						$listdetailsadded = true;
						$ebayItem->ProductListingDetails = new Types\ProductListingDetailsType();
						if($profile->product_id_type == "ISBN"){
							$ebayItem->ProductListingDetails->ISBN = $pvariant->product_id_val;
							 Log::info("product_id_type is the ISBN ".$pvariant->product_id_val);
						}
						else if($profile->product_id_type == "UPC"){
						
						 if($shopifyStore->user_id == 1013 || $shopifyStore->user_id == 1402  ||  $shopifyStore->user_id == 1555  ||  $shopifyStore->user_id == 1444 || $shopifyStore->user_id == 1468 || $shopifyStore->user_id == 1469 ){
							     	$ebayItem->ProductListingDetails->UPC = "";
							    }else{
							 	$ebayItem->ProductListingDetails->UPC = $pvariant->product_id_val;
							    }
						
								 Log::info("product_id_type is the UPC ".$pvariant->product_id_val);
							
						}
						else if($profile->product_id_type == "EAN"){
							$ebayItem->ProductListingDetails->EAN = $pvariant->product_id_val;
							 Log::info("product_id_type is the EAN ".$pvariant->product_id_val);
						}
						else if($profile->product_id_type == "MPN" && $vendor){
						     Log::info("product_id_type is the MPN ".$pvariant->product_id_val);
							$brandMPN = new Types\BrandMPNType();
							$brandMPN->Brand = $vendor;
							$brandMPN->MPN = $pvariant->product_id_val;
							$ebayItem->ProductListingDetails->BrandMPN = $brandMPN;
						}
					}
				}
               Log::info("code is running on the line 1994");
				if($profile->product_id_type != "MPN" && $vendor && $manuf_part_no && $ebay_environment != "sandbox"){
					if(!$listdetailsadded) $ebayItem->ProductListingDetails = new Types\ProductListingDetailsType();
					$brandMPN = new Types\BrandMPNType();
					$brandMPN->Brand = $vendor;
					$brandMPN->MPN = $manuf_part_no;
					$ebayItem->ProductListingDetails->BrandMPN = $brandMPN;
				}
                 if($shopifyStore->user_id == 8) {
                      $ebayItem->PictureDetails = new Types\PictureDetailsType();
					$ebayItem->PictureDetails->GalleryType = Enums\GalleryTypeCodeType::C_GALLERY;
					$imagesUrl = array();
					foreach($shProduct["images"] as $image){
						if($skipImages && in_array($image["src"],$skipImages)) continue;


                        $imageUrl = $image["src"];

                         $ch = curl_init($imageUrl);
                        $dirname = public_path($shopifyStore->user_id);
                        
                          
                           if(is_dir($dirname)) {
                           }
                           else{
                               $dir =  mkdir($dirname); 
                           }
                           $u_id = $shopifyStore->user_id;
                           $mid = $image["id"];
                          $filename = public_path('/'.$u_id.'/'.$mid.'.jpg');

                         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                           $imageData = curl_exec($ch);
                              curl_close($ch);

                        file_put_contents($filename, $imageData);
                        Log::info("image url ".$filename);
						$imagesUrl[] = url($filename);
						if(count($imagesUrl) >= 12) break;
					}
					$ebayItem->PictureDetails->PictureURL = $imagesUrl;
                 }
                 else{

					if ($shProduct["image"] === null || $shProduct["image"] === "") {
						// If null, assign default image
						$shProduct["images"] = array("https://app1.ecomshore.com/service/public/image/default_image.png"); // Replace "default.jpg" with your default image path
						
						if($shProduct["images"] && $shProduct["images"]){
							$ebayItem->PictureDetails = new Types\PictureDetailsType();
							$ebayItem->PictureDetails->GalleryType = Enums\GalleryTypeCodeType::C_GALLERY;
							$imagesUrl = array();
	
							foreach($shProduct["images"] as $image){
								if($skipImages && in_array($image["src"],$skipImages)) continue;
								$imagesUrl[] = $image;
							}
							$ebayItem->PictureDetails->PictureURL = $imagesUrl;
						}
					} else {

						if($shProduct["images"] && $shProduct["images"]){
							$ebayItem->PictureDetails = new Types\PictureDetailsType();
							$ebayItem->PictureDetails->GalleryType = Enums\GalleryTypeCodeType::C_GALLERY;
							$imagesUrl = array();
	
							foreach($shProduct["images"] as $image){
								if($skipImages && in_array($image["src"],$skipImages)) continue;
								$imagesUrl[] = $image["src"];
							}
							$ebayItem->PictureDetails->PictureURL = $imagesUrl;
						}

					}

					// if($shProduct["images"] && $shProduct["images"]){
					// 	$ebayItem->PictureDetails = new Types\PictureDetailsType();
					// 	$ebayItem->PictureDetails->GalleryType = Enums\GalleryTypeCodeType::C_GALLERY;
					// 	$imagesUrl = array();

					// 	foreach($shProduct["images"] as $image){
					// 		if($skipImages && in_array($image["src"],$skipImages)) continue;
					// 		$imagesUrl[] = $image["src"];
					// 	}
					// 	$ebayItem->PictureDetails->PictureURL = $imagesUrl;
					// }

				}
				Log::info("code is running on the line 2048");
				$paymentProfile = null;
				$shippingProfile = null;
				$returnProfile = null;
				Log::info("here is profile".json_encode($profile));
				if($profile->paymentProfile){
					$paymentProfile = new Types\SellerPaymentProfileType();
					$paymentProfile->PaymentProfileID = (int) $profile->paymentProfile->seller_profile_id;
					Log::info("payment profile is here for the current user".	$paymentProfile->PaymentProfileID );
				}
               Log::info("code is running on the line 2056");
				if($profile->shippingProfile){
					$shippingProfile = new Types\SellerShippingProfileType();
					$shippingProfile->ShippingProfileID = (int) $profile->shippingProfile->seller_profile_id;
					
					 Log::info("shipping profile is here for the current user".	$shippingProfile->ShippingProfileID);
					
				}
            Log::info("code is running on the line 2064");
				if($profile->returnProfile){
					$returnProfile = new Types\SellerReturnProfileType();
					$returnProfile->ReturnProfileID = (int) $profile->returnProfile->seller_profile_id;
					Log::info("return profile is here for the current user".	$returnProfile->ReturnProfileID );
				}
		Log::info("publish for 1296666".$shVariants[0]["grams"]);
		
		if($shopifyStore->id == 1296 || $shopifyStore->id == 1460 ) {
	                	$packageDetails = new Types\ShipPackageDetailsType();
				 		//	$packageDetails->ShippingPackage = 'PackageThickEnvelope';
				 		//	$packageDetails->MeasurementUnit = Enums\MeasurementSystemCodeType::C_ENGLISH;
				 		//	$packageDetails->ShippingIrregular = true;
				 		
                       Log::info("entered in weight unit for shopifyStore $shopifyStore->id");

				 			$packageDetails->WeightMajor = new Types\MeasureType();
                            $packageDetails->WeightMinor = new Types\MeasureType();
                             
                       Log::info("publish for 1296".$shVariants[0]["grams"]);
                     $packageDetails->WeightMinor->unit = "g";
               $packageDetails->WeightMinor->value = 100;

                 $packageDetails->WeightMajor->unit =  "kg";
                  $packageDetails->WeightMajor->value = 0;
                  }
                            
				if($paymentProfile || $shippingProfile || $returnProfile){
					$ebayItem->SellerProfiles = new Types\SellerProfilesType();
			
				if($shippingProfile){
				    
				      $ebayItem = $this->getShippingprofile($ebayItem,$profile,$shopifyStore,$shVariants,$shippingProfile);
                           
					}else{
					    echo ' <- shippingProfile not -> ';
					}

					if($paymentProfile){
						$ebayItem->SellerProfiles->SellerPaymentProfile = $paymentProfile;
					}

					if($returnProfile){
						$ebayItem->SellerProfiles->SellerReturnProfile = $returnProfile;
					}
				}else{
				  echo ' <- paymentProfile not -> ';
				}
                //print_r($ebayitem);
				//Log::info("domestic_returns_accepted value " . $ebayItem);
				$payment_methods = ($profile->payment_methods) ? json_decode($profile->payment_methods,true) : array();
					

				if(!$paymentProfile && $payment_methods){
					$ebayItem->PaymentMethods = $payment_methods;
					if(in_array("PayPal",$payment_methods) && $profile->paypal_email) $ebayItem->PayPalEmailAddress = $profile->paypal_email;
				}

				if(!$returnProfile){
					$ebayItem->ReturnPolicy = new Types\ReturnPolicyType();

					if(($profile->domestic_returns_accepted == "ReturnsAccepted") || ($profile->international_returns_accepted && $profile->international_returns_accepted != "ReturnsNotAccepted") ){
						if(($profile->return_policy_details) && ($site_id == 77 || $site_id == 16 || $site_id == 71 || $site_id == 101 || $site_id == 186)) $ebayItem->ReturnPolicy->Description = $profile->return_policy_details;
					}

               Log::info("domestic_returns_accepted value " . $profile->domestic_returns_accepted);
               Log::info("domestic_returns_accepted value " . $profile->domestic_refund_given_as); 
               Log::info("domestic_returns_accepted value " . $profile->domestic_returned_within); 
               
					$ebayItem->ReturnPolicy->ReturnsAcceptedOption = $profile->domestic_returns_accepted;
					if($profile->domestic_returns_accepted == "ReturnsAccepted"){
						$ebayItem->ReturnPolicy->RefundOption = $profile->domestic_refund_given_as;
						$ebayItem->ReturnPolicy->ReturnsWithinOption = $profile->domestic_returned_within;
						$ebayItem->ReturnPolicy->ShippingCostPaidByOption = $profile->domestic_returns_paid_by;
					}
					///////////////////////////////////////////////////////////////////////////////this below code will give error  
				// 	if($profile->international_returns_accepted && $profile->international_returns_accepted != "ReturnsNotAccepted"){
				// 		$ebayItem->ReturnPolicy->InternationalReturnsAcceptedOption = $profile->international_returns_accepted;
				// 		$ebayItem->ReturnPolicy->InternationalRefundOption = $profile->international_refund_given_as;
				// 		$ebayItem->ReturnPolicy->InternationalReturnsWithinOption = $profile->international_returned_within;
				// 		$ebayItem->ReturnPolicy->InternationalShippingCostPaidByOption = $profile->international_returns_paid_by;
				// 	}
					/////////////////////////////////////////////////////////////////////////////////
					else{
						//$ebayItem->ReturnPolicy->InternationalReturnsAcceptedOption = "ReturnsNotAccepted";
					}
				}


				if(!$shippingProfile){
				    
				       $ebayItem = $this->CreateShippingprofile($ebayItem,$profile,$shopifyStore,$shVariants,$shippingProfile);
				       
				}
	            Log::info("here is ebay object we are passing ".json_encode($ebayItem,true));
				$ebayRequest->Item = $ebayItem;
			
    	        //print_r($ebayItem);
				sleep(2);

				$ebayResponse = [];
				if($listing){
					$ebayResponse = ($listing_format == "auction") ? $ebayService->reviseItem($ebayRequest) : $ebayService->reviseFixedPriceItem($ebayRequest);
				}
				else{
					$ebayResponse = ($listing_format == "auction") ? $ebayService->addItem($ebayRequest) : $ebayService->addFixedPriceItem($ebayRequest);
				}
                 Log::info("add updated ebay item ebrequest  $listing_title".json_encode($ebayResponse,true));
                  Log::info("add updated ebay item ebbbbb".json_encode($ebayResponse,true));
				$isEnded = true;
				//$upc_val = false;
				$errors = array();
				if(isset($ebayResponse->Errors)){
					foreach($ebayResponse->Errors as $error){
						$severityCode = $error->SeverityCode === Enums\SeverityCodeType::C_ERROR ? 'Error' : 'Warning';
						if($severityCode == "Warning") continue;
						$errors[] = array("severitycode" => $severityCode,"shortmessage" => $error->ShortMessage,"longmessage" => $error->LongMessage);
				// 		if(strpos($error->ShortMessage, 'UPC has an invalid value of') !== false){
				// 		    $upc_val = true;
				// 		}
						if(strpos($error->ShortMessage,'ended') !== false) $isEnded = true;
					}
					$errors = json_encode($errors);
				//	Log::info("value of upc value ->  ".json_encode($upc_val));
					Log::info("Error occures in publishing product to ebay and here is the error  ".json_encode($errors,true));
				}
				
                 $SKU = "";
                  print_r(json_encode($ebayResponse));
				$isFailed = true;
				if($ebayResponse && isset($ebayResponse->Ack) && $ebayResponse->Ack !== 'Failure'){
					$isFailed = false;
					$itemID = $ebayResponse->ItemID;

					$ebayItemData = [];

					try{
						$ebayItemRequest = new Types\GetItemRequestType();
						$ebayItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
						$ebayItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
						$ebayItemRequest->ItemID = $itemID;
						$ebayItemRequest->IncludeItemSpecifics = true;
						sleep(2);

						$ebayItemResponse = $ebayService->getItem($ebayItemRequest);
						$ebayItemData = $ebayItemResponse->toArray();
						$ebayItemData = (isset($ebayItemData["Item"])) ? $ebayItemData["Item"] : [];
					}
					catch(\Exception $e){
						report($e);
					}
					echo "hiteshmali" . $itemID ;
					//////////////////////////////////////////////////////////////////////////////////////////////////////
					$this->listproductstoebay($ebayItemData,$listing,$variants,$listing_title,$itemID,$ebayAccount,$shopifyStore,$product,$shVariants,$option1Name,$option2Name,$option3Name);
                $errors = (is_array($errors)) ? json_encode($errors) : $errors;
				
				}
				
				 
				else if($ebayResponse && $ebayResponse->Ack === 'Failure' && $isEnded && $listing){
					$ebayRequest = ($listing_format == "auction") ? new Types\RelistItemRequestType() : new Types\RelistFixedPriceItemRequestType();
					$ebayRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
					$ebayRequest->RequesterCredentials->eBayAuthToken = $ebay_token;

					$listing_duration = "";
					if( isset($profile->listing_duration) && $profile->listing_duration ){
						$listing_duration = $profile->listing_duration;
					}
					$ebayItem = new Types\ItemType();
					if($listing_format == "auction"){
						$ebayItem->ListingType = Enums\ListingTypeCodeType::C_CHINESE;
						$ebayItem->ListingDuration = ($listing_duration) ? $listing_duration : Enums\ListingDurationCodeType::C_DAYS_7;
					}
					else{
						$ebayItem->ListingType = Enums\ListingTypeCodeType::C_FIXED_PRICE_ITEM;
						$ebayItem->ListingDuration = ($listing_duration) ? $listing_duration : Enums\ListingDurationCodeType::C_GTC;
					}
					$ebayItem->ItemID = $listing->ebay_item_id;
					$ebayItem->Site = EbayHelper::getEbaySiteNameFromID($site_id);
					$ebayRequest->Item = $ebayItem;

					$ebayResponse = array();
					sleep(2);

					$ebayResponse = ($listing_format == "auction") ? $ebayService->relistItem($ebayRequest) : $ebayService->relistFixedPriceItem($ebayRequest);

					$errors = array();
					if(isset($ebayResponse->Errors)){
						foreach($ebayResponse->Errors as $error){
							$severityCode = $error->SeverityCode === Enums\SeverityCodeType::C_ERROR ? 'Error' : 'Warning';
							if($severityCode == "Warning") continue;
							$errors[] = array("severitycode" => $severityCode,"shortmessage" => $error->ShortMessage,"longmessage" => $error->LongMessage);
							if(strpos($error->ShortMessage,'ended') !== false) $isEnded = true;
						}
						$errors = json_encode($errors);
					}
					print_r(json_encode($ebayResponse,true));
					echo 'hiteshmali' ;
					echo 'relistendproducts';
					 $functjjjj =   $this->relistendproducts($ebayResponse,$ebayService,$shopifyStore,$ebay_token,$listing,$pendingPublish);

                if (isset($functjjjj)) {
                    $errors = $functjjjj ;
                }


				}
               
    //             elseif($ebayResponse && $ebayResponse->Ack === 'Failure' && $upc_val){
    //                 	Log::info(">>>>>>>>>>>>>>>>>>>>>hi>>>>>>>>>>>>>>>> ".$pvariant->id);
                    	
    //              $productt = $shopifyStore->variants()
    //                      ->where('product_id', $pendingPublish->product_id)
    //                      ->update(['product_id_val' => ""]);

                 
                  
    //                  $jobData = array();
				// 	$jobData["product_id"] = (int) $pendingPublish->product_id;
				// 	$jobData["profile_id"] = 1;
				// 	$jobData["account_id"] = 1202;
				// 	$jobData["store_id"] = 1500;
				// 	$jobData["user_id"] = 1508;
				
				// 	PublishProduct::dispatchNow($jobData);
	   //             Log::info(">>>>>>>>>>>>>>>>>>>>>hello>>>>>>>>>>>>>>>> ");

    //             }
				if($pendingPublish->product && $pendingPublish->product->submit){
					$pendingPublish->product->submit = NULL;
					$pendingPublish->product->save();
				}
				$pendingPublish->delete();

				$log_data_id[] = array(
					"product_id" => $pendingPublish->product_id,
					"profile_id" => $pendingPublish->profile_id,
					"account_id" => $pendingPublish->account_id,
					"store_id" => $pendingPublish->store_id
				);

				$output_data = array();
				if($errors) $output_data["errors"] = $errors;


				$logData = array();
				$logData["log_type"] = "publish_product_ebay";
				$logData["shopify_data"] = NULL;
				$logData["shopify_data_id"] = NULL;
				$logData["log_data_id"] = json_encode($log_data_id);
				$logData["status"] = ($isFailed) ? "error" : "success";
				$logData["output_data"] = json_encode($output_data,JSON_INVALID_UTF8_IGNORE);
				$logData["remarks"] = (!$isFailed) ? " : product published on ebay" : " : product failed to publish on ebay";
				$logData["remarks"] = $shProduct["title"].$logData["remarks"];
				$logData["store_id"] = $shopifyStore->id;
				$logData["user_id"] = $shopifyStore->user_id;
				$shopifyStore->logs()->create($logData);

				return $ebayResponse;
			}
			else{
				return "one of product, profile, category data is invalid";
			}
		}
		catch(\Exception $e){
			report($e);
			return $e->getMessage();
		}
	}

function CreateShippingprofile($ebayItem,$profile,$shopifyStore,$shVariants,$shippingProfile)
{

    $ebayItem->ShippingDetails = new Types\ShippingDetailsType();

    $domestic_shipping = $profile->domestic_shipping;
    $intl_shipping = $profile->intl_shipping;
    if ($domestic_shipping && $domestic_shipping != "NotSpecified" && $domestic_shipping != "NOT_SPECIFIED") {

        $domestic_ships_within_handling_days = (int) $profile->domestic_ships_within_handling_days;

        if ($domestic_ships_within_handling_days !== "" && $domestic_ships_within_handling_days >= 0)
            $ebayItem->DispatchTimeMax = $domestic_ships_within_handling_days;

        if ($domestic_shipping == "Flat" && $intl_shipping == "Calculated") {
            $ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_FLAT_DOMESTIC_CALCULATED_INTERNATIONAL;
        } else if ($domestic_shipping == "Calculated" && $intl_shipping == "Flat") {
            $ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_CALCULATED_DOMESTIC_FLAT_INTERNATIONAL;
        } else if ($domestic_shipping == "Flat" || $intl_shipping == "Flat") {
            $ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_FLAT;
        } else if ($domestic_shipping == "Calculated" || $intl_shipping == "Calculated") {
            $ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_CALCULATED;
        } else if ($domestic_shipping == "Freight") {
            $ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_FREIGHT;
        } else if ($domestic_shipping == "FreightFlat") {
            $ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_FREIGHT_FLAT;
        }


        if ($domestic_shipping == "Calculated" || $intl_shipping == "Calculated") {
            $ebayItem->ShippingDetails->CalculatedShippingRate = new Types\CalculatedShippingRateType();

            if ($domestic_shipping == "Calculated") {
                $ebayItem->ShippingDetails->CalculatedShippingRate->PackagingHandlingCosts = new Types\AmountType(['value' => $profile->domestic_pkg_handling_fee]);
            }
            if ($intl_shipping == "Calculated") {
                $ebayItem->ShippingDetails->CalculatedShippingRate->InternationalPackagingHandlingCosts = new Types\AmountType(['value' => $profile->intl_pkg_handling_fee]);
            }
            $ebayItem->ShippingDetails->CalculatedShippingRate->OriginatingPostalCode = (string) $profile->postal_code;

            $packageDetails = new Types\ShipPackageDetailsType();
            $packageDetails->ShippingPackage = 'PackageThickEnvelope';
            $packageDetails->MeasurementUnit = Enums\MeasurementSystemCodeType::C_ENGLISH;
            $packageDetails->ShippingIrregular = true;

            /*
            if($profile->pk_width){
                $packageDetails->PackageWidth = new Types\MeasureType();
                $packageDetails->PackageWidth->unit = 'in';
                $packageDetails->PackageWidth->value = $profile->pk_width;
            }
            if($profile->pk_length){
                $packageDetails->PackageLength = new Types\MeasureType();
                $packageDetails->PackageLength->unit = 'in';
                $packageDetails->PackageLength->value = $profile->pk_length;
            }
            if($profile->pk_height){
                $packageDetails->PackageDepth = new Types\MeasureType();
                $packageDetails->PackageDepth->unit = 'in';
                $packageDetails->PackageDepth->value = $profile->pk_height;
            }
            */



            $packageDetails->WeightMajor = new Types\MeasureType();
            $packageDetails->WeightMinor = new Types\MeasureType();


            if ($shopifyStore->id == 1460) {
                $packageDetails = new Types\ShipPackageDetailsType();
                $packageDetails->WeightMajor = new Types\MeasureType();
                $packageDetails->WeightMinor = new Types\MeasureType();

                Log::info("publish for 1460");
                $packageDetails->WeightMinor->unit = "ounces";
                $packageDetails->WeightMinor->value = 0;

                $packageDetails->WeightMajor->unit = "lb";
                $packageDetails->WeightMajor->value = 10;
            }


            if ($shVariants[0]["grams"] < 1000) {

                $packageDetails->WeightMinor->unit = "g";
                $packageDetails->WeightMinor->value = 1;//$shVariants[0]["grams"];

                $packageDetails->WeightMajor->unit = "kg";
                $packageDetails->WeightMajor->value = 0;//ceil($shVariants[0]["weight"]);
            } else {
                $packageDetails->WeightMinor->unit = "g";
                $packageDetails->WeightMinor->value = 100;

                $packageDetails->WeightMajor->unit = "kg";
                $packageDetails->WeightMajor->value = $shVariants[0]["grams"];
            }


            $ebayItem->ShippingPackageDetails = $packageDetails;

            Log:
            info("anjali shipping 1" . json_encode($ebayItem->ShippingPackageDetails));
        }

        if ($profile->domestic_ship_service1 && $profile->domestic_ship_service1 != "NotSelected" && $profile->domestic_shipping != "NotSpecified") {
            $shippingService = new Types\ShippingServiceOptionsType();
            $shippingService->ShippingServicePriority = 1;
            $shippingService->ShippingService = $profile->domestic_ship_service1;
            if ($domestic_shipping == "Flat") {
                $shippingService->ShippingServiceCost = new Types\AmountType(['value' => (float) $profile->ship_fee1]);
                if ($profile && isset($profile->x_ship_fee1) && $profile->x_ship_fee1 !== NULL && $profile->x_ship_fee1 !== "") {
                    $shippingService->ShippingServiceAdditionalCost = new Types\AmountType(['value' => (float) $profile->x_ship_fee1]);
                }
            }
            if ($profile->domestic_free_shipping)
                $shippingService->FreeShipping = true;
            if ($profile->domestic_local_pickup) {
                $shippingService->LocalPickup = true;
            } else {
                $shippingService->LocalPickup = false;
            }
            $ebayItem->ShippingDetails->ShippingServiceOptions[] = $shippingService;
        }
        $domestic_ship_additional_services = ($profile->domestic_ship_additional_services) ? json_decode($profile->domestic_ship_additional_services) : array();
        if ($domestic_ship_additional_services) {
            $pr = 2;
            foreach ($domestic_ship_additional_services as $dsservice) {
                if (isset($dsservice->domestic_ship_service1) && $dsservice->domestic_ship_service1 && $dsservice->domestic_ship_service1 != "NOT_SPECIFIED" && $dsservice->domestic_ship_service1 != "NotSpecified" && $dsservice->domestic_ship_service1 != "NotSelected") {

                    $shippingService = new Types\ShippingServiceOptionsType();
                    $shippingService->ShippingServicePriority = $pr;
                    $shippingService->ShippingService = $dsservice->domestic_ship_service1;
                    if ($domestic_shipping == "Flat") {
                        $shippingService->ShippingServiceCost = new Types\AmountType(['value' => (float) $dsservice->ship_fee1]);
                        if ($dsservice && isset($dsservice->x_ship_fee1) && $dsservice->x_ship_fee1 !== NULL && $dsservice->x_ship_fee1 !== "") {
                            $shippingService->ShippingServiceAdditionalCost = new Types\AmountType(['value' => (float) $dsservice->x_ship_fee1]);
                        }
                    }
                    if (isset($dsservice->domestic_free_shipping) && $dsservice->domestic_free_shipping)
                        $shippingService->FreeShipping = true;
                    if (isset($dsservice->domestic_local_pickup) && $dsservice->domestic_local_pickup) {
                        $shippingService->LocalPickup = true;
                    } else {
                        $shippingService->LocalPickup = false;
                    }
                    $ebayItem->ShippingDetails->ShippingServiceOptions[] = $shippingService;
                    $pr++;
                }
            }
        }


        if ($profile->intl_ship_service1 && $profile->intl_ship_service1 != "NOT_SPECIFIED" && $profile->intl_ship_service1 != "NotSpecified" && $profile->intl_ship_service1 != "NotSelected" && $profile->intl_shipping != "NotSpecified") {
            $shippingService = new Types\InternationalShippingServiceOptionsType();
            $shippingService->ShippingServicePriority = 1;
            $shippingService->ShippingService = $profile->intl_ship_service1;
            if ($intl_shipping == "Flat") {
                $shippingService->ShippingServiceCost = new Types\AmountType(['value' => (float) $profile->intl_ship_fee1]);
                $shippingService->ShippingServiceAdditionalCost = new Types\AmountType(['value' => (float) $profile->intl_x_ship_fee1]);
            }
            $intl_ship_options1 = $profile->intl_ship_options1;
            if ($intl_ship_options1 == 2) {
                $intl_locations1 = ($profile->intl_locations1) ? explode(",", $profile->intl_locations1) : array('WorldWide');
                $shippingService->ShipToLocation = ($intl_locations1) ? $intl_locations1 : array('WorldWide');
            } else if ($intl_ship_options1 == 3) {
                $shippingService->ShipToLocation = ['CA'];
            } else {
                $shippingService->ShipToLocation = ['WorldWide'];
            }
            //$shippingService->LocalPickup = false;
            $ebayItem->ShippingDetails->InternationalShippingServiceOption[] = $shippingService;
        }

        $intl_ship_additional_services = ($profile->intl_ship_additional_services) ? json_decode($profile->intl_ship_additional_services) : array();
        if ($intl_ship_additional_services) {
            $pr = 2;
            foreach ($intl_ship_additional_services as $isservice) {
                if (isset($isservice->intl_ship_service1) && $isservice->intl_ship_service1 && $isservice->intl_ship_service1 != "NOT_SPECIFIED" && $isservice->intl_ship_service1 != "NotSpecified" && $isservice->intl_ship_service1 != "NotSelected") {

                    $shippingService = new Types\InternationalShippingServiceOptionsType();
                    $shippingService->ShippingServicePriority = $pr;
                    $shippingService->ShippingService = $isservice->intl_ship_service1;
                    if ($intl_shipping == "Flat") {
                        $shippingService->ShippingServiceCost = new Types\AmountType(['value' => (float) $isservice->intl_ship_fee1]);
                        $shippingService->ShippingServiceAdditionalCost = new Types\AmountType(['value' => (float) $isservice->intl_x_ship_fee1]);
                    }
                    $intl_ship_options1 = $isservice->intl_ship_options1;
                    if ($intl_ship_options1 == 2) {
                        if (!is_array($isservice->intl_locations1))
                            $intl_locations1 = ($isservice->intl_locations1) ? explode(",", $isservice->intl_locations1) : array('WorldWide');
                        else
                            $intl_locations1 = $isservice->intl_locations1;

                        //$intl_locations1 = ($isservice->intl_locations1) ? explode(",",$isservice->intl_locations1) : array('WorldWide');
                        $shippingService->ShipToLocation = ($intl_locations1) ? $intl_locations1 : array('WorldWide');
                    } else if ($intl_ship_options1 == 3) {
                        $shippingService->ShipToLocation = ['CA'];
                    } else {
                        $shippingService->ShipToLocation = ['WorldWide'];
                    }
                    //$shippingService->LocalPickup = false;
                    $ebayItem->ShippingDetails->InternationalShippingServiceOption[] = $shippingService;
                    $pr++;
                }
            }
        }
    } else {
        $ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_NOT_SPECIFIED;
        //$ebayItem->ShipToLocations[] = 'None';
    }

    if ($profile->sales_tax_rate > 0 && $profile->sales_tax_region && $profile->sales_tax_region != "ALL") {
        $salesTaxType = new Types\SalesTaxType();
        $salesTaxType->SalesTaxPercent = (double) $profile->sales_tax_rate;
        $salesTaxType->SalesTaxState = $profile->sales_tax_region;
        if ($profile->apply_tax_to_shipping) {
            $salesTaxType->ShippingIncludedInTax = true;
        }
        $ebayItem->ShippingDetails->SalesTax = $salesTaxType;
    }
    return $ebayItem;

}


public function getShippingprofile($ebayItem,$profile,$shopifyStore,$shVariants,$shippingProfile)
{


    echo ' <- shippingProfile -> ';
    Log::info("shipping profile " . json_encode($shippingProfile, true));
    $ebayItem->SellerProfiles->SellerShippingProfile = $shippingProfile;


    $packageDetails = new Types\ShipPackageDetailsType();
    //	$packageDetails->ShippingPackage = 'PackageThickEnvelope';
    //	$packageDetails->MeasurementUnit = Enums\MeasurementSystemCodeType::C_ENGLISH;
    //	$packageDetails->ShippingIrregular = true;


    $packageDetails->WeightMajor = new Types\MeasureType();
    $packageDetails->WeightMinor = new Types\MeasureType();


    Log::info("publish for 12965555" . $shVariants[0]["grams"]);
    if ($shVariants[0]["grams"] < 1000) {

        $packageDetails->WeightMinor->unit = "g";
        $packageDetails->WeightMinor->value = 1;//$shVariants[0]["grams"];

        $packageDetails->WeightMajor->unit = "kg";
        $packageDetails->WeightMajor->value = 0;//ceil($shVariants[0]["weight"]);
        if ($shopifyStore->id == 1296) {
            Log::info("publish for 1296" . $shVariants[0]["grams"]);
            $packageDetails->WeightMinor->unit = "g";
            $packageDetails->WeightMinor->value = 1;

            $packageDetails->WeightMajor->unit = "kg";
            $packageDetails->WeightMajor->value = 0;
        }
        Log::info("shipping profile else if side" . json_encode($packageDetails, true));
    } else {
        $packageDetails->WeightMinor->unit = "g";
        $packageDetails->WeightMinor->value = 0;

        $packageDetails->WeightMajor->unit = "kg";
        $packageDetails->WeightMajor->value = $shVariants[0]["grams"];
        Log::info("shipping profile else side" . json_encode($shVariants[0]));
        Log::info("shipping profile else side" . json_encode($packageDetails, true));
        if ($shopifyStore->user_id == 447 && $packageDetails->WeightMajor->unit = "kg" && $packageDetails->WeightMajor->value > 65) {
            $packageDetails->WeightMinor->unit = "g";
            $packageDetails->WeightMinor->value = 0;

            $packageDetails->WeightMajor->unit = "kg";
            $packageDetails->WeightMajor->value = 65;
        }
        if ($shopifyStore->user_id == 584) {
            $packageDetails->WeightMinor->unit = "g";
            $packageDetails->WeightMinor->value = 0;

            $packageDetails->WeightMajor->unit = "kg";
            $packageDetails->WeightMajor->value = 65;
        }
    }

    //   else {
    //      $packageDetails->WeightMajor->unit =  $shVariants[0]["weight_unit"];
    //       $packageDetails->WeightMajor->value =$shVariants[0]["weight"];

    //       Log::info("sssssssssssssss profile else side".json_encode($packageDetails,true));
    //       if($shopifyStore->user_id == 584 && $packageDetails->WeightMajor->unit =  "kg" &&  $packageDetails->WeightMajor->value >65) {
    // //           $packageDetails->WeightMinor->unit = "g";
    // //   $packageDetails->WeightMinor->value = 0;

    //      $packageDetails->WeightMajor->unit =  $shVariants[0]["weight_unit"];
    //       $packageDetails->WeightMajor->value =65;
    //       }
    //  }

    Log::info("shipping profile 2" . json_encode($packageDetails, true));
    Log::info("trial shipping package test start from here");


    $packageDetails->PackageLength = new Types\MeasureType();
    $packageDetails->PackageWidth = new Types\MeasureType();
    $packageDetails->PackageDepth = new Types\MeasureType();
    if ($shopifyStore->user_id == 437 || $shopifyStore->user_id == 511) {
        Log::info("Entered in the  parcel detail of user_id 437 ");
        $packageDetails->PackageLength->unit = "cm";
        $packageDetails->PackageLength->value = 23;
        $packageDetails->PackageWidth->unit = "cm";
        $packageDetails->PackageWidth->value = 18;
        $packageDetails->PackageDepth->unit = "cm";
        $packageDetails->PackageDepth->value = 4;
    } else {
        Log::info("Entered in the else condition of parcel detail");
        $packageDetails->PackageLength->unit = "cm";
        $packageDetails->PackageLength->value = 75;
        $packageDetails->PackageWidth->unit = "cm";
        $packageDetails->PackageWidth->value = 50;
        $packageDetails->PackageDepth->unit = "cm";
        $packageDetails->PackageDepth->value = 50;
    }

    // Log::info("Entered in the " . json_encode($packageDetails)); 
    $ebayItem->ShippingPackageDetails = $packageDetails;
    return $ebayItem;

}

	
  public function priceandquntity($pvariant, $ebayAccount, $shopifyStore, $ebayItem)
{

    $vquantity = (int) $pvariant->quantity;

    $lvarqty = $vquantity;
    Log::info("Here is the quantity " . $vquantity);
    $listing_quantity_value = (int) $ebayAccount->listing_quantity_value;
    if ($ebayAccount->listing_quantity == 1 && $lvarqty > $listing_quantity_value)
        $lvarqty = $listing_quantity_value;
    if ($ebayAccount->threshold_quantity == 1 && $lvarqty <= $ebayAccount->threshold_quantity_value)
        $lvarqty = 0;


    if ($lvarqty < 0)
        $lvarqty = 0;

    $lvarpr = (float) $pvariant->price;
    Log::info("price is this " . $lvarpr);

    $lvmsrp = (float) $pvariant->compare_at_price;
    Log::info("compare_at_price is this " . $lvmsrp);


    if ($shopifyStore->user_id == 7)
        $lvarqty = 1;

    if ($shopifyStore->id == 1460) {
        log::info(" shopify store id is 1460 ");
        $lvarqty = 1;
    }

	if ($shopifyStore->id == 1582) {
        log::info(" shopify store id is 1582 ");
        $lvarqty = 1;
    }

    if ($ebayAccount->pricing_mark_up == 1) {
        if ($ebayAccount->pricing_mark_up_type == "percentage") {
            $lvarpr = $lvarpr + (($ebayAccount->pricing_mark_up_value / 100) * $lvarpr);
            $lvmsrp = $lvmsrp + (($ebayAccount->pricing_mark_up_value / 100) * $lvmsrp);
        } else if ($ebayAccount->pricing_mark_up_type == "fixed") {
            $lvarpr = $lvarpr + $ebayAccount->pricing_mark_up_value;
            $lvmsrp = $lvmsrp + $ebayAccount->pricing_mark_up_value;
        }
    }

    $ebayItem->Quantity = $lvarqty;//($listing_format == "auction") ? 1 : $lvarqty;

    $ebayItem->StartPrice = new Types\AmountType(['value' => (float) $lvarpr]);

    // Additional processing for eBay item can be added here
	/*if($lvmsrp > $lvarpr){
						$discountPriceInfo = new Types\DiscountPriceInfoType();
						$discountPriceInfo->OriginalRetailPrice = new Types\AmountType(['value' => (float) $lvmsrp]);
						$ebayItem->DiscountPriceInfo = $discountPriceInfo;
					}*/


    return $ebayItem;
}

public function getEbayategory($listing,$profile,$shProduct,$productData,$ebayItem,$site_id,$shopifyStore)
{
    if ($profile->category1) {
        Log::info("here is the category id for category 1 " . $profile->category1->ebay_category_id);
        $ebayItem->PrimaryCategory = new Types\CategoryType();
        $ebayItem->PrimaryCategory->CategoryID = $profile->category1->ebay_category_id;
    }

    if ($profile->category2) {
        Log::info("here is the category id for category 2 " . $profile->category1->ebay_category_id);
        $ebayItem->SecondaryCategory = new Types\CategoryType();
        $ebayItem->SecondaryCategory->CategoryID = $profile->category2->ebay_category_id;
    }

    if ($profile->storeCategory) {
        Log::info("Here is the sotre category id " . $profile->category1->ebay_category_id);
        $ebayItem->Storefront = new Types\StorefrontType();
        $ebayItem->Storefront->StoreCategoryID = (int) $profile->storeCategory->ebay_category_id;
        $ebayItem->Storefront->StoreCategoryName = $profile->storeCategory->category_name;
    }

    $ebayItem->Country = EbayHelper::getEbayCountry($site_id);
    if ($profile->postal_code)
        $ebayItem->PostalCode = (string) $profile->postal_code;
    if ($profile->item_location)
        $ebayItem->Location = trim($profile->item_location);
    $ebayItem->Currency = EbayHelper::getEbayCurrency($site_id);


    if ($productData && $productData->condition) {
        Log::info("Item condition is this " . $productData->condition);
        if ($productData->condition == 'New')
            $ebayItem->ConditionID = 1000;
        else if ($productData->condition == 'Used')
            $ebayItem->ConditionID = 3000;
        else if ($productData->condition == 'Good')
            $ebayItem->ConditionID = 5000;
        else if ($productData->condition == 'Very Good')
            $ebayItem->ConditionID = 4000;
        else if ($productData->condition == 'Like New')
            $ebayItem->ConditionID = 2750;
        else if ($productData->condition == 'New other (see details)')
            $ebayItem->ConditionID = 1500;
        else if ($productData->condition == 'New with defects')
            $ebayItem->ConditionID = 1750;
        else if ($productData->condition == 'Certified - Refurbished')
            $ebayItem->ConditionID = 2000;
        else if ($productData->condition == 'Excellent - Refurbished')
            $ebayItem->ConditionID = 2010;
        else if ($productData->condition == 'Very Good - Refurbished')
            $ebayItem->ConditionID = 2020;
        else if ($productData->condition == 'Good - Refurbished')
            $ebayItem->ConditionID = 2030;
        else if ($productData->condition == 'Seller refurbished')
            $ebayItem->ConditionID = 2500;
        else if ($productData->condition == 'Acceptable')
            $ebayItem->ConditionID = 6000;
        else if ($productData->condition == 'For parts or not working')
            $ebayItem->ConditionID = 7000;
    } else
        $ebayItem->ConditionID = 1000;

if ($productData && $productData->condition_note)
        $ebayItem->ConditionDescription = $productData->condition_note;
    
        //   print_r($ebayItem);
    // if ($shopifyStore->user_id == 1272) {
        
        
        
    // $ebayItem->ConditionID = 4000; // Assuming 4000 is a valid ID for "Ungraded".
    
    // // Set the condition description.
    // $ebayItem->ConditionDescription = "Ungraded";
        // $conditionDescriptor = new Types\ConditionDescriptorType();
        
        
// $conditionDescriptor->ConditionDescriptorID = 40001; // Card Condition ID
// $conditionDescriptor->ConditionDescriptorValueID = 400012; // Very good ID
// $conditionDescriptor->ConditionDescriptorValueName = 'Very good';

// $ebayItem->ConditionDescriptors = new Types\ConditionDescriptorArrayType();
// $ebayItem->ConditionDescriptors->ConditionDescriptor[] = $conditionDescriptor;

// // Add item specifics
// $itemSpecifics = new Types\NameValueListArrayType();
// $nameValue = new Types\NameValueListType();
// $nameValue->Name = 'Card Condition';
// $nameValue->Value[] = 'Very good';
// $itemSpecifics->NameValueList[] = $nameValue;
// $item->ItemSpecifics = $itemSpecifics;


//          // Set the main condition ID for the eBay item.
//     // $ebayItem->ConditionDescription = 
//     // Set the condition descriptor ID and name.
//     // These should match the specifics of the eBay API documentation for trading cards.
    
//     // $ebayItem->ConditionDescriptorId = 400012; // Assuming 40001 is a valid ID for "Card Condition".
//     // $ebayItem->ConditionDescriptorName = "Very good";
    
//     // Uncomment and set the descriptor value ID and name if needed.
//     // These values must be valid as per eBay's trading card condition descriptors.
    
//     // $ebayItem->ConditionDescriptorValueId = 400012; // Assuming 400012 is a valid ID for "Very good".
//     // $ebayItem->ConditionDescriptorValueName = "Very good";
        
        
        
//         // $ebayItem->ConditionID = 4000;
//         // $ebayItem->ConditionDescription = "Ungraded";
        
//         // $ebayItem->ConditionDescriptorId = 40001 ;
//         // $ebayItem->ConditionDescriptorName = "Card Condition";
        
//         // $ebayItem->ConditionDescriptorValueId =  400012 ;
//         // $ebayItem->conditionDescriptorValueName = "Very good" ;
    // }
    

    return $ebayItem;
}	
	
	
  public function getEbayItem($listing, $profile, $shProduct, $productData, $listing_format,$ebayItem)
{
    // $ebayItem = new Types\ItemType();
    $listing_duration = $profile->listing_duration;

    if ($listing_format == "auction") {
        Log::info("listing format is auction");
        $ebayItem->ListingType = Enums\ListingTypeCodeType::C_CHINESE;
        $ebayItem->ListingDuration = ($listing_duration) ? $listing_duration : Enums\ListingDurationCodeType::C_DAYS_7;
    } else {
        Log::info("listing format is fixed price ");
        $ebayItem->ListingType = Enums\ListingTypeCodeType::C_FIXED_PRICE_ITEM;
        $ebayItem->ListingDuration = ($listing_duration) ? $listing_duration : Enums\ListingDurationCodeType::C_GTC;
    }

    if ($listing)
        $ebayItem->ItemID = $listing->ebay_item_id;

    //	$listing_title = ($profile->listing_title) ? $profile->listing_title : $shProduct["title"];
    $listing_title = $shProduct["title"];
    Log::info("add updated ebay item title $listing_title");
    if ($productData && $productData->title)
        $listing_title = $productData->title;
    else if ($profile->trim_title == 1) {//!$profile->listing_title && 
        $listing_title = substr($listing_title, 0, 80);
    }

    $ebayItem->Title = $listing_title;


    if ($profile->template && $profile->template->template_data) {
        $ebayItem->Description = str_replace("{{description}}", $shProduct["body_html"], $profile->template->template_data);
    } else if ($shProduct["body_html"] == "") {
        $ebayItem->Description = "new items";//??
    } else {
        $ebayItem->Description = $shProduct["body_html"];
    }

    return $ebayItem;
}


public	function listproductstoebay($ebayItemData,$listing,$variants,$listing_title,$itemID,$ebayAccount,$shopifyStore,$product,$shVariants,$option1Name,$option2Name,$option3Name){
    
    if(isset($ebayItemData["Variations"]) && $ebayItemData["Variations"]){
        Log::info("item is multivariant variant ");
   $SKU = "Multivariant";
 }else{
         Log::info("item is single variant ");
     $SKU = "Singlevariant";
 }
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 if($listing){
     $listingVariants = $listing->variants()->get();
     if($listingVariants->count() > 0){
         $deleteVars = array();
         foreach($listingVariants as $listingVariant){
             $varFound = false;
             foreach($variants as $pvariant){
                 if($pvariant->id == $listingVariant->variant_id){
                     $varFound = true;
                     break;
                 }
             }
             if(!$varFound && !in_array($listingVariant->variant_id,$deleteVars)){
                 $deleteVars[] = $listingVariant->variant_id;   
                 $listingVariant->delete();
             }
         }
     }
 }

 $image = null;
 if(isset($ebayItemData["PictureDetails"]) && isset($ebayItemData["PictureDetails"]["PictureURL"])){
     $image = $ebayItemData["PictureDetails"]["PictureURL"][0];
 }
 else if(isset($ebayItemData["Variations"]) && isset($ebayItemData["Variations"]["Pictures"]) && $ebayItemData["Variations"]["Pictures"]){
     $image = $ebayItemData["Variations"]["Pictures"][0]["VariationSpecificPictureSet"][0]["PictureURL"][0];
 }

 $listing_id = "";
 if($listing){
     $listing_id = $listing->id;
     $listing->listing_data = json_encode($ebayItemData);
     $listing->image = $image;
     $listing->sku = $SKU;
 //	$listing->sku = $variants[0]->shopify_variant_id;
     $listing->save();
 }
 else{
    //  $errors = (is_array($errors)) ? json_encode($errors) : $errors;

     $listingData = array();
     $listingData["title"] = mb_convert_encoding($listing_title,'ISO-8859-1','utf-8');
     $listingData["image"] = $image;
     $listingData["status"] = "published";
     $listingData["ebay_item_id"] = $itemID;
 //	$listingData["sku"] = $variants[0]->sku;
 //	$listingData["sku"] = $variants[0]->shopify_variant_id;
     $listingData["sku"] = $SKU;
     
     $listingData["listing_data"] = json_encode($ebayItemData);

     $listingData["listing_url"] = "https://www.ebay.com/itm/".$itemID;
     $listingData["account_id"] = $ebayAccount->id;
     $listingData["store_id"] = $shopifyStore->id;
     $listingData["user_id"] = $shopifyStore->user_id;
     
     $listing = $shopifyStore->listings()->create($listingData);
Log::info("listing is created in db ");
     $listing_id = $listing->id;
 }
  Log::info("listing  2222222222222222222 ");
 if($listing->product_id != $product->id){
     $listing->product_id = $product->id;
     $listing->save();
 }

 if($product->listing_id != $listing->id){
     $product->listing_id = $listing->id;
     $product->status = "published";
     $product->save();
 }

 Log::info("listing  3333333333333333333333 ");
 foreach($shVariants as $shVariant){
     $pvariant = [];
     foreach($variants as $variant){
         if($variant->shopify_variant_id == $shVariant["id"]){
             $pvariant = $variant;
             break;
         }
     }

     $listing_variant_data = [];
     Log::info("ebay variation valueeeeee -> ".json_encode($ebayItemData,true));
// 		if(isset($ebayItemData["Variations"]) && $ebayItemData["Variations"]){
// 			foreach($ebayItemData["Variations"]["Variation"] as $variation){
             
// 			    Log::info("ebay variation value -> ".json_encode($variation,true));
// 			    Log::info("pvariant sku value -> ".$pvariant->sku);
          
// 			 //  $shopify_variant_id =  $variation["SKU"] ;
// 			 //  $shopifyvar = $shopifyStore->variants()->where('shopify_variant_id',$shopify_variant_id)->first();
// 			 //  	if($variation["SKU"] == $shopifyvar->shopify_variant_id){
// 				// 	$listing_variant_data = $variation;
                 
// 				// }
             
             
             
// 				if($variation["SKU"] == $pvariant->sku){
// 					$listing_variant_data = $variation;
// 					break;
// 				}
// 			}
// 		}
//////////////////////////////////////////////////////////*********************************************//////////////////////////////////////////////////////////////////

       if(isset($ebayItemData["Variations"]) && $ebayItemData["Variations"]){
             Log::info("Item is multivariant ");
         foreach($ebayItemData["Variations"]["Variation"] as $variation){
             
             Log::info("ebay variation value -> ".json_encode($variation,true));
             Log::info("pvariant sku value -> ".$pvariant->sku);
          
            $shopify_variant_id =  $variation["SKU"] ;
            $shopifyvar = $shopifyStore->variants()->where('shopify_variant_id',$shopify_variant_id)->first();
                if($variation["SKU"] == $shopifyvar->shopify_variant_id){
                  $listing_variant_data = $variation;
                 
              }
             
             
             
         }
     
         if(!$listing_variant_data) continue;

     $vimage =null;

      Log::info("listing  444444444444444444444444444 ");
         if(isset($ebayItemData["Variations"]["Pictures"]) && $ebayItemData["Variations"]["Pictures"]){
             $variationSpecificName = $ebayItemData["Variations"]["Pictures"][0]["VariationSpecificName"];
             foreach($ebayItemData["Variations"]["Pictures"][0]["VariationSpecificPictureSet"] as $picture){
                 if($variationSpecificName == $option1Name && $picture["VariationSpecificValue"] == $shVariant["option1"]){
                     $vimage = $picture["PictureURL"][0];break;
                 }
                 else if($variationSpecificName == $option2Name && $picture["VariationSpecificValue"] == $shVariant["option2"]){
                     $vimage = $picture["PictureURL"][0];break;
                 }
                 else if($variationSpecificName == $option3Name && $picture["VariationSpecificValue"] == $shVariant["option3"]){
                     $vimage = $picture["PictureURL"][0];break;
                 }
             }
         }
     


     $variant_id = $pvariant->id;
     Log::info("111111111111111111111111111111 db".$variant_id);
      Log::info("222222222222222222222222 db".$pvariant->shopify_variant_id);
     $listingVariant = $listing->variants()->where('variant_id',$variant_id)->first();
     if($listingVariant){
         Log::info("listingVariant found in db");
         $listingVariant->ebay_item_id = $itemID;
         $listingVariant->sku = $pvariant->shopify_variant_id;
         $listingVariant->ebay_item_data = json_encode($ebayItemData);
         $listingVariant->listing_variant_data = json_encode($listing_variant_data);
         $listingVariant->image = $vimage;

         $listingVariant->save();
     }
     else{
       
       //   Log::info("Creating ebay variants in db".$itemID);
       //   Log::info("Creating ebay variants in db".$pvariant->shopify_variant_id);
    //       Log::info("Creating ebay variants in db".$vimage);
    //      Log::info("Creating ebay variants in db".json_encode($listing_variant_data));
    //      Log::info("Creating ebay variants in db".json_encode($ebayItemData));
       //   Log::info("Creating ebay variants in db". $listing->id);
       //   Log::info("Creating ebay variants in db".$ebayAccount->id);
       //   Log::info("Creating ebay variants in db".$shopifyStore->id);
       //   Log::info("Creating ebay variants in db".$shopifyStore->user_id);
                   
          
         $variant_title = $pvariant->title;
         $variantData = array();
         $variantData["title"] = mb_convert_encoding($variant_title,'ISO-8859-1','utf-8');
         $variantData["ebay_item_id"] = $itemID;
         $variantData["sku"] = $pvariant->shopify_variant_id;
         $variantData["image"] = $vimage;
         $variantData["listing_variant_data"] = json_encode($listing_variant_data);
         $variantData["ebay_item_data"] = json_encode($ebayItemData);
         $variantData["listing_id"] = $listing->id;
         $variantData["account_id"] = $ebayAccount->id;
         $variantData["store_id"] = $shopifyStore->id;
         $variantData["user_id"] = $shopifyStore->user_id;
         $lvariant = $listing->variants()->create($variantData);

         if($pvariant->listing_variant_id != $lvariant->id){
             $pvariant->listing_variant_id = $lvariant->id;
             $pvariant->save();
         }

         if($lvariant->variant_id != $pvariant->id){
             $lvariant->variant_id = $pvariant->id;
             $lvariant->save();
         }
     }
}
          else{
        /////// Item is single variant ///////////// 

            $shopify_variant_id =  $ebayItemData["SKU"] ;
              $shopifyvar = $shopifyStore->variants()->where('shopify_variant_id',$shopify_variant_id)->first();
                if($ebayItemData["SKU"] == $shopifyvar->shopify_variant_id){
                $listing_variant_data = $ebayItemData;
                 
         }

       if(isset($ebayItemData["PictureDetails"]["PictureURL"])){
           //insert it in listing variant image colum
           $image =$ebayItemData["PictureDetails"]["PictureURL"];
       } 
       
           $variant_id = $pvariant->id;
     Log::info("111111111111111111111111111111 db".$variant_id);
     $listingVariant = $listing->variants()->where('variant_id',$variant_id)->first();
     if($listingVariant){
         Log::info("listingVariant found in db");
         $listingVariant->ebay_item_id = $itemID;
         $listingVariant->sku = $pvariant->shopify_variant_id;      ////////////////////////
         $listingVariant->ebay_item_data = json_encode($ebayItemData);
         $listingVariant->listing_variant_data = json_encode($listing_variant_data);
         $listingVariant->image = $image;

         $listingVariant->save();
     }
     else{ 
       //      Log::info("Creating ebay variants in db item id ".$itemID);
  //   Log::info("Creating ebay variants in db shopify_variant_id ".$pvariant->shopify_variant_id);
     //      Log::info("Creating ebay variants in db image ".json_encode($image,true));
    //      Log::info("Creating ebay variants in db listing_variant_data ".json_encode($listing_variant_data));
    //      Log::info("Creating ebay variants in db ebayItemData ".json_encode($ebayItemData));
       //   Log::info("Creating ebay variants in db listing id ". $listing->id);
       //   Log::info("Creating ebay variants in db account id ".$ebayAccount->id);
       //   Log::info("Creating ebay variants in db store id ".$shopifyStore->id);
       //   Log::info("Creating ebay variants in db user id ".$shopifyStore->user_id);
                   
          Log::info("Creating ebay variants in db");
         $variant_title = $pvariant->title;
         $variantData = array();
         $variantData["title"] = mb_convert_encoding($variant_title,'ISO-8859-1','utf-8');
         $variantData["ebay_item_id"] = $itemID;
         $variantData["sku"] = $pvariant->shopify_variant_id;          //////////////////////
         $variantData["image"] = is_array($image) ? $image[0] : $image ; 
         //$variantData["image"] = $image[0];
         $variantData["listing_variant_data"] = json_encode($listing_variant_data);
         $variantData["ebay_item_data"] = json_encode($ebayItemData);
         $variantData["listing_id"] = $listing->id;
         $variantData["account_id"] = $ebayAccount->id;
         $variantData["store_id"] = $shopifyStore->id;
         $variantData["user_id"] = $shopifyStore->user_id;
         $lvariant = $listing->variants()->create($variantData);

         if($pvariant->listing_variant_id != $lvariant->id){
             $pvariant->listing_variant_id = $lvariant->id;
             $pvariant->save();
         }

         if($lvariant->variant_id != $pvariant->id){
             $lvariant->variant_id = $pvariant->id;
             $lvariant->save();
         }
     }
         
         
     }


//////////////////////////////////////////////////////////*********************************************//////////////////////////////////////////////////////////////////
     

     
 //	if(!$listing_variant_data) continue;

// 		$vimage =null;

// 		if(isset($ebayItemData["Variations"]) && $ebayItemData["Variations"]){
// 			foreach($ebayItemData["Variations"]["Variation"] as $variation){
// 				if($variation["SKU"] == $pvariant->sku){
// 					$listing_variant_data = $variation;
// 					break;
// 				}
// 			}
//                      Log::info("listing  444444444444444444444444444 ");
// 			if(isset($ebayItemData["Variations"]["Pictures"]) && $ebayItemData["Variations"]["Pictures"]){
// 				$variationSpecificName = $ebayItemData["Variations"]["Pictures"][0]["VariationSpecificName"];
// 				foreach($ebayItemData["Variations"]["Pictures"][0]["VariationSpecificPictureSet"] as $picture){
// 					if($variationSpecificName == $option1Name && $picture["VariationSpecificValue"] == $shVariant["option1"]){
// 						$vimage = $picture["PictureURL"][0];break;
// 					}
// 					else if($variationSpecificName == $option2Name && $picture["VariationSpecificValue"] == $shVariant["option2"]){
// 						$vimage = $picture["PictureURL"][0];break;
// 					}
// 					else if($variationSpecificName == $option3Name && $picture["VariationSpecificValue"] == $shVariant["option3"]){
// 						$vimage = $picture["PictureURL"][0];break;
// 					}
// 				}
// 			}
// 		}


     //$variant_id = $pvariant->variant_id;
     
//              $variant_id = $pvariant->id;
//              Log::info("111111111111111111111111111111 db".$variant_id);
// 		$listingVariant = $listing->variants()->where('variant_id',$variant_id)->first();
// 		if($listingVariant){
// 		    Log::info("listingVariant found in db");
// 			$listingVariant->ebay_item_id = $itemID;
// 			//$listingVariant->sku = $pvariant->sku;
// 			$listingVariant->sku = $pvariant->shopify_variant_id;
// 			$listingVariant->ebay_item_data = json_encode($ebayItemData);
// 			$listingVariant->listing_variant_data = json_encode($listing_variant_data);
// 			$listingVariant->image = $vimage;

// 			$listingVariant->save();
// 		}
// 		else{
// 		     Log::info("Creating ebay variants in db");
// 			$variant_title = $pvariant->title;
// 			$variantData = array();
// 			$variantData["title"] = mb_convert_encoding($variant_title,'ISO-8859-1','utf-8');
// 			$variantData["ebay_item_id"] = $itemID;
// 			//$variantData["sku"] = $pvariant->sku;
// 			$variantData["sku"] = $pvariant->shopify_variant_id;
// 			$variantData["image"] = $vimage;
// 			$variantData["listing_variant_data"] = json_encode($listing_variant_data);
// 			$variantData["ebay_item_data"] = json_encode($ebayItemData);
// 			$variantData["listing_id"] = $listing->id;
// 			$variantData["account_id"] = $ebayAccount->id;
// 			$variantData["store_id"] = $shopifyStore->id;
// 			$variantData["user_id"] = $shopifyStore->user_id;
// 			$lvariant = $listing->variants()->create($variantData);

// 			if($pvariant->listing_variant_id != $lvariant->id){
// 				$pvariant->listing_variant_id = $lvariant->id;
// 				$pvariant->save();
// 			}

// 			if($lvariant->variant_id != $pvariant->id){
// 				$lvariant->variant_id = $pvariant->id;
// 				$lvariant->save();
// 			}
// 		}
 }
    
}



public function relistendproducts($ebayResponse,$ebayService,$shopifyStore,$ebay_token,$listing,$pendingPublish){
    $errorserr = array();

    if($ebayResponse && $ebayResponse->Ack !== 'Failure'){
  echo 'working' ;
  echo $ebayResponse->ItemID ;
        $newItemID = $ebayResponse->ItemID;
    $relistParentID = $listing->ebay_item_id;
    try{
        $ebayItemRequest = new Types\GetItemRequestType();
        $ebayItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
        $ebayItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
        $ebayItemRequest->ItemID = $relistParentID;  
        $ebayItemRequest->IncludeItemSpecifics = true;
        //$ebayItemRequest->DetailLevel = "ReturnAll";

        sleep(2);
        $ebayItemResponse = $ebayService->getItem($ebayItemRequest);
        $ebayItemResponse = $ebayItemResponse->toArray();
        if(isset($ebayItemResponse["Item"]) && $ebayItemResponse["Item"]){
         Log::info('This is the ebay item response for relist'.json_encode($ebayItemResponse["Item"],true));
            $rebayItem = $ebayItemResponse["Item"];
            $listing_url =  $ebayItemResponse["ViewItemURL"];
            $relistedItemID = (isset($rebayItem["ListingDetails"]["RelistedItemID"])) ? (string) $rebayItem["ListingDetails"]["RelistedItemID"] : "";
                Log::info('This is the ebay item response for relist'.json_encode($rebayItem,true));
            // Log::info('This is the relist Parent ID  '.$relistParentID);
            // Log::info('This is the relisted item id  '.$relistedItemID);
            // Log::info('This is the new Item ID  '.$newItemID);
            // if($relistedItemID == $newItemID){
            // 	$isFailed = false;
            // 	Log::info('relistedItemID is equals to newItemID for relistParentID'.$relistParentID);
            // 	$listing->ebay_item_id = $newItemID;
            // //	$listing->sku = $rebayItem['SKU'];   //need to insert only if product is single variant in mnultivar case we put Multivariant
            // 	$listing->save();

            // 	$listingVariants = $listing->variants()->get();
            // // 	if($listingVariants->count() > 0){
            // // 		foreach($listingVariants as $listingVariant){
            // // 			$listingVariant->ebay_item_id = $newItemID; //need to update sku for every variant accordance with its shopify variant id
            // // 			$listingVariant->save();
            // // 		}
            // // 	}
            
////////////////////////////////////////////////////*******************************/////////////////////////////////////////////////////////////////////////


           if($relistedItemID == $newItemID){
                $isFailed = false;
                Log::info('relistedItemID is equals to newItemID for relistParentID'.$relistParentID);
                $listingVariants = $listing->variants()->get();
        Log::info('This is the ebay item response'.$relistedItemID);
            if($listingVariants->count() == 1){
                Log::info('product is single variant for relistParentID'.$relistParentID);
             $listing->ebay_item_id = $newItemID;
                $listing->sku = "Singlevariant"; 
                $listing->listing_data = json_encode($rebayItem); /// by hitesh mali
                $listing->listing_url = $listing_url;
                $listing->save();
                
                 Log::info('saved in listing table for single');
             $listingVariants->ebay_item_id = $newItemID;
             $listingVariants->sku = $rebayItem['SKU'];
                $listingVariants->save();
                 Log::info('saved in listing_var table for single');
          }
            elseif($listingVariants->count() > 1){
                    Log::info('This is the ebay item response'.$listingVariants->count());
                 Log::info('product is multi variant for relistParentID'.$relistParentID);
                  $listing->ebay_item_id = $newItemID;
                $listing->sku = "Multivariant"; 
                $listing->listing_url = $listing_url;
                 $listing->listing_data = json_encode($rebayItem);
                $listing->save();
             Log::info('saved in listing table for multi');
             foreach($listingVariants as $listingVariant){

                $shopify_var = $shopifyStore->variants()->where('id',$listingVariant->variant_id)->first();
                if($shopify_var->shopify_variant_id == $listingVariant->sku){
                 $listingVariant->ebay_item_id = $newItemID; 
                    $listingVariant->save();
                }else{
                  $listingVariant->sku = $shopify_var->shopify_variant_id ;
                 $listingVariant->ebay_item_id = $newItemID; 
                    $listingVariant->save();
                }
                Log::info('saved in listing_var table for multi');

          }


            
        }
           }
            
////////////////////////////////////////////////////*******************************/////////////////////////////////////////////////////////////////////////								
            else{
            // 	$errors[] = array(
            // 		"errortype"=>"ebay api error",
            // 		"msg"=>"relistParentID item id mapping issue | ".json_encode($rebayItem),
            // 		"item_id"=> $newItemID,
            // 		"relistParentID"=> $relistParentID
            // 	);
                $errors = array(
                    "errortype"=>"ebay api error",
                    "msg"=>"relistParentID item id mapping issue | ".json_encode($rebayItem),
                    "item_id"=> $newItemID,
                    "relistParentID"=> $relistParentID
                );
                return   $errors;
                $pendingPublish->delete(); //TODO the same for all errors 
            }
        }
        else{
            //$errors[] = array(
                    $errors = array(
                "errortype" => "ebay api error",
                "msg" => "failed to get relistParentID | ",
                "item_id" => $newItemID,
                "relistParentID" => $relistParentID
            );
            return   $errors;
        }
    }
    catch(\Exception $e){
        //$errors[] = array(
                $errors = array(
            "errortype" => "Exception - get relist item",
            "msg" => $e->getMessage(),
            "item_id" => $newItemID,
            "relistParentID" => $relistParentID
        );
    }
}
    echo '  not working check hitesh';
}
	public function verifyEbayItem($product_id, $profile_id, $ebayAccount, $shopifyStore, $ebayService = null){
		try {
		      Log::info('enetered in verifyEbayItem  ');
			$ebay_environment = config('ebay.environment');
			if ($shopifyStore->user_id == 2)
				$ebay_environment = "sandbox";

			$ebayCredentials = array(
				'credentials' => [
					'devId' => config('ebay.' . $ebay_environment . 'devid'),
					'appId' => config('ebay.' . $ebay_environment . 'appid'),
					'certId' => config('ebay.' . $ebay_environment . 'certid'),
				],
				'authToken' => '',
				'oauthUserToken' => '',
				'ruName' => config('ebay.' . $ebay_environment . 'RuName')
			);
			$ebay_token = $ebayAccount->access_token;
			$site_id = (isset($ebayAccount->siteid)) ? (int) $ebayAccount->siteid : Constants\SiteIds::US;

			if (!$ebayService) {
				$ebayService = new Services\TradingService([
					'credentials' => $ebayCredentials['credentials'],
					'sandbox' => ($ebay_environment == "sandbox") ? true : false,
					'siteId' => $site_id
				]);
			}
             Log::info('finding products info in db for product id '.$product_id);
			$product = $shopifyStore->products()->with('variants')->with('productData')->find($product_id);
			$profile = $shopifyStore->profiles()->with('template')->with('returnProfile')->with('shippingProfile')->with('paymentProfile')->with('storeCategory')->with('category1')->with('category2')->find($profile_id);
			if ($product && $profile && $profile->category1) {
            Log::info('products and profile category found');
				$productData = [];
				if ($product->productData->count() > 0) {
					foreach ($product->productData as $proData) {
						if ($proData->profile_id == $profile->id) {
							$productData = $proData;
							break;
						}
					}
					if (!$productData) {
						foreach ($product->productData as $proData) {
							if (!$proData->profile_id) {
								$productData = $proData;
								break;
							}
						}
					}
					if ($productData)
						$productData->item_specific_values = json_decode($productData->item_specific_values);
				}

				$listing = [];
				if ($product->listing_id)
				Log::info('finding listing for the listing id '.$product->listing_id);
					$listing = $shopifyStore->listings()->with('variants')->find($product->listing_id);

				$shProduct = json_decode($product->shopify_product_data, true);


				$option1name = (isset($shProduct["options"][0]["name"])) ? strtolower($shProduct["options"][0]["name"]) : NULL;
				$option2name = (isset($shProduct["options"][1]["name"])) ? strtolower($shProduct["options"][1]["name"]) : NULL;
				$option3name = (isset($shProduct["options"][2]["name"])) ? strtolower($shProduct["options"][2]["name"]) : NULL;


				$option1name_l = strtolower($option1name);
				$option2name_l = strtolower($option2name);
				$option3name_l = strtolower($option3name);

				$tags = $shProduct["tags"];
				$variants = $product->variants;
				$shVariants = $shProduct["variants"];

				$listing_format = $profile->listing_format;

				$ebayRequest = ($listing_format == "auction") ? new Types\VerifyAddItemRequestType() : new Types\VerifyAddFixedPriceItemRequestType();
                 Log::info('Creating ebay request for verify item '.$product_id);
				$ebayRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
				$ebayRequest->RequesterCredentials->eBayAuthToken = $ebay_token;

				$ebayItem = new Types\ItemType();

				$listing_duration = $profile->listing_duration;

				if ($listing_format == "auction") {
				    Log::info('Listing type is auction for product id  '.$product_id);
					$ebayItem->ListingType = Enums\ListingTypeCodeType::C_CHINESE;
					$ebayItem->ListingDuration = ($listing_duration) ? $listing_duration : Enums\ListingDurationCodeType::C_DAYS_7;
				} else {
				       Log::info('Listing type is not auction for product id  '.$product_id);
					$ebayItem->ListingType = Enums\ListingTypeCodeType::C_FIXED_PRICE_ITEM;
					$ebayItem->ListingDuration = ($listing_duration) ? $listing_duration : Enums\ListingDurationCodeType::C_GTC;
				}

				if ($listing) $ebayItem->ItemID = $listing->ebay_item_id;
				  //Log::info('Product found in listings for product idddddd  '.$product_id.' and ebay item id '.json_encode($listing,true));
				 // Log::info('idddddd  '.$product_id.' and ebay item id '.json_encode($listing,true));
				//	$ebayItem->ItemID = $listing->ebay_item_id;

				$listing_title = ($profile->listing_title) ? $profile->listing_title : $shProduct["title"];

				if ($productData && $productData->title)
					$listing_title = $productData->title;
				else if (!$profile->listing_title && $profile->trim_title == 1) {
					$listing_title = substr($listing_title, 0, 80);
				}
				Log::info("title " . $listing_title);

				$ebayItem->Title = $listing_title;

				if ($profile->template && $profile->template->template_data) {
					$ebayItem->Description = str_replace("{{description}}", $shProduct["body_html"], $profile->template->template_data);
				} else {
					$ebayItem->Description = $shProduct["body_html"];
				}

				//$ebayItem->Description = "dddddddddddd ddddddddddddd";

				//$ebayCategory1 = EbayCategory::where("category_id",$ebayData->ebay_category_1)->first();
				//$ebayCategory2 = EbayCategory::where("category_id",$ebayData->ebay_category_2)->first();

				if ($profile->category1) {
					$ebayItem->PrimaryCategory = new Types\CategoryType();
					$ebayItem->PrimaryCategory->CategoryID = $profile->category1->ebay_category_id;
				}

				if ($profile->category2) {
					$ebayItem->SecondaryCategory = new Types\CategoryType();
					$ebayItem->SecondaryCategory->CategoryID = $profile->category2->ebay_category_id;
				}

				if ($profile->storeCategory) {
					$ebayItem->Storefront = new Types\StorefrontType();
					$ebayItem->Storefront->StoreCategoryID = (int) $profile->storeCategory->ebay_category_id;
					$ebayItem->Storefront->StoreCategoryName = $profile->storeCategory->category_name;
				}

				$ebayItem->Country = EbayHelper::getEbayCountry($site_id);
				if ($profile->postal_code)
					$ebayItem->PostalCode = (string) $profile->postal_code;
				if ($profile->item_location)
					$ebayItem->Location = trim($profile->item_location);
				$ebayItem->Currency = EbayHelper::getEbayCurrency($site_id);


				if ($productData && $productData->condition) {
					if ($productData->condition == 'New')
						$ebayItem->ConditionID = 1000;
					else if ($productData->condition == 'Used')
						$ebayItem->ConditionID = 3000;
					else if ($productData->condition == 'Good')
						$ebayItem->ConditionID = 5000;
					else if ($productData->condition == 'Very Good')
						$ebayItem->ConditionID = 4000;
					else if ($productData->condition == 'Like New')
						$ebayItem->ConditionID = 2750;
					else if ($productData->condition == 'New other (see details)')
						$ebayItem->ConditionID = 1500;
					else if ($productData->condition == 'New with defects')
						$ebayItem->ConditionID = 1750;
					else if ($productData->condition == 'Certified - Refurbished')
						$ebayItem->ConditionID = 2000;
					else if ($productData->condition == 'Excellent - Refurbished')
						$ebayItem->ConditionID = 2010;
					else if ($productData->condition == 'Very Good - Refurbished')
						$ebayItem->ConditionID = 2020;
					else if ($productData->condition == 'Good - Refurbished')
						$ebayItem->ConditionID = 2030;
					else if ($productData->condition == 'Seller refurbished')
						$ebayItem->ConditionID = 2500;
					else if ($productData->condition == 'Acceptable')
						$ebayItem->ConditionID = 6000;
					else if ($productData->condition == 'For parts or not working')
						$ebayItem->ConditionID = 7000;
				} else
					$ebayItem->ConditionID = 1000  ;

				if ($productData && $productData->condition_note)
					$ebayItem->ConditionDescription = $productData->condition_note;



				$vendor = $shProduct["vendor"];
				$item_specifics = ($profile->item_specifics) ? json_decode($profile->item_specifics, true) : null;
				$manuf_part_no = ($variants[0]->sku) ? $variants[0]->sku : $shVariants[0]["sku"];

				if ($productData && $productData->item_specific_values) {
					if (isset($productData->item_specific_values->brand) && $productData->item_specific_values->brand) {
						$vendor = $productData->item_specific_values->brand;
					}

					if (isset($productData->item_specific_values->mpn) && $productData->item_specific_values->mpn) {
						$manuf_part_no = $productData->item_specific_values->mpn;
					}
				}


				if ($vendor || $manuf_part_no || $item_specifics) {
					$itemSpecificsSet = new Types\NameValueListArrayType();
					if ($vendor) {
						$itemSpecificNameValue = new Types\NameValueListType();
						$itemSpecificNameValue->Name = 'Brand';
						$itemSpecificNameValue->Value = array($vendor);
						$itemSpecificsSet->NameValueList[] = $itemSpecificNameValue;
					}

					if ($manuf_part_no) {
						$itemSpecificNameValue = new Types\NameValueListType();
						$itemSpecificNameValue->Name = 'MPN';
						$itemSpecificNameValue->Value = array($manuf_part_no);
						$itemSpecificsSet->NameValueList[] = $itemSpecificNameValue;
					}

					if ($item_specifics) {
						foreach ($item_specifics as $item_specific_key => $item_specific_value) {
							$item_specific_key_l = strtolower($item_specific_key);
							if ($item_specific_key_l == $option1name_l || $item_specific_key_l == $option2name_l || $item_specific_key_l == $option3name_l)
								continue;

							$item_specific_value = trim($item_specific_value);
							if ($item_specific_value !== "") {
								$itemSpecificNameValue = new Types\NameValueListType();
								$itemSpecificNameValue->Name = $item_specific_key;
								$itemSpecificNameValue->Value = array($item_specific_value);
								$itemSpecificsSet->NameValueList[] = $itemSpecificNameValue;
							}
						}
					}

					$ebayItem->ItemSpecifics = $itemSpecificsSet;
				}


				$ebayImagesMappings = array();

				$extraImages = array();
				$hasVariantImages = false;
				$addedVariantImages = array();

				$listdetailsadded = false;




				if ($option1name && (count($shVariants) > 1 || strtolower($shVariants[0]["option1"]) != "default title") && $shVariants[0]["option1"] && $listing_format != "auction") {

					$ebayItem->Variations = new Types\VariationsType();
					$option1Name = $option1name;
					$option1Values = array();

					$option2Name = $option2name;
					$option2Values = array();

					$option3Name = $option3name;
					$option3Values = array();

					foreach ($shVariants as $shVariant) {
						$pvariant = [];
						foreach ($variants as $variant) {
							if ($variant->shopify_variant_id == $shVariant["id"]) {
								$pvariant = $variant;
								break;
							}
						}

						if (!$pvariant)
							continue;

						if ($shVariant["option1"] && !in_array($shVariant["option1"], $option1Values)) {
							$option1Values[] = $shVariant["option1"];
						}
						if ($shVariant["option2"] && !in_array($shVariant["option2"], $option2Values)) {
							$option2Values[] = $shVariant["option2"];
						}
						if ($shVariant["option3"] && !in_array($shVariant["option3"], $option3Values)) {
							$option3Values[] = $shVariant["option3"];
						}
					}
					$variationSpecificsSet = new Types\NameValueListArrayType();

					$optionNameValue = new Types\NameValueListType();
					$optionNameValue->Name = $option1Name;
					$optionNameValue->Value = $option1Values;
					$variationSpecificsSet->NameValueList[] = $optionNameValue;

					if ($option2Name && $option2Values) {
						$optionNameValue = new Types\NameValueListType();
						$optionNameValue->Name = $option2Name;
						$optionNameValue->Value = $option2Values;
						$variationSpecificsSet->NameValueList[] = $optionNameValue;

						if ($option3Name && $option3Values) {
							$optionNameValue = new Types\NameValueListType();
							$optionNameValue->Name = $option3Name;
							$optionNameValue->Value = $option3Values;
							$variationSpecificsSet->NameValueList[] = $optionNameValue;
						}
					}
					$ebayItem->Variations->VariationSpecificsSet = $variationSpecificsSet;

					foreach ($shVariants as $shVariant) {

						$pvariant = [];
						foreach ($variants as $variant) {
							if ($variant->shopify_variant_id == $shVariant["id"]) {
								$pvariant = $variant;
								break;
							}
						}

						if (!$pvariant)
							continue;


						$itemVariation = new Types\VariationType();
						$itemVariation->SKU = $pvariant->sku;




						$vquantity = (int) $pvariant->quantity;

						$lvarqty = $vquantity;

						$listing_quantity_value = (int) $ebayAccount->listing_quantity_value;
						if ($ebayAccount->listing_quantity == 1 && $lvarqty > $listing_quantity_value)
							$lvarqty = $listing_quantity_value;
						if ($ebayAccount->threshold_quantity == 1 && $lvarqty <= $ebayAccount->threshold_quantity_value)
							$lvarqty = 0;


						if ($lvarqty < 0)
							$lvarqty = 0;
						//if($lvarqty < 0) continue;
						if ($shopifyStore->user_id == 7)
							$lvarqty = 1;

                	if ($shopifyStore->id == 1460){
                	      log::info(" shopify store id is 1460 ");
                	    $lvarqty = 1;
                	}
                	
						$lvarpr = (float) $pvariant->price;
						$lvmsrp = (float) $pvariant->compare_at_price;

						if ($ebayAccount->pricing_mark_up == 1) {
							if ($ebayAccount->pricing_mark_up_type == "percentage") {
								$lvarpr = $lvarpr + (($ebayAccount->pricing_mark_up_value / 100) * $lvarpr);
								$lvmsrp = $lvmsrp + (($ebayAccount->pricing_mark_up_value / 100) * $lvmsrp);
							} else if ($ebayAccount->pricing_mark_up_type == "fixed") {
								$lvarpr = $lvarpr + $ebayAccount->pricing_mark_up_value;
								$lvmsrp = $lvmsrp + $ebayAccount->pricing_mark_up_value;
							}
						}
						 
						 log::info(" this is the quantity for store_id $shopifyStore->id -> ".$lvarqty );
						 
						$lvarpr = number_format($lvarpr, 2, '.', '');
						$lvmsrp = number_format($lvmsrp, 2, '.', '');
						$itemVariation->Quantity = ($lvarqty > 5 && $shopifyStore->id == 8) ? 5 : $lvarqty;

						$itemVariation->StartPrice = new Types\AmountType(['value' => (float) $lvarpr]);





						if ($profile->product_id_type && $pvariant->product_id_val && $ebay_environment != "sandbox") {
							$itemVariation->VariationProductListingDetails = new Types\VariationProductListingDetailsType();
							if ($profile->product_id_type == "ISBN") {
								$itemVariation->VariationProductListingDetails->ISBN = $pvariant->product_id_val;
							} else if ($profile->product_id_type == "UPC") {
							    
							    	 if($shopifyStore->user_id == 1013 || $shopifyStore->user_id == 1402 ||  $shopifyStore->user_id == 1555  || $shopifyStore->user_id == 1444 || $shopifyStore->user_id == 1468 || $shopifyStore->user_id == 1469 ){
							     	$itemVariation->VariationProductListingDetails->UPC = "";
							    }else{
							 	$itemVariation->VariationProductListingDetails->UPC = $pvariant->product_id_val;
							    }
							    
							    
							
							} else if ($profile->product_id_type == "EAN") {
								$itemVariation->VariationProductListingDetails->EAN = $pvariant->product_id_val;
							} else if ($profile->product_id_type == "MPN" && $vendor) {
								$brandMPN = new Types\BrandMPNType();
								$brandMPN->Brand = $vendor;
								$brandMPN->MPN = $pvariant->product_id_val;
								$itemVariation->VariationProductListingDetails->BrandMPN = $brandMPN;
							}
						}


						$variationSpecifics = new Types\NameValueListArrayType();

						$optionNameValue = new Types\NameValueListType();
						$optionNameValue->Name = $option1Name;
						$optionNameValue->Value = [$shVariant["option1"]];
						$variationSpecifics->NameValueList[] = $optionNameValue;

						if ($shVariant["option2"] && $option2Name) {
							$optionNameValue = new Types\NameValueListType();
							$optionNameValue->Name = $option2Name;
							$optionNameValue->Value = [$shVariant["option2"]];
							$variationSpecifics->NameValueList[] = $optionNameValue;

							if ($shVariant["option3"] && $option3Name) {
								$optionNameValue = new Types\NameValueListType();
								$optionNameValue->Name = $option3Name;
								$optionNameValue->Value = [$shVariant["option3"]];
								$variationSpecifics->NameValueList[] = $optionNameValue;
							}
						}
						$itemVariation->VariationSpecifics[] = $variationSpecifics;
						$ebayItem->Variations->Variation[] = $itemVariation;
					}

				} else {

					$pvariant = $variants[0];

					$vquantity = (int) $pvariant->quantity;

					$lvarqty = $vquantity;

					$listing_quantity_value = (int) $ebayAccount->listing_quantity_value;
					if ($ebayAccount->listing_quantity == 1 && $lvarqty > $listing_quantity_value)
						$lvarqty = $listing_quantity_value;
					if ($ebayAccount->threshold_quantity == 1 && $lvarqty <= $ebayAccount->threshold_quantity_value)
						$lvarqty = 0;


					if ($lvarqty < 0)
						$lvarqty = 0;
					//if($lvarqty <= 0) return ["error" => "inventory quantity must be greater than 0"];

					$lvarpr = (float) $pvariant->price;
					$lvmsrp = (float) $pvariant->compare_at_price;

					if ($shopifyStore->user_id == 7)
						$lvarqty = 1;
						
						
						
						
                     if ($shopifyStore->id == 1460){
                           log::info(" shopify store id is 1460 ");
                	    $lvarqty = 1;
                  	}
 
					if ($ebayAccount->pricing_mark_up == 1) {
						if ($ebayAccount->pricing_mark_up_type == "percentage") {
							$lvarpr = $lvarpr + (($ebayAccount->pricing_mark_up_value / 100) * $lvarpr);
							$lvmsrp = $lvmsrp + (($ebayAccount->pricing_mark_up_value / 100) * $lvmsrp);
						} else if ($ebayAccount->pricing_mark_up_type == "fixed") {
							$lvarpr = $lvarpr + $ebayAccount->pricing_mark_up_value;
							$lvmsrp = $lvmsrp + $ebayAccount->pricing_mark_up_value;
						}
					}
					
                   log::info(" this is the quantity for store_id $shopifyStore->id -> ".$lvarqty );
					$ebayItem->Quantity = ($listing_format == "auction") ? 1 : $lvarqty;

					$ebayItem->StartPrice = new Types\AmountType(['value' => (float) $lvarpr]);
					$ebayItem->SKU = $pvariant->sku;



					if (isset($item_specifics["buy_it_now_price"]) && $item_specifics["buy_it_now_price"] > 0) {
						$ebayItem->BuyItNowPrice = new Types\AmountType(['value' => $item_specifics["buy_it_now_price"]]);
					}


					if ($profile->product_id_type && $pvariant->product_id_val && $ebay_environment != "sandbox") {
						$listdetailsadded = true;
						$ebayItem->ProductListingDetails = new Types\ProductListingDetailsType();
						if ($profile->product_id_type == "ISBN") {
							$ebayItem->ProductListingDetails->ISBN = $pvariant->product_id_val;
						} else if ($profile->product_id_type == "UPC") {
						    
						       	 if($shopifyStore->user_id == 1013 || $shopifyStore->user_id == 1402  ||  $shopifyStore->user_id == 1555 || $shopifyStore->user_id == 1444 || $shopifyStore->user_id == 1468 || $shopifyStore->user_id == 1469 ){
							     	$ebayItem->ProductListingDetails->UPC = "";
							    }else{
							 	$ebayItem->ProductListingDetails->UPC = $pvariant->product_id_val;
							    }
						    
						
						} else if ($profile->product_id_type == "EAN") {
							$ebayItem->ProductListingDetails->EAN = $pvariant->product_id_val;
						} else if ($profile->product_id_type == "MPN" && $vendor) {
							$brandMPN = new Types\BrandMPNType();
							$brandMPN->Brand = $vendor;
							$brandMPN->MPN = $pvariant->product_id_val;
							$ebayItem->ProductListingDetails->BrandMPN = $brandMPN;
						}
					}

				}


				if ($profile->product_id_type != "MPN" && $vendor && $manuf_part_no && $ebay_environment != "sandbox") {
					if (!$listdetailsadded)
						$ebayItem->ProductListingDetails = new Types\ProductListingDetailsType();
					$brandMPN = new Types\BrandMPNType();
					$brandMPN->Brand = $vendor;
					$brandMPN->MPN = $manuf_part_no;
					$ebayItem->ProductListingDetails->BrandMPN = $brandMPN;
				}


				if ($shProduct["images"] && $shProduct["images"]) {
					$ebayItem->PictureDetails = new Types\PictureDetailsType();
					$ebayItem->PictureDetails->GalleryType = Enums\GalleryTypeCodeType::C_GALLERY;
					$imagesUrl = array();
					foreach ($shProduct["images"] as $image) {
						$imagesUrl[] = $image["src"];
						if (count($imagesUrl) >= 12)
							break;
					}
					$ebayItem->PictureDetails->PictureURL = $imagesUrl;
				}



				$paymentProfile = null;
				$shippingProfile = null;
				$returnProfile = null;
				if ($profile->paymentProfile) {
					$paymentProfile = new Types\SellerPaymentProfileType();
					$paymentProfile->PaymentProfileID = (int) $profile->paymentProfile->seller_profile_id;
				}

				if ($profile->shippingProfile) {
					$shippingProfile = new Types\SellerShippingProfileType();
					$shippingProfile->ShippingProfileID = (int) $profile->shippingProfile->seller_profile_id;
				}

				if ($profile->returnProfile) {
					$returnProfile = new Types\SellerReturnProfileType();
					$returnProfile->ReturnProfileID = (int) $profile->returnProfile->seller_profile_id;
				}

				if ($paymentProfile || $shippingProfile || $returnProfile) {
					$ebayItem->SellerProfiles = new Types\SellerProfilesType();
					if ($shippingProfile) {
						$ebayItem->SellerProfiles->SellerShippingProfile = $shippingProfile;
					}

					if ($paymentProfile) {
						$ebayItem->SellerProfiles->SellerPaymentProfile = $paymentProfile;
					}

					if ($returnProfile) {
						$ebayItem->SellerProfiles->SellerReturnProfile = $returnProfile;
					}
				}

				$payment_methods = ($profile->payment_methods) ? json_decode($profile->payment_methods, true) : array();


				if (!$paymentProfile && $payment_methods) {
					$ebayItem->PaymentMethods = $payment_methods;
					if (in_array("PayPal", $payment_methods) && $profile->paypal_email)
						$ebayItem->PayPalEmailAddress = $profile->paypal_email;
				}

				if (!$returnProfile) {
					$ebayItem->ReturnPolicy = new Types\ReturnPolicyType();
					if (($profile->return_policy_details) && ($site_id == 77 || $site_id == 16 || $site_id == 71 || $site_id == 101 || $site_id == 186))
						$ebayItem->ReturnPolicy->Description = $profile->return_policy_details;

					$ebayItem->ReturnPolicy->ReturnsAcceptedOption = $profile->domestic_returns_accepted;
					if ($profile->domestic_returns_accepted == "ReturnsAccepted") {
						$ebayItem->ReturnPolicy->RefundOption = $profile->domestic_refund_given_as;
						$ebayItem->ReturnPolicy->ReturnsWithinOption = $profile->domestic_returned_within;
						$ebayItem->ReturnPolicy->ShippingCostPaidByOption = $profile->domestic_returns_paid_by;
					}
					if ($profile->international_returns_accepted && $profile->international_returns_accepted != "ReturnsNotAccepted") {
						$ebayItem->ReturnPolicy->InternationalReturnsAcceptedOption = $profile->international_returns_accepted;
						$ebayItem->ReturnPolicy->InternationalRefundOption = $profile->international_refund_given_as;
						$ebayItem->ReturnPolicy->InternationalReturnsWithinOption = $profile->international_returned_within;
						$ebayItem->ReturnPolicy->InternationalShippingCostPaidByOption = $profile->international_returns_paid_by;
					} else {
						//$ebayItem->ReturnPolicy->InternationalReturnsAcceptedOption = "ReturnsNotAccepted";
					}
				}


				if (!$shippingProfile) {
					$ebayItem->ShippingDetails = new Types\ShippingDetailsType();

					$domestic_shipping = $profile->domestic_shipping;
					$intl_shipping = $profile->intl_shipping;
					if ($domestic_shipping && $domestic_shipping != "NotSpecified" && $domestic_shipping != "NOT_SPECIFIED") {

						$domestic_ships_within_handling_days = (int) $profile->domestic_ships_within_handling_days;

						if ($domestic_ships_within_handling_days !== "" && $domestic_ships_within_handling_days >= 0)
							$ebayItem->DispatchTimeMax = $domestic_ships_within_handling_days;

						if ($domestic_shipping == "Flat" && $intl_shipping == "Calculated") {
							$ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_FLAT_DOMESTIC_CALCULATED_INTERNATIONAL;
						} else if ($domestic_shipping == "Calculated" && $intl_shipping == "Flat") {
							$ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_CALCULATED_DOMESTIC_FLAT_INTERNATIONAL;
						} else if ($domestic_shipping == "Flat" || $intl_shipping == "Flat") {
							$ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_FLAT;
						} else if ($domestic_shipping == "Calculated" || $intl_shipping == "Calculated") {
							$ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_CALCULATED;
						} else if ($domestic_shipping == "Freight") {
							$ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_FREIGHT;
						} else if ($domestic_shipping == "FreightFlat") {
							$ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_FREIGHT_FLAT;
						}


						if ($domestic_shipping == "Calculated" || $intl_shipping == "Calculated") {
							$ebayItem->ShippingDetails->CalculatedShippingRate = new Types\CalculatedShippingRateType();

							if ($domestic_shipping == "Calculated") {
								$ebayItem->ShippingDetails->CalculatedShippingRate->PackagingHandlingCosts = new Types\AmountType(['value' => $profile->domestic_pkg_handling_fee]);
							}
							if ($intl_shipping == "Calculated") {
								$ebayItem->ShippingDetails->CalculatedShippingRate->InternationalPackagingHandlingCosts = new Types\AmountType(['value' => $profile->intl_pkg_handling_fee]);
							}
							$ebayItem->ShippingDetails->CalculatedShippingRate->OriginatingPostalCode = (string) $profile->postal_code;

							$packageDetails = new Types\ShipPackageDetailsType();
							$packageDetails->ShippingPackage = 'PackageThickEnvelope';
							$packageDetails->MeasurementUnit = Enums\MeasurementSystemCodeType::C_ENGLISH;
							$packageDetails->ShippingIrregular = true;

							$packageDetails->WeightMajor = new Types\MeasureType();
							$packageDetails->WeightMinor = new Types\MeasureType();


                        if ($shVariants[0]["grams"] < 1000 ){
							              //////////////////////////////////////
					 if($shopifyStore->id == 1296){
					     log::info(" publishing for 1296 ".$shVariants[0]["grams"]);
                       $packageDetails->WeightMinor->unit = "g";
               $packageDetails->WeightMinor->value = $shVariants[0]["grams"];

                 $packageDetails->WeightMajor->unit =  "kg";
                  $packageDetails->WeightMajor->value =0;
                  }
                  ///////////////////////////////////////////////
							              
							              
                            $packageDetails->WeightMinor->unit = "g";
                           $packageDetails->WeightMinor->value = 1;//$shVariants[0]["grams"];

                             $packageDetails->WeightMajor->unit =  "kg";
                            $packageDetails->WeightMajor->value =0;//ceil($shVariants[0]["weight"]);
                   
                           Log::info("shipping profile else if side".json_encode($packageDetails,true));
                        }
                     else{
                $packageDetails->WeightMinor->unit = "g";
               $packageDetails->WeightMinor->value = 0;

                 $packageDetails->WeightMajor->unit =  "kg";
                  $packageDetails->WeightMajor->value =$shVariants[0]["grams"];
                 Log::info("shipping profile else side".json_encode($shVariants[0]));
                  Log::info("shipping profile else side".json_encode($packageDetails,true));
                 
                  if($shopifyStore->user_id == 447 && $packageDetails->WeightMajor->unit =  "kg" &&  $packageDetails->WeightMajor->value >65) {
                       $packageDetails->WeightMinor->unit = "g";
               $packageDetails->WeightMinor->value = 0;

                 $packageDetails->WeightMajor->unit =  "kg";
                  $packageDetails->WeightMajor->value =65;
                  }
                    if($shopifyStore->user_id == 584) {
                     $packageDetails->WeightMinor->unit = "g";
               $packageDetails->WeightMinor->value = 0;

                 $packageDetails->WeightMajor->unit =  "kg";
                  $packageDetails->WeightMajor->value =65;
                  }
             }
   
   
				// 			if ($shVariants[0]["grams"] < 1000) {

				// 				$packageDetails->WeightMinor->unit = "g";
				// 				$packageDetails->WeightMinor->value = $shVariants[0]["grams"];

				// 				$packageDetails->WeightMajor->unit = "kg";
				// 				$packageDetails->WeightMajor->value = 0; //ceil($shVariants[0]["weight"]);
				// 			} else {
				// 				$packageDetails->WeightMinor->unit = "g";
				// 				$packageDetails->WeightMinor->value = 0;

				// 				$packageDetails->WeightMajor->unit = "kg";
				// 				$packageDetails->WeightMajor->value = $shVariants[0]["grams"];
				// 			}

							$ebayItem->ShippingPackageDetails = $packageDetails;
						}

						if ($profile->domestic_ship_service1 && $profile->domestic_ship_service1 != "NotSelected" && $profile->domestic_shipping != "NotSpecified") {
							$shippingService = new Types\ShippingServiceOptionsType();
							$shippingService->ShippingServicePriority = 1;
							$shippingService->ShippingService = $profile->domestic_ship_service1;
							if ($domestic_shipping == "Flat") {
								$shippingService->ShippingServiceCost = new Types\AmountType(['value' => (float) $profile->ship_fee1]);
								if ($profile && isset($profile->x_ship_fee1) && $profile->x_ship_fee1 !== NULL && $profile->x_ship_fee1 !== "") {
									$shippingService->ShippingServiceAdditionalCost = new Types\AmountType(['value' => (float) $profile->x_ship_fee1]);
								}
							}
							if ($profile->domestic_free_shipping)
								$shippingService->FreeShipping = true;
							if ($profile->domestic_local_pickup) {
								$shippingService->LocalPickup = true;
							} else {
								$shippingService->LocalPickup = false;
							}
							$ebayItem->ShippingDetails->ShippingServiceOptions[] = $shippingService;
						}
						$domestic_ship_additional_services = ($profile->domestic_ship_additional_services) ? json_decode($profile->domestic_ship_additional_services) : array();
						if ($domestic_ship_additional_services) {
							$pr = 2;
							foreach ($domestic_ship_additional_services as $dsservice) {
								if (isset($dsservice->domestic_ship_service1) && $dsservice->domestic_ship_service1 && $dsservice->domestic_ship_service1 != "NOT_SPECIFIED" && $dsservice->domestic_ship_service1 != "NotSpecified" && $dsservice->domestic_ship_service1 != "NotSelected") {

									$shippingService = new Types\ShippingServiceOptionsType();
									$shippingService->ShippingServicePriority = $pr;
									$shippingService->ShippingService = $dsservice->domestic_ship_service1;
									if ($domestic_shipping == "Flat") {
										$shippingService->ShippingServiceCost = new Types\AmountType(['value' => (float) $dsservice->ship_fee1]);
										if ($dsservice && isset($dsservice->x_ship_fee1) && $dsservice->x_ship_fee1 !== NULL && $dsservice->x_ship_fee1 !== "") {
											$shippingService->ShippingServiceAdditionalCost = new Types\AmountType(['value' => (float) $dsservice->x_ship_fee1]);
										}
									}
									if (isset($dsservice->domestic_free_shipping) && $dsservice->domestic_free_shipping)
										$shippingService->FreeShipping = true;
									if (isset($dsservice->domestic_local_pickup) && $dsservice->domestic_local_pickup) {
										$shippingService->LocalPickup = true;
									} else {
										$shippingService->LocalPickup = false;
									}
									$ebayItem->ShippingDetails->ShippingServiceOptions[] = $shippingService;
									$pr++;
								}
							}
						}


						if ($profile->intl_ship_service1 && $profile->intl_ship_service1 != "NOT_SPECIFIED" && $profile->intl_ship_service1 != "NotSpecified" && $profile->intl_ship_service1 != "NotSelected" && $profile->intl_shipping != "NotSpecified") {
							$shippingService = new Types\InternationalShippingServiceOptionsType();
							$shippingService->ShippingServicePriority = 1;
							$shippingService->ShippingService = $profile->intl_ship_service1;
							if ($intl_shipping == "Flat") {
								$shippingService->ShippingServiceCost = new Types\AmountType(['value' => (float) $profile->intl_ship_fee1]);
								$shippingService->ShippingServiceAdditionalCost = new Types\AmountType(['value' => (float) $profile->intl_x_ship_fee1]);
							}
							$intl_ship_options1 = $profile->intl_ship_options1;
							if ($intl_ship_options1 == 2) {
								$intl_locations1 = ($profile->intl_locations1) ? explode(",", $profile->intl_locations1) : array('WorldWide');
								$shippingService->ShipToLocation = ($intl_locations1) ? $intl_locations1 : array('WorldWide');
							} else if ($intl_ship_options1 == 3) {
								$shippingService->ShipToLocation = ['CA'];
							} else {
								$shippingService->ShipToLocation = ['WorldWide'];
							}
							//$shippingService->LocalPickup = false;
							$ebayItem->ShippingDetails->InternationalShippingServiceOption[] = $shippingService;
						}

						$intl_ship_additional_services = ($profile->intl_ship_additional_services) ? json_decode($profile->intl_ship_additional_services) : array();
						if ($intl_ship_additional_services) {
							$pr = 2;
							foreach ($intl_ship_additional_services as $isservice) {
								if (isset($isservice->intl_ship_service1) && $isservice->intl_ship_service1 && $isservice->intl_ship_service1 != "NOT_SPECIFIED" && $isservice->intl_ship_service1 != "NotSpecified" && $isservice->intl_ship_service1 != "NotSelected") {

									$shippingService = new Types\InternationalShippingServiceOptionsType();
									$shippingService->ShippingServicePriority = $pr;
									$shippingService->ShippingService = $isservice->intl_ship_service1;
									if ($intl_shipping == "Flat") {
										$shippingService->ShippingServiceCost = new Types\AmountType(['value' => (float) $isservice->intl_ship_fee1]);
										$shippingService->ShippingServiceAdditionalCost = new Types\AmountType(['value' => (float) $isservice->intl_x_ship_fee1]);
									}
									$intl_ship_options1 = $isservice->intl_ship_options1;
									if ($intl_ship_options1 == 2) {
										if (!is_array($isservice->intl_locations1))
											$intl_locations1 = ($isservice->intl_locations1) ? explode(",", $isservice->intl_locations1) : array('WorldWide');
										else
											$intl_locations1 = $isservice->intl_locations1;

										//$intl_locations1 = ($isservice->intl_locations1) ? explode(",",$isservice->intl_locations1) : array('WorldWide');
										$shippingService->ShipToLocation = ($intl_locations1) ? $intl_locations1 : array('WorldWide');
									} else if ($intl_ship_options1 == 3) {
										$shippingService->ShipToLocation = ['CA'];
									} else {
										$shippingService->ShipToLocation = ['WorldWide'];
									}
									//$shippingService->LocalPickup = false;
									$ebayItem->ShippingDetails->InternationalShippingServiceOption[] = $shippingService;
									$pr++;
								}
							}
						}
					} else {
						$ebayItem->ShippingDetails->ShippingType = Enums\ShippingTypeCodeType::C_NOT_SPECIFIED;
						//$ebayItem->ShipToLocations[] = 'None';
					}

					if ($profile->sales_tax_rate > 0 && $profile->sales_tax_region && $profile->sales_tax_region != "ALL") {
						$salesTaxType = new Types\SalesTaxType();
						$salesTaxType->SalesTaxPercent = (double) $profile->sales_tax_rate;
						$salesTaxType->SalesTaxState = $profile->sales_tax_region;
						if ($profile->apply_tax_to_shipping) {
							$salesTaxType->ShippingIncludedInTax = true;
						}
						$ebayItem->ShippingDetails->SalesTax = $salesTaxType;
					}
				}

				$ebayRequest->Item = $ebayItem;

				sleep(2);
				file_put_contents("ebay_req.json", json_encode($ebayRequest->toArray()));
				//Log::info($ebayRequest);
				$ebayResponse = ($listing_format == "auction") ? $ebayService->verifyAddItem($ebayRequest) : $ebayService->verifyAddFixedPriceItem($ebayRequest);
				//Log::info($ebayResponse);
				Log::info('Here is the ebay response for the product id '.$product_id.' ebay response '.$ebayResponse);
				return $ebayResponse;

				/*
							$isEnded = true;
							$errors = array();
							if(isset($ebayResponse->Errors)){
								foreach($ebayResponse->Errors as $error){
									$severityCode = $error->SeverityCode === Enums\SeverityCodeType::C_ERROR ? 'Error' : 'Warning';
									$errors[] = array("severitycode" => $severityCode,"shortmessage" => $error->ShortMessage,"longmessage" => $error->LongMessage);
									if(strpos($error->ShortMessage,'ended') !== false) $isEnded = true;
								}
								$errors = json_encode($errors);
							}

							$isFailed = true;
							if($ebayResponse && isset($ebayResponse->Ack) && $ebayResponse->Ack !== 'Failure'){
								$isFailed = false;
								$itemID = $ebayResponse->ItemID;

								$ebayItemData = [];

								try{
									$ebayItemRequest = new Types\GetItemRequestType();
									$ebayItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
									$ebayItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
									$ebayItemRequest->ItemID = $itemID;
									$ebayItemRequest->IncludeItemSpecifics = true;						
									$ebayItemResponse = $ebayService->getItem($ebayItemRequest);
									$ebayItemData = $ebayItemResponse->toArray();
									$ebayItemData = (isset($ebayItemData["Item"])) ? $ebayItemData["Item"] : [];
								}
								catch(\Exception $e){
									report($e);
								}

								if($listing){
									$listingVariants = $listing->variants()->get();
									if($listingVariants->count() > 0){
										$deleteVars = array();
										foreach($listingVariants as $listingVariant){
											$varFound = false;
											foreach($variants as $pvariant){
												if($pvariant->id == $listingVariant->variant_id){
													$varFound = true;
													break;
												}
											}
											if(!$varFound && !in_array($listingVariant->variant_id,$deleteVars)){
												$deleteVars[] = $listingVariant->variant_id;
												$listingVariant->delete();
											}
										}
									}
								}

								$image = null;
								if(isset($ebayItemData["PictureDetails"]) && isset($ebayItemData["PictureDetails"]["PictureURL"])){
									$image = $ebayItemData["PictureDetails"]["PictureURL"][0];
								}
								else if(isset($ebayItemData["Variations"]) && isset($ebayItemData["Variations"]["Pictures"]) && $ebayItemData["Variations"]["Pictures"]){
									$image = $ebayItemData["Variations"]["Pictures"][0]["VariationSpecificPictureSet"][0]["PictureURL"][0];
								}

								$listing_id = "";
								if($listing){
									$listing_id = $listing->id;
									$listing->listing_data = json_encode($ebayItemData);
									$listing->image = $image;
									$listing->save();
								}
								else{
									$errors = (is_array($errors)) ? json_encode($errors) : $errors;

									$listingData = array();
									$listingData["title"] = mb_convert_encoding($listing_title,'ISO-8859-1','utf-8');
									$listingData["image"] = $image;
									$listingData["status"] = "published";
									$listingData["ebay_item_id"] = $itemID;
									$listingData["sku"] = $variants[0]->sku;

									$listingData["listing_data"] = json_encode($ebayItemData);

									$listingData["listing_url"] = "https://www.ebay.com/itm/".$itemID;
									$listingData["account_id"] = $ebayAccount->id;
									$listingData["store_id"] = $shopifyStore->id;
									$listingData["user_id"] = $shopifyStore->user_id;
									
									$listing = $shopifyStore->listings()->create($listingData);

									$listing_id = $listing->id;
								}

								if($listing->product_id != $product->id){
									$listing->product_id = $product->id;
									$listing->save();
								}

								if($product->listing_id != $listing->id){
									$product->listing_id = $listing->id;
									$product->status = "published";
									$product->save();
								}


								foreach($shVariants as $shVariant){
									$pvariant = [];
									foreach($variants as $variant){
										if($variant->shopify_variant_id == $shVariant["id"]){
											$pvariant = $variant;
											break;
										}
									}

									$listing_variant_data = [];

									if(isset($ebayItemData["Variations"]) && $ebayItemData["Variations"]){
										foreach($ebayItemData["Variations"]["Variation"] as $variation){
											if($variation["SKU"] == $pvariant->sku){
												$listing_variant_data = $variation;
												break;
											}
										}
									}
									if(!$listing_variant_data) continue;

									$vimage =null;

									if(isset($ebayItemData["Variations"]) && $ebayItemData["Variations"]){
										foreach($ebayItemData["Variations"]["Variation"] as $variation){
											if($variation["SKU"] == $pvariant->sku){
												$listing_variant_data = $variation;
												break;
											}
										}

										if(isset($ebayItemData["Variations"]["Pictures"]) && $ebayItemData["Variations"]["Pictures"]){
											$variationSpecificName = $ebayItemData["Variations"]["Pictures"][0]["VariationSpecificName"];
											foreach($ebayItemData["Variations"]["Pictures"][0]["VariationSpecificPictureSet"] as $picture){
												if($variationSpecificName == $option1Name && $picture["VariationSpecificValue"] == $shVariant["option1"]){
													$vimage = $picture["PictureURL"][0];break;
												}
												else if($variationSpecificName == $option2Name && $picture["VariationSpecificValue"] == $shVariant["option2"]){
													$vimage = $picture["PictureURL"][0];break;
												}
												else if($variationSpecificName == $option3Name && $picture["VariationSpecificValue"] == $shVariant["option3"]){
													$vimage = $picture["PictureURL"][0];break;
												}
											}
										}
									}


									$variant_id = $pvariant->variant_id;

									$listingVariant = $listing->variants()->where('variant_id',$variant_id)->first();
									if($listingVariant){
										$listingVariant->ebay_item_id = $itemID;
										$listingVariant->sku = $pvariant->sku;

										$listingVariant->ebay_item_data = json_encode($ebayItemData);
										$listingVariant->listing_variant_data = json_encode($listing_variant_data);

										$listingVariant->image = $vimage;

										$listingVariant->save();
									}
									else{
										$variant_title = $pvariant->title;
										$variantData = array();
										$variantData["title"] = mb_convert_encoding($variant_title,'ISO-8859-1','utf-8');
										$variantData["ebay_item_id"] = $itemID;
										$variantData["sku"] = $pvariant->sku;
										$variantData["image"] = $vimage;
										$variantData["listing_variant_data"] = json_encode($listing_variant_data);
										$variantData["ebay_item_data"] = json_encode($ebayItemData);
										$variantData["listing_id"] = $listing->id;
										$variantData["account_id"] = $ebayAccount->id;
										$variantData["store_id"] = $shopifyStore->id;
										$variantData["user_id"] = $shopifyStore->user_id;
										$lvariant = $listing->variants()->create($variantData);

										if($pvariant->listing_variant_id != $lvariant->id){
											$pvariant->listing_variant_id = $lvariant->id;
											$pvariant->save();
										}
				
										if($lvariant->variant_id != $pvariant->id){
											$lvariant->variant_id = $pvariant->id;
											$lvariant->save();
										}
									}
								}
							}
							else if($ebayResponse && $ebayResponse->Ack === 'Failure' && $isEnded && $listing){
								$ebayRequest = ($listing_format == "auction") ? new Types\RelistItemRequestType() : new Types\RelistFixedPriceItemRequestType();
								$ebayRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
								$ebayRequest->RequesterCredentials->eBayAuthToken = $ebay_token;

								$listing_duration = "";
								if( isset($profile->listing_duration) && $profile->listing_duration ){
									$listing_duration = $profile->listing_duration;
								}
								$ebayItem = new Types\ItemType();
								if($listing_format == "auction"){
									$ebayItem->ListingType = Enums\ListingTypeCodeType::C_CHINESE;
									$ebayItem->ListingDuration = ($listing_duration) ? $listing_duration : Enums\ListingDurationCodeType::C_DAYS_7;
								}
								else{
									$ebayItem->ListingType = Enums\ListingTypeCodeType::C_FIXED_PRICE_ITEM;
									$ebayItem->ListingDuration = ($listing_duration) ? $listing_duration : Enums\ListingDurationCodeType::C_GTC;
								}
								$ebayItem->ItemID = $listing->ebay_item_id;
								$ebayItem->Site = EbayHelper::getEbaySiteNameFromID($site_id);
								$ebayRequest->Item = $ebayItem;

								$ebayResponse = array();
								$ebayResponse = ($listing_format == "auction") ? $ebayService->relistItem($ebayRequest) : $ebayService->relistFixedPriceItem($ebayRequest);

								$errors = array();
								if(isset($ebayResponse->Errors)){
									foreach($ebayResponse->Errors as $error){
										$severityCode = $error->SeverityCode === Enums\SeverityCodeType::C_ERROR ? 'Error' : 'Warning';
										$errors[] = array("severitycode" => $severityCode,"shortmessage" => $error->ShortMessage,"longmessage" => $error->LongMessage);
										if(strpos($error->ShortMessage,'ended') !== false) $isEnded = true;
									}
									$errors = json_encode($errors);
								}

								if($ebayResponse && $ebayResponse->Ack !== 'Failure'){

									$newItemID = $ebayResponse->ItemID;
									$relistParentID = $listing->ebay_item_id;
									try{
										$ebayItemRequest = new Types\GetItemRequestType();
										$ebayItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
										$ebayItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
										$ebayItemRequest->ItemID = $relistParentID;
										$ebayItemRequest->IncludeItemSpecifics = true;
										//$ebayItemRequest->DetailLevel = "ReturnAll";
													
										$ebayItemResponse = $ebayService->getItem($ebayItemRequest);
										$ebayItemResponse = $ebayItemResponse->toArray();

										if(isset($ebayItemResponse["Item"]) && $ebayItemResponse["Item"]){
											$rebayItem = $ebayItemResponse["Item"];
											$relistedItemID = (isset($rebayItem["ListingDetails"]["RelistedItemID"])) ? (string) $rebayItem["ListingDetails"]["RelistedItemID"] : "";
											if($relistedItemID == $newItemID){
												$isFailed = false;
												
												$listing->ebay_item_id = $newItemID;
												$listing->save();

												$listingVariants = $listing->variants()->get();
												if($listingVariants->count() > 0){
													foreach($listingVariants as $listingVariant){
														$listingVariant->ebay_item_id = $newItemID;
														$listingVariant->save();
													}
												}
											}
											else{
												$errors[] = array(
													"errortype"=>"ebay api error",
													"msg"=>"relistParentID item id mapping issue | ".json_encode($rebayItem),
													"item_id"=> $newItemID,
													"relistParentID"=> $relistParentID
												);
											}
										}
										else{
											$errors[] = array(
												"errortype" => "ebay api error",
												"msg" => "failed to get relistParentID | ".json_encode($rebayItem),
												"item_id" => $newItemID,
												"relistParentID" => $relistParentID
											);
										}
									}
									catch(\Exception $e){
										$errors[] = array(
											"errortype" => "Exception - get relist item",
											"msg" => $e->getMessage(),
											"item_id" => $newItemID,
											"relistParentID" => $relistParentID
										);
									}
								}
							}

							return $ebayResponse;
							*/
			} else {
				return ["error" => "one of product, profile, category data is invalid"];
				//return "one of product, profile, category data is invalid";
			}
		} catch (\Exception $e) {
			report($e);
			return ["error" => $e->getMessage()];
		}
	}
	
	public function processPendingProductPublish(){
			Log::info("process pending product");
		$cronJob = AppHelper::getCronJob("publish_products");
		if (!$cronJob || $cronJob->flag == 1 || $cronJob->do_stop == 1)
			die();
		AppHelper::updateCronJob($cronJob->type, 1);

		$storeIds = array();
		$pstores = PendingProductPublish::select('store_id')->groupBy('store_id')->get();
		if ($pstores && $pstores->count() > 0)
			foreach ($pstores as $pstore)
				$storeIds[] = $pstore->store_id;


		$shopifyStores = ($storeIds) ? ShopifyStore::where('status', "active")->whereIn("id", $storeIds)->get() : array();
		if ($shopifyStores && $shopifyStores->count() > 0) {
			foreach ($shopifyStores as $shopifyStore) {

				if ($shopifyStore->user_id == 2 || $shopifyStore->user_id == 509)
					$ebay_environment = "sandbox";
				else
					$ebay_environment = config('ebay.environment');

				$ebayCredentials = array(
					'credentials' => [
						'devId' => config('ebay.' . $ebay_environment . 'devid'),
						'appId' => config('ebay.' . $ebay_environment . 'appid'),
						'certId' => config('ebay.' . $ebay_environment . 'certid'),
					],
					'authToken' => '',
					'oauthUserToken' => '',
					'ruName' => config('ebay.' . $ebay_environment . 'RuName')
				);

				$cronJob2 = AppHelper::getCronJob($cronJob->type);
				if ($cronJob2 && $cronJob2->do_stop)
					break;

				$shopify_store_id = $shopifyStore->id;
				$store_database_name = config('config.store_db_prefix') . $shopify_store_id;
				AppHelper::setConnection($store_database_name, $shopifyStore);

				$errors = array();
				try {
					$ebayAccounts = $shopifyStore->ebayAccounts()->where("is_valid", 1)->get();

					Log::info("process pending product ebayAccounts" . json_encode($ebayAccounts, true));
					if ($ebayAccounts->count() > 0) {
						foreach ($ebayAccounts as $ebayAccount) {
							$cronJob2 = AppHelper::getCronJob($cronJob->type);
							if ($cronJob2 && $cronJob2->do_stop)
								break;
							$account_id = $ebayAccount->id;
							$accountErrors = [];
							try {

								$site_id = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;


								$pendingPublishs = $shopifyStore->pendingProductPublish()->with('profile')->with('product')->where("account_id", $account_id)->where(function ($query) {
									$query->where("processing", 0)->orWhereNull('processing');
								})->get();

								if ($pendingPublishs->count() > 0) {
									$ebayService = new Services\TradingService([
										'credentials' => $ebayCredentials['credentials'],
										'sandbox' => ($ebay_environment == "sandbox") ? true : false,
										'siteId' => $site_id
									]);

									foreach ($pendingPublishs as $pendingPub) {

										$cronJob2 = AppHelper::getCronJob($cronJob->type);
										if ($cronJob2 && $cronJob2->do_stop)
											break;

										$pendingPub->update(["processing" => 1]);
										Log::info("process pending product add update");
										$ebayResponse = $this->addUpdateEbayItem($pendingPub, $ebayAccount, $shopifyStore, $ebayService);
										Log::info("process pending product add update after send request" . json_encode($ebayResponse, true));
										if ($ebayResponse && !isset($ebayResponse->Ack)) {
											$pendingPub->update(["processing" => 0]);

											$log_data_id[] = array(
												"product_id" => $pendingPub->product_id,
												"profile_id" => $pendingPub->profile_id,
												"account_id" => $pendingPub->account_id,
												"store_id" => $pendingPub->store_id
											);

											$output_data = array();
											if ($ebayResponse)
												$output_data["errors"] = $ebayResponse;


											$logData = array();
											$logData["log_type"] = "publish_product_ebay";
											$logData["shopify_data"] = NULL;
											$logData["shopify_data_id"] = NULL;
											$logData["log_data_id"] = json_encode($log_data_id);
											$logData["status"] = "error";
											$logData["output_data"] = json_encode($output_data, JSON_INVALID_UTF8_IGNORE);
											$logData["remarks"] = $pendingPub->product->title . " : product failed to published on ebay";
											$logData["store_id"] = $shopifyStore->id;
											$logData["user_id"] = $shopifyStore->user_id;
											$shopifyStore->logs()->create($logData);
										}
									}
								}
							} catch (\Exception $e) {
								report($e);
								$accountErrors[] = $e->getMessage();
							}

							if ($accountErrors) {
								$errors = array_merge($errors, $accountErrors);
								$output_data = array();
								$output_data["errors"] = $accountErrors;
								$logData = array();
								$logData["log_type"] = "publish_products";
								$logData["log_data_id"] = $ebayAccount->id;
								$logData["status"] = "error";
								$logData["output_data"] = json_encode($output_data, JSON_INVALID_UTF8_IGNORE);
								$logData["remarks"] = "error publishing products " . $ebayAccount->name . " account";
								$logData["store_id"] = $shopifyStore->id;
								$logData["user_id"] = $shopifyStore->user_id;
								$shopifyStore->logs()->create($logData);
							}
						}
					}
				} catch (\Exception $e) {
					report($e);
					$errors[] = $e->getMessage();
				}
				if ($errors)
					file_put_contents("publishProductsError_" . $shopify_store_id . ".json", json_encode($errors));
			}
		}

		AppHelper::updateCronJob($cronJob->type, 0);

		return response()->json(['status' => 'success', 'msg' => "done"], 200);
	}

	public function fixEbayProductsVariants(){
		$cronJob = CronJob::where('type', 'import_account_products')->first();
		if ($cronJob && ($cronJob->flag == 1 || $cronJob->do_stop == 1)) {
			return response()->json(['status' => 'error', 'msg' => "cron already running"], 406);
		} else {
			$cronJob->flag = 1;
			$cronJob->started_at = date("Y-m-d H:i:s");
			$cronJob->ended_at = NULL;
			$cronJob->last_updated_at = date("Y-m-d H:i:s");
			$cronJob->save();
		}

		$updated = [];

		$shopifyStores = ShopifyStore::where('status', "active")->where('id', 8)->get();
		if ($shopifyStores->count() > 0) {
			foreach ($shopifyStores as $shopifyStore) {
				if ($shopifyStore->user_id == 2)
					$ebay_environment = "sandbox";
				else
					$ebay_environment = config('ebay.environment');

				$ebayCredentials = array(
					'credentials' => [
						'devId' => config('ebay.' . $ebay_environment . 'devid'),
						'appId' => config('ebay.' . $ebay_environment . 'appid'),
						'certId' => config('ebay.' . $ebay_environment . 'certid'),
					],
					'authToken' => '',
					'oauthUserToken' => '',
					'ruName' => config('ebay.' . $ebay_environment . 'RuName')
				);

				$shopify_store_id = $shopifyStore->id;
				$store_database_name = config('config.store_db_prefix') . $shopify_store_id;
				AppHelper::setConnection($store_database_name, $shopifyStore);

				try {
					$ebayAccounts = $shopifyStore->ebayAccounts()->where("is_valid", 1)->get();
					if ($ebayAccounts->count() > 0) {
						foreach ($ebayAccounts as $ebayAccount) {
							$cronJob2 = AppHelper::getCronJob($cronJob->type);
							if ($cronJob2 && $cronJob2->do_stop)
								break;

							try {
								$ebay_token = $ebayAccount->access_token;
								$site_id = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;

								$ebayService = new Services\TradingService([
									'credentials' => $ebayCredentials['credentials'],
									'sandbox' => ($ebay_environment == "sandbox") ? true : false,
									'siteId' => $site_id
								]);

								$listings = $shopifyStore->listings()->with('variants')->with('product')->get();
								if ($listings->count() > 0) {
									$lc = 0;
									foreach ($listings as $listing) {
										if (!$listing->product)
											continue;
										if ($listing->variants && $listing->variants->count() > 0)
											continue;
										$item_id = $listing->ebay_item_id;

										if ($lc >= 50)
											break;

										try {
											$ebayItem = [];

											$ebayItemRequest = new Types\GetItemRequestType();
											$ebayItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
											$ebayItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
											$ebayItemRequest->ItemID = $item_id;
											$ebayItemRequest->IncludeItemSpecifics = true;
											sleep(1);
											$ebayItemResponse = $ebayService->getItem($ebayItemRequest);
											$ebayItemResponse = $ebayItemResponse->toArray();

											if (isset($ebayItemResponse["Item"]) && $ebayItemResponse["Item"])
												$ebayItem = $ebayItemResponse["Item"];

											if (!isset($ebayItem["SKU"]) || !$ebayItem["SKU"])
												$ebayItem["SKU"] = "eb_" . mt_rand(10, 999) . "_" . uniqid();

											$sku = $ebayItem["SKU"];
											if (!$sku)
												$sku = "eb_" . $item_id;

											$listing_title = $ebayItem["Title"];

											$variations = (isset($ebayItem["Variations"]) && isset($ebayItem["Variations"]["Variation"])) ? $ebayItem["Variations"]["Variation"] : array();

											$options = array();
											if ($variations) {
												$nameValueList = $variations[0]["VariationSpecifics"][0]["NameValueList"];
												foreach ($nameValueList as $nameValue) {
													if ($nameValue["Value"])
														$options[] = $nameValue["Name"];
												}
												$skuvarc = 1;
												foreach ($variations as $variation) {

													$pvsku = $sku . "_" . $skuvarc;
													if (isset($variation["SKU"]) && $variation["SKU"])
														$pvsku = $variation["SKU"];

													$vlsv = $listing->variants()->where("ebay_item_id", $item_id)->where("sku", $pvsku)->first();
													if ($vlsv)
														continue;

													$optionsvalue = array();
													$nameValueList = $variation["VariationSpecifics"][0]["NameValueList"];
													foreach ($nameValueList as $nameValue)
														$optionsvalue[] = $nameValue["Value"][0];

													$vimage = null;

													if (isset($ebayItem["Variations"]["Pictures"]) && $ebayItem["Variations"]["Pictures"]) {
														$variationSpecificName = $ebayItem["Variations"]["Pictures"][0]["VariationSpecificName"];
														foreach ($ebayItem["Variations"]["Pictures"][0]["VariationSpecificPictureSet"] as $picture) {

															foreach ($nameValueList as $nameValue) {
																if ($nameValue["Name"] == $variationSpecificName && $picture["VariationSpecificValue"] == $nameValue["Value"][0]) {
																	$vimage = $picture["PictureURL"][0];
																	break;
																}
															}
															if ($vimage)
																break;
														}
													}

													$pvariant = $listing->product->variants()->where('sku', $pvsku)->first();

													$variant_title = implode(" ", $optionsvalue);
													$variantData = array();
													$variantData["title"] = mb_convert_encoding($variant_title, 'ISO-8859-1', 'utf-8');
													$variantData["ebay_item_id"] = $item_id;
													$variantData["sku"] = $pvsku;
													$variantData["image"] = $vimage;
													$variantData["listing_variant_data"] = json_encode($variation);
													$variantData["ebay_item_data"] = json_encode($ebayItem);
													$variantData["listing_id"] = $listing->id;
													if ($pvariant)
														$variantData["variant_id"] = $pvariant->id;
													$variantData["account_id"] = $ebayAccount->id;
													$variantData["store_id"] = $shopifyStore->id;
													$variantData["user_id"] = $shopifyStore->user_id;
													$lsvar = $listing->variants()->create($variantData);
													if ($pvariant && $lsvar) {
														$pvariant->listing_variant_id = $lsvar->id;
														$pvariant->save();
													}
												}
											} else {
												$lsv = $listing->variants()->where("ebay_item_id", $item_id)->where("sku", $sku)->first();
												if ($lsv)
													continue;
												$pvariant = $listing->product->variants()->where('sku', $sku)->first();
												$variant_title = "Default Variant";
												$variantData = array();
												$variantData["title"] = mb_convert_encoding($variant_title, 'ISO-8859-1', 'utf-8');
												$variantData["ebay_item_id"] = $item_id;
												$variantData["sku"] = $sku;
												$variantData["image"] = null;
												$variantData["listing_variant_data"] = json_encode($ebayItem);
												$variantData["ebay_item_data"] = json_encode($ebayItem);
												$variantData["listing_id"] = $listing->id;
												if ($pvariant)
													$variantData["variant_id"] = $pvariant->id;
												$variantData["account_id"] = $ebayAccount->id;
												$variantData["store_id"] = $shopifyStore->id;
												$variantData["user_id"] = $shopifyStore->user_id;
												$lsvar = $listing->variants()->create($variantData);

												if ($pvariant && $lsvar) {
													$pvariant->listing_variant_id = $lsvar->id;
													$pvariant->save();
												}
											}
											$updated[] = $item_id;
										} catch (\Exception $e) {
											report($e);
										}
										$lc++;
									}
								}
							} catch (\Exception $e) {
								report($e);
							}
						}
					}
				} catch (\Exception $e) {
					report($e);
				}
			}
		}

		$cronJob->flag = 0;
		$cronJob->ended_at = date("Y-m-d H:i:s");
		$cronJob->last_updated_at = date("Y-m-d H:i:s");
		$cronJob->save();

		return response()->json(['status' => 'success', 'msg' => "done", "updated" => $updated], 200);
	}
	
	
		//     public function checkipn(){
		// 		    $data = array();

		//         $data[] = array('EventName', 'EventType', 'NotificationEnable');

		//         // $ebayAccounts = $shopifyStore->ebayAccounts()->where("is_valid", 1)->get();

		//     //     $host12 = "69.64.64.108";
		//     //     $username12 = "app1_ebay";
		//     // 	$password12 = "38d(g5G+Y+][";
		//     // 	$dbname12 = "app1_ebay_shopify";
		//     // 	$conn12 = new mysqli($host12, $username12, $password12, $dbname12);
		//     // 	if ($conn12->connect_error) {
		//     // 	    // TODO: Add some logging and email notification here
		//     // 		die("Connection failed: " . $conn12->connect_error);
		//     // 	}
		// 	$ebayAccounts =EbayAccount::where("is_valid",1)->where("store_id",95)->get();


		// 	foreach($ebayAccounts as $ebayAccount){
				
		// 	    	$siteId = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
		// 			$authToken = $ebayAccount->access_token;
					
		// 				$ebay_environment = config('ebay.environment');
		// 					$ebayCredentials = array(
		// 						'credentials' => [
		// 							'devId' => config('ebay.'.$ebay_environment.'devid'),
		// 							'appId' => config('ebay.'.$ebay_environment.'appid'),
		// 							'certId' => config('ebay.'.$ebay_environment.'certid'),
		// 						],
		// 						'authToken' => '',
		// 						'oauthUserToken' => '',
		// 						'ruName' => config('ebay.'.$ebay_environment.'RuName')
		// 					);

		// $ebayService = new Services\TradingService([
		// 									'credentials' => $ebayCredentials['credentials'],
		// 									'sandbox' => ($ebay_environment == "sandbox" ) ? true : false,
		// 									'siteId' => $siteId
		// 								]);

		// // Create an instance of GetNotificationPreferencesRequestType
		//             $request = new Types\GetNotificationPreferencesRequestType(); 
		//             $request->RequesterCredentials = new Types\CustomSecurityHeaderType();
		//             $request->RequesterCredentials->eBayAuthToken = $authToken;
		//             $request->PreferenceLevel = 'Application';
		//             $response =$ebayService->getNotificationPreferences($request);
		//           print_r($response);
		//           //  addlog("new ipn data select sucess ".json_encode($response), "INFO");	
					
					
		// 			     if ($response->Ack === 'Success') {
					
		//                 $notificationPreferences = $response->ApplicationDeliveryPreferences;
						
						
		//                     $notificationName =  $notificationPreferences ->ApplicationURL;
		//                     $notificationName1 =  $notificationPreferences ->ApplicationEnable;
		//                   // $res =$this->setupIPN( $authToken, $siteId, "Disable", "ItemListed", $notificationName );
		//                  //   if($res['status'] == 'failure'){
		// 		//	$errmsg = $errmsg.' ItemListed - '.$res['error'];
		// 	//	}
				
						
		//           //   print_r("hetyyy prabhakerr".$notificationPreferences);
						
						
		//                 foreach ($notificationPreferences as $preference) {
		//                     print_r($preference);
							
						
		//                     $notificationName = $preference->ApplicationURL;
		//                     $notificationName1 = $preference->ApplicationEnable;
							
							
							
							
							
		//                   print_r("name ::".$notificationName."/n");
							
							
		//                          echo"name2 ::".$notificationName1."/n";
							
							
					
		//                     $notificationEnabled = $preference->UserDeliveryPreferenceArray->NotificationEnable;
							
		//                     echo"name2 ::".$notificationEnabled."/n";
							
		//                       $data[] = array($notificationName, $notificationName1, $notificationEnabled);

		//         outputCSV($data);
							
							
							
		//         $res = setupIPN( $ebtoken, $siteid, "Disable", "ItemListed",$eventurl);
		// 		if($res['status'] == 'failure'){
		// 			$errmsg = $errmsg.' ItemListed - '.$res['error'];
		// 		}
		// 		$res = setupIPN( $ebtoken, $siteid, "Disable", "ItemRevised",$eventurl);
		// 		if($res['status'] == 'failure'){
		// 			$errmsg = $errmsg.' ItemRevised - '.$res['error'];
		// 		}
				
		// 		$res = setupIPN( $ebtoken, $siteid, "Disable", "FixedPriceTransaction",$eventurl);
		// 		if($res['status'] == 'failure'){
		// 			$errmsg = $errmsg.' FixedPriceTransaction - '.$res['error'];
		// 		}
						
				

		//     }
		// //     	
		// } else {
		//     echo"ebay request is not suceesfulll";
		// }
				
				
		// 	}
		//         // $query_main=$conn12->query("select * from ebay_accounts ") or die("error in query");
				
				

		// 		}


	public function checkipn() {
		// Initialize CSV content
		exit(0);
		$csv_content = "store_id,EventName, EventType, NotificationEnable\n";
		$directory_path = '/home/app1/public_html/service/app/';
		if (!file_exists($directory_path)) {
			mkdir($directory_path, 0777, true);
		}

		$ebayAccounts = EbayAccount::where("is_valid", 1)->get();

		foreach ($ebayAccounts as $ebayAccount) {
			$siteId = isset($ebayAccount->siteid) ? $ebayAccount->siteid : 0;
			$authToken = $ebayAccount->access_token;
			$storeId=$ebayAccount->store_id;
			

			$ebay_environment = config('ebay.environment');
			$ebayCredentials = array(
				'credentials' => [
					'devId' => config('ebay.' . $ebay_environment . 'devid'),
					'appId' => config('ebay.' . $ebay_environment . 'appid'),
					'certId' => config('ebay.' . $ebay_environment . 'certid'),
				],
				'authToken' => '',
				'oauthUserToken' => '',
				'ruName' => config('ebay.' . $ebay_environment . 'RuName')
			);

			$ebayService = new Services\TradingService([
				'credentials' => $ebayCredentials['credentials'],
				'sandbox' => ($ebay_environment == "sandbox"),
				'siteId' => $siteId
			]);

			// Create an instance of GetNotificationPreferencesRequestType
			$request = new Types\GetNotificationPreferencesRequestType();
			$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
			$request->RequesterCredentials->eBayAuthToken = $authToken;
			$request->PreferenceLevel = 'Application';

			try {
				// Make the API call
				$response = $ebayService->getNotificationPreferences($request);
				
			//  print_r($response."\n");

				if ($response->Ack === 'Success') {
					$notificationPreferences = $response->ApplicationDeliveryPreferences;
					
					
				print_r("here is responseee after scuscess".$notificationPreferences."\n");
					
					$notificationName =  $notificationPreferences ->ApplicationURL;
					$notificationName1 =  $notificationPreferences ->ApplicationEnable;
					
					$row_data = '"'.$storeId.'"' . $notificationName . '","' . $notificationName1 . '",' . "\n";
						
					
						$csv_content .= $row_data;
						
						
					//   if($notificationName='https://dev.infoshoreapps.com/handleIPN.php' || $notificationName='https://app1.ecomshore.com/service/handleipn'){
							
						//   $res =$this->setupIPN( $authToken, $siteId, "Disable",  $notificationName );
							
						//   print_r("here is responseee after scuscess".$res."\n");
							
							//echo"hheelelel";
		//                         if($res['status'] == 'failure'){
		// 			$errmsg = $errmsg.' ItemRevised - '.$res['error'];
		// 		}
								
								// $res = $this->setupIPN( $authToken, $siteId, "Disable", "ItemRevised",$notificationName);
								//  print_r("here is responseee after scuscess".$res."\n");
		// 		if($res['status'] == 'failure'){
		// 			$errmsg = $errmsg.' ItemRevised - '.$res['error'];
		// 		}
				
		// 		$res =$this->setupIPN($authToken, $siteId, "Disable", "FixedPriceTransaction",$notificationName);
				
		// 		print_r("here is responseee after scuscess".$res."\n");
		// 		if($res['status'] == 'failure'){
		// 			$errmsg = $errmsg.' FixedPriceTransaction - '.$res['error'];
		// 		}
								
							
					//  }
						
						
					
				//     foreach ($notificationPreferences->ApplicationDeliveryPreferences as $preference) {
						
				//         print_r($preference."\n");
				//         $notificationName = $preference->ApplicationURL;
				//         $notificationName1 = $preference->ApplicationEnable;
				//       // $notificationEnabled = $preference->UserDeliveryPreferenceArray->NotificationEnable;

					
				//         $row_data = '"'.$storeId.'"' . $notificationName . '","' . $notificationName1 . '",' . "\n";
					
				//         $csv_content .= $row_data;
				//     }
				} else {
					echo "eBay request was not successful";
				}
			} catch (\Exception $e) {
				echo 'Error: ' . $e->getMessage();
			}
		}
		$csv_file_path = $directory_path . 'notification_preferences2.csv';
		file_put_contents($csv_file_path, $csv_content);
		
		
		//file_put_contents('/public_html/service/app/notification_preferences.csv', $csv_content);

		
		// file_put_contents('notification_preferences.csv', $csv_content);
	}

    public function setupIPN($token, $siteid, $status,  $eventURL){
        $eventType='ItemListed';
        
			echo $status;
		//global $conn, $ebConfig;
		if(strlen($token) == 0){		
			return false;
		}	
    
    	$ebay_environment = config('ebay.environment');
					$ebayCredentials = array(
						'credentials' => [
							'devId' => config('ebay.'.$ebay_environment.'devid'),
							'appId' => config('ebay.'.$ebay_environment.'appid'),
							'certId' => config('ebay.'.$ebay_environment.'certid'),
						],
						'authToken' => '',
						'oauthUserToken' => '',
						'ruName' => config('ebay.'.$ebay_environment.'RuName')
					);
    	$ebayService = new Services\TradingService([
									'credentials' => $ebayCredentials['credentials'],
									'sandbox' => ($ebay_environment == "sandbox" ) ? true : false,
									'siteId' => $siteid
								]);
		$notificationPreferencesRequestType = new Types\SetNotificationPreferencesRequestType();	
		$notificationPreferencesRequestType->RequesterCredentials = new Types\CustomSecurityHeaderType();
		$notificationPreferencesRequestType->RequesterCredentials->eBayAuthToken = $token;
		$notificationPreferencesRequestType->DetailLevel = ['ReturnAll','ItemReturnAttributes','ItemReturnDescription'];
		$applicationDeliveryPreferencesType = new Types\ApplicationDeliveryPreferencesType();
		$applicationDeliveryPreferencesType->ApplicationURL = $eventURL;
		
		$applicationDeliveryPreferencesType->ApplicationEnable=$status;
		$notificationPreferencesRequestType->ApplicationDeliveryPreferences = $applicationDeliveryPreferencesType;

		$notificationEnableType = new Types\NotificationEnableType();
		$notificationEnableType->EventType = $eventType;
		$notificationEnableType->EventEnable = $status;

		$notificationEnableArrayType = new Types\NotificationEnableArrayType();
		$notificationEnableArrayType->NotificationEnable = array($notificationEnableType);
		$notificationPreferencesRequestType->UserDeliveryPreferenceArray = $notificationEnableArrayType;

		$notificationUserDataType = new Types\NotificationUserDataType();
		
		$notificationPreferencesRequestType->UserData = $notificationUserDataType;		
		$response = $ebayService->setNotificationPreferences($notificationPreferencesRequestType);
		if($response->Ack !== 'Failure') {
			
			return $response;
			//return array("status"=>"success");
		} else {
			$errmsg = "";
			if (isset($response->Errors)) {
				foreach ($response->Errors as $error) {
					$errmsg = $errmsg." :: ".$error->LongMessage;
				}
			}			
			return array("status"=>"failure", "error" => $errmsg);
		}		
	}

    public function outputCSV($data) {

		$output = fopen("ebayWebhookdata.csv", "w");

		foreach ($data as $row) {
			fputcsv($output, $row);
		}

		fclose($output);
	}
	
	public function fixEbayListingVariantsSync(){
		$cronJob = CronJob::where('type', 'import_account_products')->first();
		if ($cronJob && ($cronJob->flag == 1 || $cronJob->do_stop == 1)) {
			return response()->json(['status' => 'error', 'msg' => "cron already running"], 406);
		} else {
			$cronJob->flag = 1;
			$cronJob->started_at = date("Y-m-d H:i:s");
			$cronJob->ended_at = NULL;
			$cronJob->last_updated_at = date("Y-m-d H:i:s");
			$cronJob->save();
		}

		$updated = [];


		$shopifyStores = ShopifyStore::where('status', "active")->where('id', 8)->get();
		if ($shopifyStores->count() > 0) {
			foreach ($shopifyStores as $shopifyStore) {

				$shopify_store_id = $shopifyStore->id;
				$store_database_name = config('config.store_db_prefix') . $shopify_store_id;
				AppHelper::setConnection($store_database_name, $shopifyStore);

				try {
					$ebayAccounts = $shopifyStore->ebayAccounts()->where("is_valid", 1)->get();
					if ($ebayAccounts->count() > 0) {
						foreach ($ebayAccounts as $ebayAccount) {
							$cronJob2 = AppHelper::getCronJob($cronJob->type);
							if ($cronJob2 && $cronJob2->do_stop)
								break;

							try {
								$listings = $shopifyStore->listings()->whereHas('product')->with('product')->with('variants')->get();
								if ($listings->count() > 0) {
									foreach ($listings as $listing) {
										try {
											foreach ($listing->variants as $lvariant) {
												if ($lvariant->variant_id > 0) {
													$pvariant = $listing->product->variants()->find($lvariant->variant_id);
													if ($pvariant && !$pvariant->listing_variant_id) {
														$pvariant->listing_variant_id = $lvariant->id;
														$pvariant->save();

														$updated[] = $listing->ebay_item_id;
													}
												} else {
													$pvariant = $listing->product->variants()->where('sku', $lvariant->sku)->first();
													if ($pvariant && !$pvariant->listing_variant_id) {
														$lvariant->variant_id = $pvariant->id;
														$lvariant->save();

														$pvariant->listing_variant_id = $lvariant->id;
														$pvariant->save();

														$updated[] = $listing->ebay_item_id;
													}
												}
											}
										} catch (\Exception $e) {
											report($e);
										}
									}
								}
							} catch (\Exception $e) {
								report($e);
							}
						}
					}
				} catch (\Exception $e) {
					report($e);
				}
			}
		}

		$cronJob->flag = 0;
		$cronJob->ended_at = date("Y-m-d H:i:s");
		$cronJob->last_updated_at = date("Y-m-d H:i:s");
		$cronJob->save();

		return response()->json(['status' => 'success', 'msg' => "done", "updated" => $updated], 200);
	}
	
	public function decryptData(){
		$data = 'O6yxzZzXEs4qorl0w2otTCQBt6xtEVHvevv9zWrhx68oaBN59xIqzRfgifH4uKc/YxslEI5fDUHYoU2VM/1m4Z4Tu89S+iJY8WtPMF9p0aNgi2h5IpCGVBwfCz/IyVuQqrn1NdFOf9SHrNZbzmqzME1dT5+Jt4yJUM5CwLfLD+dL7cTBN3vKfUjnRQD+wbgMym/RdEG3HkfDLrSXyAETuRfjqO3C50Uan/oPSD4VBlyi1TaHRR136/ZSvGgxGNuWRkOZCLvMQBju+oqySKuitIgYsgFB7sZc6pvozv50aBKmewHf6BBRf55e5EwgD734Af3XFZaTA7PoJLUlWE7l8CYr8QD9F6QKWj6GSgB7qeszouyiMoXd5lbHsjH+OKU87xM7UaodPK+utcEGNguuSEPze+MZFY+yEciGy2+oQHPE0BiCur+6IrQR4uwGPKVDB5g13oRnvFBoTDKTUJro6DsreNnNsHwOEiSlo9Oaa6Nj4gMtDwVEvuDV3JG4B2AMXZgk2fI5gJhjrh9VCz364BV0YiedkVKjJXXDlDcn4gZYY2jnyl3WwaSsW7ioCQDKJCcI/r36s/FXwfm2I9cBchbYMfYGTEqTisyZOH+EwtDKZzHZsccstgVcNxLtDq4tDpDMNPmds+VpQQUD4YrXGqAw3OR0RpsyumC3hXToegntpho2nsZxq9gvWzNTxhbExoJhfnfGaiDYufWlyAfee9BD/z5KrDW6tRNVPKJ7fTDKuzMfVSe8QxnCLq/rGQp8A8i1MyARNOro2C+wL12aEr9zbFj3ZyS5o2TKi/LOTvqzVgK3riXjY4k0yeB4nvcpleIkKDPn7RbLH8JphFQFBAHM8+Oo9AoFk/ADDe03i0dshzSaJBH0M5YyD9lMtnS8A1ZUOup6k5UXSVgLzC0E8BsM2kP2OA4ahpo+sDl3MnqAgbk86ZSpUG1wsAnUVzoKLW26ZEZ4BjoxmWj4/1IaeeLt4l2wre1neDwUKWJkwnpHFPWW1E5bfVCjjN3du0XdVdVWMn0Wp9jSBsrtTAuNdPKpoI1IndDVfQX60K/YzKN40LVHnbKgcpJDCW4UK4HxaUWLdEsadB3172RvrEqyAQho9mbJ19KYLukN53lGwhsM7lKkaj8kksiwvWJLluyUWVCgGdlho7Yky1Q4z+gt+jue1F1CX0qUvvfV2Me59Z/yEPpcBHxChenbNfLoSeQTdeuX77Dx+dfizXDVYeeuzuoNvp/h854t0Y6gOFBhSKKm4lJw/YkIzrS335SSFrSA4j7fz94S9AUphz2ONDcVvh8P6eARUJLGcN9KX5rXsmIrVeG4lj5uM9KRPrL25/7l92xK96VEHjn7iLMkFCYsc61NilmM+Wc9KiK1kShJCAIjF+2dksYbGcXoVCdQgOro8oS5tn0SGoxJ4us8vbFVsRYTzdWce4WDf4UhnyPB4Re/bbUQ2Vs6yoo06pZuezwXlhUXgagc1Fyp7dnSbxJNc02VxbodkDwYc1YjzAlirrNNij9Vv3L7QyISkr8U/XFdua1iTzSkXB4vh5RTS8XeK231WYcTl1fCNwk5PsnBX/ljWoYH3wgksK6ngS1NF54d5qe+ti3dPSSiWH9ZrqCdU/zUmmqkzwnTXf02Z9qnRIiGPoo+qAvk5tpTCPRil4IIxMAVo5gVO2IQpYttcIPVzO0EeNHJ8k2z24SBkCjFV/LXx2kfQKGCKev0d97fi/0gKz6uhHwjFXh1G3MAmSmdIXAmQxHUipz0Fkm3M+LjHMeS+hlvJyOOAi+IdLkKiDse9oC2rzbnlV4KR/pxnnDl11fysCAjdIiepeT6LcRyePVAfth7gDEViyBbX68WyHl825ZwPx+A574+Vaj4CNmxRnVmH8d4d6G9PflWx/vuTLGmZM9eDWLKvtxQHEOhrt+ZoUqwzemVm43X9f9tB9nUG178AwmEfJEDiYxGUPhrd20Frm+96Lzhj5klmZzukq0W8mj38wp8ntcUG+tXDnLlVAjnjgTYQ4J7cki9mfwsS3qfRUUVSDva3sau4zKJ11iVXYxjMAO5GBT/65t9CfSqwaAyTXUmUGgGuXKzUCeafgxHSUdTg39G4/qyLsziHRYy8LqYuDEXBYrZ2wwQW4s2IGvBrm6BXDrlnsWbMPJZewEV8L2ySvytb9I8iijop9uwUlzZfb543NPUygxTG85tmUo13qi2OibrQstkamPTHSHdMiq9EmIbmwZ2KO4mknMUTKhmMuf+t6KCTHeeV6dBFvbgoPHS15nraMbarv8zfNuwDuC3oH2Zc9Lwx1qAgp51pnc2CtEcVm8PKW+sYvnhIbAy/OSzNg3O5mod04faac6f+x8JFMd3hHOTxA7rIB2wVemOyHVfaCKfGKXjPJqfu4Oqm3icVRTmoN+vzrPBpR1r8XCaCLw0WQ9NOive4wv90+L1lS/X5MhmcOJmVyGy3OeZoORfAeTn3r6jV4ybHq2R1M7n42+C77G/Q6z7ZpaYhorjxfsmNSogWutOnQHKVtOkSXrTbNxjW56Lp9WYnnU9yidms0MAnFZcyZXM1vh7DKKk+HRoUicTlmMQFp5rgVFRxy11omx3tCkofYyXdfm7h6e5SspHWx6P7UPQsNrmLr3G+AOdo/W1ZczV8YEc8w==:UmsJeF6PO6hoxqNALXa48w==';
		$data = AppHelper::decryptData($data);
		echo $data;
	}
	
	

}