<?php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
use App\Http\Controllers\Controller;
use App\EbayCategory;
use App\EbayCategorynew;
use App\Libraries\Ebay;
use App\ShopifyStore;
use App\CronJob;
use App\Helpers\AppHelper;
use App\EbayStoreCategory;
use App\EbayAccount;
use App\EbayShippingService;
use App\EbayShippingServiceType;
use App\EbayShippingServiceTypeMapping;
use App\EbayItemcondition;
use App\EbaySalesTaxState;
use App\EbayPaymentOption;
use App\EbaySellerProfile;

use \DTS\eBaySDK\Constants;
use \DTS\eBaySDK\BusinessPoliciesManagement\Services;
use \DTS\eBaySDK\BusinessPoliciesManagement\Types;

use \DTS\eBaySDK\Trading\Services as TServices;
use \DTS\eBaySDK\Trading\Types as TTypes;
use Illuminate\Support\Facades\Log;

class EbayDataController extends Controller
{
    public function __construct(){
    }
    
// 	public function ebayCategory(Request $request){
// 		$shopifyStore = AppHelper::getShopifyStore($request);
// 		if(!$shopifyStore) return response()->json(['status' => 'error','msg' => "invalid request"],403);
		
// 		$ebayAccount = $shopifyStore->ebayAccounts()->where("is_valid","1")->first();
// 		if(!$ebayAccount) return response()->json(['status' => 'error','msg' => "invalid request"],403);

// 		$siteid = $ebayAccount->siteid;
// 		$account_id = $ebayAccount->id;
// 		$store_id = $shopifyStore->id;

// 		$category_id = ($request->has('category_id') && $request->input('category_id') > 0) ? $request->input('category_id') : 0;

// 		if($category_id > 0){
// 			$ebayCategory = EbayCategory::select('id','category_tree_name','category_attributes')->find($category_id);
// 			if($ebayCategory){
// 				$category_attributes = json_decode($ebayCategory->category_attributes,true);

// 				if(!$category_attributes || !isset($category_attributes[0]["min_values"])){
// 					$category_attributes = $this->getEbayCategorySpecifics($ebayCategory->ebay_category_id,$siteid);
// 					$ebayCategory->category_attributes = $category_attributes;
// 				}
// 				else $ebayCategory->category_attributes = $category_attributes;
// 			}
// 			return response()->json($ebayCategory,200);
// 		}
		
// 		$ebayCategories = EbayCategory::select('id','category_tree_name','category_attributes')->where('ebay_site', $siteid)->where('is_last_level',1)->get();
		
// 		if($ebayCategories->count()){
// 			$ebayCategories = $ebayCategories->toArray();
// 			foreach($ebayCategories as $key => $ebayCategory){
// 				$ebayCategories[$key]["category_attributes"] = json_decode($ebayCategory["category_attributes"],true);
// 			}
// 		}

// 		return response()->json($ebayCategories,200);
//     }

public function ebayCategory(Request $request){
       Log::info(" here is the ebay cat -> $request");
		$shopifyStore = AppHelper::getShopifyStore($request);
		if(!$shopifyStore) return response()->json(['status' => 'error','msg' => "invalid request"],403);

		$ebayAccount = $shopifyStore->ebayAccounts()->where("is_valid","1")->first();
		if(!$ebayAccount) return response()->json(['status' => 'error','msg' => "invalid request"],403);

		$siteid = $ebayAccount->siteid;
		$account_id = $ebayAccount->id;
		$store_id = $shopifyStore->id;

		$category_id = ($request->has('category_id') && $request->input('category_id') > 0) ? $request->input('category_id') : 0;
		$selectedConditionId = ($request->has('conditionId') && $request->input('conditionId') > 0) ? $request->input('conditionId') : 0;
		echo $selectedConditionDescriptors = $request->input('selectedConditionDescriptors');

		if($category_id > 0){

			$ebayCategory = EbayCategory::select('id','category_tree_name','category_attributes')->find($category_id);
			
			if($ebayCategory){				
				$itemConditionData = EbayItemcondition::select('item_condition_data')->where('categories_id', $ebayCategory->id)->first();
				// Decode the JSON data
				$itemConditionArray = json_decode($itemConditionData->item_condition_data, true);
				// Check if decoding was successful
				if ($itemConditionArray === null) {
					echo "Error decoding JSON data\n";
					exit;
				}

				$foundMatch = false;
				$conditionDescriptors = [];
				foreach ($itemConditionArray as $item) {
					if (isset($item['conditionId']) && $item['conditionId'] == $selectedConditionId) {
						//echo "Match found: " . $item['conditionDescription'] . " (ID: " . $item['conditionId'] . ")\n";
						if (isset($item['conditionDescriptors']) && is_array($item['conditionDescriptors'])) {
							$conditionDescriptors = array_merge($conditionDescriptors, $item['conditionDescriptors']);  // Merge arrays
						}
						$foundMatch = true;
						break;  // Exit the loop after finding the first match
					}
				}

				$category_attributes = json_decode($ebayCategory->category_attributes,true);

				if(!$category_attributes || !isset($category_attributes[0]["min_values"])){
					$category_attributes = $this->getEbayCategorySpecifics($ebayCategory->ebay_category_id, $siteid);
					$ebayCategory->category_attributes = $category_attributes;
				} else {
					$ebayCategory->category_attributes = $category_attributes;
				}
				
				$itemConditionDatanew = json_decode($itemConditionData,true);

				// Add item condition data to the category response
				$ebayCategory->item_condition_data = json_decode($itemConditionDatanew['item_condition_data'],true);
				$ebayCategory->conditionDescriptors = $conditionDescriptors;
			}
			return response()->json($ebayCategory,200);
		}

		$ebayCategories = EbayCategory::select('id','category_tree_name','category_attributes')->where('ebay_site', $siteid)->where('is_last_level',1)->get();

		if($ebayCategories->count()){
			$ebayCategories = $ebayCategories->toArray();
			foreach($ebayCategories as $key => $ebayCategory){
				$ebayCategories[$key]["category_attributes"] = json_decode($ebayCategory["category_attributes"],true);
			}
		}

		return response()->json($ebayCategories,200);
    }

	public function updateEbayCategory(Request $request){
		$cronJob = CronJob::where('type','update_ebay_data')->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();
		}

		$environment = config('ebay.environment');
		$siteIDs = array('0','2','3','15','16','23','71','77','100','101','123','146','186','193','201','203','205','207','210','211','212','216');
		if($request->has('siteid')){
			$siteid = ($request->input('siteid')) ? $request->input('siteid') : 0;
			$siteIDs = [$siteid];
		}
		else{
			$siteIDs = ['0'];
		}

		$siteIDs = ['3'];

		$_EBAY = array(
			'trade'  => config('ebay.'.$environment.'trade'),
			'signin' => config('ebay.'.$environment.'signin'),
			'devid'  => config('ebay.'.$environment.'devid'),
			'appid'  => config('ebay.'.$environment.'appid'),
			'certid' => config('ebay.'.$environment.'certid'),
			'RuName' => config('ebay.'.$environment.'RuName'),
			'compatabilityLevel' => 859,
			'siteID' => 0
		);
		$ebay_token ='v^1.1#i^1#p^1#r^0#f^0#I^3#t^H4sIAAAAAAAAAOVYbWwURRi+a6+FytcPUSxovG5FCeTuZnfvc+ldvH7QHgItvbZARXF2d7Zdul/uztEeieYsSoRggKhEopFGYlAwwA8UsMIPRBMh/BIjKGhQw1cQQYHqH+Lu9ijXSgDpJTbx/lzmnXfeeZ5n3ndmdkCmuGT6yrqVfeOcowp6MiBT4HSSY0BJcdGM8YUFk4scIMfB2ZN5LOPqLjxbYUBZ0phGZGiqYiB3lywpBmMbo0RKVxgVGqLBKFBGBoM5JhmfO4ehvIDRdBWrnCoR7kR1lAiQgGdJSEYiHIoINGdalRsxm9QowQdoFKFCgsALYVoIQLPfMFIooRgYKjhKUICiPSDoAeEmEGACIYYKeYMRspVwtyDdEFXFdPECImbDZeyxeg7W20OFhoF0bAYhYon4rGR9PFFdM6+pwpcTK5bVIYkhThmDW1Uqj9wtUEqh209j2N5MMsVxyDAIX6x/hsFBmfgNMPcA35YaQQrwIZ5ngUBRCFB5kXKWqssQ3x6HZRF5j2C7MkjBIk7fSVFTDXYp4nC2Nc8Mkah2W3/zU1ASBRHpUaKmMr4o3tBgxlIENdmu6p7kU82VKZaVPA2N1R4/JQTCZAhRHhhAIBIkQ9mJ+qNlZR4yU5Wq8KIlmuGep+JKZKJGQ7Xx52hjOtUr9XpcwBaiXL/QDQ3DoVZrUftXMYXbFWtdkWwK4babd16BgdEY6yKbwmggwtAOW6IoATVN5ImhnXYuZtOny4gS7RhrjM/X2dnp7aS9qt7mowAgfQvnzkly7Ug2i61Ltmq931+88wCPaFPhkDnSEBmc1kwsXWaumgCUNiJGUUF/JJDVfTCs2FDrPww5nH2DKyJfFUKG6BD0Qz9H8oj2AzofFRLLJqnPwoFYmPbIUO9AWJMghzycmWcpGekiz9ABgaLDAvLwwYjg8UcEwcMG+KCHFBACCLEsFwn/nwrlblM9iTgd4bzket7yfEZkQW0NaE6nqpbB5aS2sBaTy1hFhGQyMashsLwt1STPDydIn9Doj95tNdySfJUkmso0mfPnQwCr1vMnQp1qYMQPi16SUzXUoEoilx5ZC0zrfAPUcTqJJMk0DItkXNMS+dmr80bvX24T98Y7f2fUf3Q+3ZKVYaXsyGJljTfMAFATvdYJ5OVU2WfVugrN64dlXmKjHhZv0by5jijWJsl+tiLff+X02nS9xjLOqyNDTenmbdtbb93AmtQOpJjnGdZVSUJ6CznsepblFIashEZaYechwUU4wg5bMhgOUoAO+4e3HXH2UbpkpG1J+diKXbX3eK32Df7IjznsH9ntPAC6nfsLnE5QAaaS5aCsuLDZVTh2siFi5BWh4DXENsX8dtWRtwOlNSjqBfc7+sCZt7kLdR+u7rje+fzpmS84ct8Yep4BDw28MpQUkmNynhzAwzd7isgJk8ZRNAiCMAgEQlSoFZTf7HWRD7omvniq47NRM6ZMP9xxNL0o9rh+GF+tBeMGnJzOIoer2+lwlR47Wdq96t2Mc+bmU+zyyrIV4eKtQu+OZt97/t527fX1f+3/ZvPx46PA2jZ533elfV2T+JPHJ23pPLHlpz3Rj1cX79I+ZV774b4zu6606GNPtz73dfidwvSCP7Rf1zkmnpfP7W28Wu+OXD4wofqgXz6yZuVXX67fvTP+1qs7nrg8u3gtsa58dhdcfOiX7dfo82UTp81cvG60//PdR1YdLaOP7dy/8fct3z56Qb904dq5cje595x0cVrFB5TQc+K3mlf08NMr0JErZ9/8M/DIhszG66Md2y5Vz+49qI3/ROH3vLH9/T41/VHGh0p9NRfrDvXu++KBnzc9efHZbRvY9u8PLg1v+pF8aeuUqS+X9K/l305eQz/9EQAA';
		
		foreach($siteIDs as $site_id){
			$_EBAY['siteID'] = $site_id;

			$cronJob2 = CronJob::where('type','update_ebay_data')->first();
			if($cronJob2 && $cronJob2->do_stop) break;


			$ebayClient = new Ebay($ebay_token,$_EBAY['devid'],$_EBAY['appid'],$_EBAY['certid'],$_EBAY['trade'],$_EBAY['compatabilityLevel'],$_EBAY['siteID'],"GetCategories");

			$requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
			$requestXmlBody .= '<GetCategoriesRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$requestXmlBody .= '<RequesterCredentials>';
			$requestXmlBody .= '<eBayAuthToken>'.$ebay_token.'</eBayAuthToken>';
			$requestXmlBody .= '</RequesterCredentials>';
			$requestXmlBody .= '<ErrorLanguage>en_US</ErrorLanguage>';
			$requestXmlBody .= '<WarningLevel>High</WarningLevel>';
			$requestXmlBody .= '<CategorySiteID>'.$site_id.'</CategorySiteID>';
			$requestXmlBody .= '<DetailLevel>ReturnAll</DetailLevel>';
			$requestXmlBody .= '</GetCategoriesRequest>';
			$responseXml = $ebayClient->sendHttpRequest($requestXmlBody);
			$responseXml = simplexml_load_string($responseXml);


			if(isset($responseXml->Ack) && $responseXml->Ack=="Success"){
				$categoriesArray = (isset($responseXml->CategoryArray->Category)) ? $responseXml->CategoryArray->Category : array();
				if($categoriesArray){
					EbayCategorynew::where('ebay_site',$site_id)->delete();
					foreach($categoriesArray as $category){
						$cronJob2 = CronJob::where('type','update_ebay_data')->first();
						if($cronJob2 && $cronJob2->do_stop) break;

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

						$category_name = (string) $category->CategoryName;
						$category_level = (string) $category->CategoryLevel;
						$ebay_category_id = (string) $category->CategoryID;
						$ebay_parent_category_id = (string) $category->CategoryParentID;
						$ebay_parent_category_id = ($ebay_category_id == $ebay_parent_category_id) ? 0 : $ebay_parent_category_id;
						$auto_pay_enabled = (string) $category->AutoPayEnabled;
						if($auto_pay_enabled == 'true') $auto_pay_enabled = 1;
						else $auto_pay_enabled = 0;
	
						$ebayCategory = EbayCategorynew::where('ebay_category_id',$ebay_category_id)->where('ebay_site',$site_id)->first();
						if($ebayCategory) continue;
						$parentCategory = EbayCategorynew::where('ebay_category_id',$ebay_parent_category_id)->where('ebay_site',$site_id)->first();
						$cParentCategory = $parentCategory;
						$category_tree = array();
						$category_tree[] = $category_name;
						while($cParentCategory){
							$category_tree[] = $cParentCategory->category_name;
							if($cParentCategory->ebay_parent_category_id){
								$cParentCategory = EbayCategorynew::where('ebay_category_id',$cParentCategory->ebay_parent_category_id)->where('ebay_site',$site_id)->first();
							}
							else{
								$cParentCategory = array();
							}
						}
						//$category_tree_name = $category_name;
						if($category_tree){
							$category_tree = array_reverse($category_tree,true);
							$category_tree_name = implode(" > ",$category_tree);
						}
						
						$parent_category_id = ($parentCategory) ? $parentCategory->id : 0;
						$parent_category_name = ($parentCategory) ? $parentCategory->category_name : '';
						$ebay_site = $site_id;
	
						$categoryData = array(
							"category_name"=>$category_name,
							"category_tree_name"=>$category_tree_name,
							"category_level"=>$category_level,
							"auto_pay_enabled"=>$auto_pay_enabled,
							"ebay_category_id"=>$ebay_category_id,
							"ebay_parent_category_id"=>$ebay_parent_category_id,
							"parent_category_id"=>$parent_category_id,
							"parent_category_name"=>$parent_category_name,
							"ebay_site"=>$ebay_site
						);
						EbayCategorynew::create($categoryData);
					}
				}
			}
			
	
			$ebayCategories = EbayCategorynew::with('childs')->where('ebay_site',$site_id)->where('is_last_level',0)->orderBy('category_level','desc')->get();
			if($ebayCategories->count() > 0){
				foreach($ebayCategories as $ebayCategory){
					if( (!$ebayCategory->Childs || !$ebayCategory->Childs->toArray()) && (!$ebayCategory->is_last_level) ){
						$ebayCategory->is_last_level = 1;
						$ebayCategory->save();
					}
				}
			}

		}

		$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(['success' => 'ebay category list updated'],200);
	}

  
	public function getEbayCategorySpecifics($category_id, $site_id = 0){
		$categoryAttributes = [];
		$environment = config('ebay.environment');

		$_EBAY = array(
			'trade'  => config('ebay.'.$environment.'trade'),
			'signin' => config('ebay.'.$environment.'signin'),
			'devid'  => config('ebay.'.$environment.'devid'),
			'appid'  => config('ebay.'.$environment.'appid'),
			'certid' => config('ebay.'.$environment.'certid'),
			'RuName' => config('ebay.'.$environment.'RuName'),
			'compatabilityLevel' => 859,
			'siteID' => $site_id
		);
		//$ebay_token = config('ebay.'.$environment.'token');
		
		$shopifyStore = AppHelper::getShopifyStore($request);
		if(!$shopifyStore) return response()->json(['status' => 'error','msg' => "invalid request"],403);
		
         $ebayAccounts = $shopifyStore->ebayAccounts()->where('is_valid','1')->get();
		$ebay_token = 	$ebayAccounts->access_token;
		$ebayCategory = ($category_id) ? EbayCategory::where('ebay_site',$site_id)->where('ebay_category_id',$category_id)->first() : [];

		if($ebayCategory){
			$ebayClient = new Ebay($ebay_token,$_EBAY['devid'],$_EBAY['appid'],$_EBAY['certid'],$_EBAY['trade'],$_EBAY['compatabilityLevel'],$_EBAY['siteID'],"GetCategorySpecifics");

			$requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
			$requestXmlBody .= '<GetCategorySpecificsRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$requestXmlBody .= '<RequesterCredentials>';
			$requestXmlBody .= '<eBayAuthToken>'.$ebay_token.'</eBayAuthToken>';
			$requestXmlBody .= '</RequesterCredentials>';
			$requestXmlBody .= '<ErrorLanguage>en_US</ErrorLanguage>';
			$requestXmlBody .= '<WarningLevel>High</WarningLevel>';
			$requestXmlBody .= '<CategoryID>'.$ebayCategory->ebay_category_id.'</CategoryID>';
			$requestXmlBody .= '<CategorySiteID>'.$site_id.'</CategorySiteID>';
			$requestXmlBody .= '<CategorySpecificsFileInfo>false</CategorySpecificsFileInfo>';
			$requestXmlBody .= '<DetailLevel>ReturnAll</DetailLevel>';
			$requestXmlBody .= '</GetCategorySpecificsRequest>';
			$responseXml = $ebayClient->sendHttpRequest($requestXmlBody);
			$responseXml = simplexml_load_string($responseXml);

			if(isset($responseXml->Ack) && isset($responseXml->Recommendations) && $responseXml->Recommendations){
				$recommendations = $responseXml->Recommendations;
				if($recommendations){
					foreach($recommendations as $recommendation){
						$categoryID = $recommendation->CategoryID;
						$nameRecommendations = (isset($recommendation->NameRecommendation)) ? $recommendation->NameRecommendation : array();
						if($nameRecommendations){
							if(!isset($nameRecommendations[0])) $nameRecommendations = array($nameRecommendations);
							foreach($nameRecommendations as $nameRecommendation){
								$atte_name = (string) $nameRecommendation->Name;
								$attr_type = "Text";
								$selection_mode = "FreeText";
								$max_values = 1;
								$min_values = 0;
								$attr_values = array();
								if(isset($nameRecommendation->ValidationRules) && $nameRecommendation->ValidationRules){
									$validationRules = $nameRecommendation->ValidationRules;
									if(!isset($validationRules[0])) $validationRules = array($validationRules);
									$attr_type = (string) $validationRules[0]->ValueType;
									$selection_mode = (string) $validationRules[0]->ValueType;
									$max_values = (int) $validationRules[0]->MaxValues;
									if(isset($validationRules[0]->MinValues)) $min_values = (int) $validationRules[0]->MinValues;
								}
								if(isset($nameRecommendation->ValueRecommendation) && $nameRecommendation->ValueRecommendation){
									$valueRecommendations = $nameRecommendation->ValueRecommendation;
									if(!isset($valueRecommendations[0])) $valueRecommendations = array($valueRecommendations);
									foreach($valueRecommendations as $valueRecommendation){
										$attr_values[] = (string) $valueRecommendation->Value;
									}
								}
								$categoryAttributes[] = array(
									"name" => $atte_name,
									"type" => $attr_type,
									"selection_mode" => $selection_mode,
									"max_values" => $max_values,
									"values" => $attr_values,
									"min_values" => $min_values
								);
							}
						}
						$ebayCategory->category_attributes = json_encode($categoryAttributes);
						$ebayCategory->save();
					}
				}
			}
		}

		return $categoryAttributes;
	}

	public function ebayCategorySpecifics(Request $request){
		$category_id = ($request->has('category_id') && $request->input('category_id') > 0) ? $request->input('category_id') : 0;
		$response = $this->getEbayCategorySpecifics($category_id);
		return $response;
	}

	public function updateEbayCategorySpecifics(Request $request){
		$cronJob = CronJob::where('type','update_ebay_data')->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();
		}

		$environment = config('ebay.environment');
		$siteIDs = array('0','2','3','15','16','23','71','77','100','101','123','146','186','193','201','203','205','207','210','211','212','216');
		if($request->has('siteid')){
			$siteid = ($request->has('siteid')) ? $request->input('siteid') : 0;
			$siteIDs = [$siteid];
		}
		else{
			$siteIDs = ['0'];
		}

		//$siteIDs = ['3'];
		$siteIDs = ['0'];

		$_EBAY = array(
			'trade'  => config('ebay.'.$environment.'trade'),
			'signin' => config('ebay.'.$environment.'signin'),
			'devid'  => config('ebay.'.$environment.'devid'),
			'appid'  => config('ebay.'.$environment.'appid'),
			'certid' => config('ebay.'.$environment.'certid'),
			'RuName' => config('ebay.'.$environment.'RuName'),
			'compatabilityLevel' => 859,
			'siteID' => 0
		);
		$site_id = 0;
    	//$ebay_token = config('ebay.'.$environment.'token');
		 $ebayAccounts = $shopifyStore->ebayAccounts()->where('is_valid','1')->get();
		$ebay_token = 	$ebayAccounts->access_token;
		foreach($siteIDs as $site_id){
			$cronJob2 = CronJob::where('type','update_ebay_data')->first();
			if($cronJob2 && $cronJob2->do_stop) break;

			$_EBAY['siteID'] = $site_id;
			$ebayClient = new Ebay($ebay_token,$_EBAY['devid'],$_EBAY['appid'],$_EBAY['certid'],$_EBAY['trade'],$_EBAY['compatabilityLevel'],$_EBAY['siteID'],"GetCategorySpecifics");
			$ebayCategories = EbayCategory::where('ebay_site',$site_id)->where('is_last_level',1)->get();
			if($ebayCategories->count() > 0){
				$catCount = 0;
				$catIDArr = array();
				$tcatcount = $ebayCategories->count() - 1;
				foreach($ebayCategories as $catkey => $ebayCategory){

					$cronJob2 = CronJob::where('type','update_ebay_data')->first();
					if($cronJob2 && $cronJob2->do_stop) break;

					$cronJob->last_updated_at = date("Y-m-d H:i:s");
					$cronJob->save();
					
					$catIDArr[] = $ebayCategory["ebay_category_id"];

					if($catCount >= 270 || $tcatcount <= $catkey){
						$requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
						$requestXmlBody .= '<GetCategorySpecificsRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
						$requestXmlBody .= '<RequesterCredentials>';
						$requestXmlBody .= '<eBayAuthToken>'.$ebay_token.'</eBayAuthToken>';
						$requestXmlBody .= '</RequesterCredentials>';
						$requestXmlBody .= '<ErrorLanguage>en_US</ErrorLanguage>';
						$requestXmlBody .= '<WarningLevel>High</WarningLevel>';
						foreach($catIDArr as $catID) $requestXmlBody .= '<CategoryID>'.$catID.'</CategoryID>';
						$requestXmlBody .= '<CategorySiteID>'.$site_id.'</CategorySiteID>';
						$requestXmlBody .= '<CategorySpecificsFileInfo>false</CategorySpecificsFileInfo>';
						$requestXmlBody .= '<DetailLevel>ReturnAll</DetailLevel>';
						$requestXmlBody .= '</GetCategorySpecificsRequest>';
						$responseXml = $ebayClient->sendHttpRequest($requestXmlBody);
						$responseXml = simplexml_load_string($responseXml);

						
						if(isset($responseXml->Ack) && isset($responseXml->Recommendations) && $responseXml->Recommendations){
							$recommendations = $responseXml->Recommendations;
							if($recommendations){
								foreach($recommendations as $recommendation){
									$categoryAttributes = array();
									$categoryID = $recommendation->CategoryID;
									$nameRecommendations = (isset($recommendation->NameRecommendation)) ? $recommendation->NameRecommendation : array();
									if($nameRecommendations){
										if(!isset($nameRecommendations[0])) $nameRecommendations = array($nameRecommendations);
										foreach($nameRecommendations as $nameRecommendation){
											$atte_name = (string) $nameRecommendation->Name;
											$attr_type = "Text";
											$selection_mode = "FreeText";
											$max_values = 1;
											$min_values = 0;
											$attr_values = array();
											if(isset($nameRecommendation->ValidationRules) && $nameRecommendation->ValidationRules){
												$validationRules = $nameRecommendation->ValidationRules;
												if(!isset($validationRules[0])) $validationRules = array($validationRules);
												$attr_type = (string) $validationRules[0]->ValueType;
												$selection_mode = (string) $validationRules[0]->ValueType;
												$max_values = (int) $validationRules[0]->MaxValues;
												if(isset($validationRules[0]->MinValues)) $min_values = (int) $validationRules[0]->MinValues;
											}
											if(isset($nameRecommendation->ValueRecommendation) && $nameRecommendation->ValueRecommendation){
												$valueRecommendations = $nameRecommendation->ValueRecommendation;
												if(!isset($valueRecommendations[0])) $valueRecommendations = array($valueRecommendations);
												foreach($valueRecommendations as $valueRecommendation){
													$attr_values[] = (string) $valueRecommendation->Value;
												}
											}
											$categoryAttributes[] = array(
												"name" => $atte_name,
												"type" => $attr_type,
												"selection_mode" => $selection_mode,
												"max_values" => $max_values,
												"values" => $attr_values,
												"min_values" => $min_values
											);
										}
									}
	
									$ebayCategory = EbayCategory::where('ebay_site',$site_id)->where('ebay_category_id',$categoryID)->first();
									if($ebayCategory){
										$ebayCategory->category_attributes = json_encode($categoryAttributes);
										$ebayCategory->save();
									}
								}
							}
						}
						$catCount = 0;
						$catIDArr = array();
					}

					$catCount++;
				}
			}
		}

		$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(['success' => 'ebay category specifics updated'],200);
    }

	public function updateEbayStoreCategory(Request $request){
		$environment = config('eb.environment');
		$_EBAY = array(
			'trade'  => config('ebay.'.$environment.'trade'),
			'signin' => config('ebay.'.$environment.'signin'),
			'devid'  => config('ebay.'.$environment.'devid'),
			'appid'  => config('ebay.'.$environment.'appid'),
			'certid' => config('ebay.'.$environment.'certid'),
			'RuName' => config('ebay.'.$environment.'RuName'),
			'compatabilityLevel' => 859,
			'siteID' => 0
		);

		$shopifyStores = ShopifyStore::where('status',"active")->get();
		//$shopifyStores = ShopifyStore::where('status',"active")->where('id',"16")->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);

				$ebayAccounts = $shopifyStore->ebayAccounts()->where('is_valid','1')->get();
				if($ebayAccounts->count() > 0){
					foreach($ebayAccounts as $ebayAccount){
						$site_id = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
						$_EBAY["siteID"] = $site_id;
						$ebay_token = $ebayAccount->access_token;
						$ebayClient = new Ebay($ebay_token,$_EBAY['devid'],$_EBAY['appid'],$_EBAY['certid'],$_EBAY['trade'],$_EBAY['compatabilityLevel'],$site_id,"GetStore");

						$requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
						$requestXmlBody .= '<GetStoreRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
						$requestXmlBody .= '<RequesterCredentials>';
						$requestXmlBody .= '<eBayAuthToken>'.$ebay_token.'</eBayAuthToken>';
						$requestXmlBody .= '</RequesterCredentials>';
						$requestXmlBody .= '<ErrorLanguage>en_US</ErrorLanguage>';
						$requestXmlBody .= '<WarningLevel>High</WarningLevel>';
						$requestXmlBody .= '</GetStoreRequest>';						
						$responseXml = $ebayClient->sendHttpRequest($requestXmlBody);
						$responseObj = simplexml_load_string($responseXml);
						if(isset($responseObj->Ack) && $responseObj->Ack=="Success"){
							$customCategories = (isset($responseObj->Store) && isset($responseObj->Store->CustomCategories) && isset($responseObj->Store->CustomCategories->CustomCategory)) ? $responseObj->Store->CustomCategories->CustomCategory : array();
							if($customCategories){
								EbayStoreCategory::where('store_id',$shopifyStore->id)->where('account_id',$ebayAccount->id)->delete();

								foreach($customCategories as $category){
									$category_name = (string) $category->Name;
									$ebay_category_id = (string) $category->CategoryID;
									$category_order = (string) $category->Order;

									$category_tree_name = $category_name;
									$category_level = 1;
									$ebay_parent_category_id = 0;
									$parent_category_id = 0;
									$parent_category_name = "";

									$categoryData = array(
										"category_name" => $category_name,
										"category_tree_name" => $category_tree_name,
										"category_level" => $category_level,
										"ebay_category_id" => $ebay_category_id,
										"ebay_parent_category_id" => $ebay_parent_category_id,
										"parent_category_id" => $parent_category_id,
										"parent_category_name" => $parent_category_name,
										"account_id" => $ebayAccount->id,
										"store_id" => $shopifyStore->id,
										"user_id" => $shopifyStore->user_id,
										"is_last_level" => 1
									);

									EbayStoreCategory::create($categoryData);									
								}
							}
						}
					}
				}
			}
		}

		return response()->json(['success' => 'ebay category list updated'],200);
    }

	public function updateEbayShippingService(Request $request){
	    Log::info('entered in ebay shipping service');
		$environment = config('ebay.environment');
		$siteIDs = array('0','2','3','15','16','23','71','77','100','101','123','146','186','193','201','203','205','207','210','211','212','216');
		if($request->has('siteid')){
			$siteid = ($request->has('siteid')) ? $request->input('siteid') : 0;
			$siteIDs = [$siteid];
		}

		$_EBAY = array(
			'trade'  => config('ebay.'.$environment.'trade'),
			'signin' => config('ebay.'.$environment.'signin'),
			'devid'  => config('ebay.'.$environment.'devid'),
			'appid'  => config('ebay.'.$environment.'appid'),
			'certid' => config('ebay.'.$environment.'certid'),
			'RuName' => config('ebay.'.$environment.'RuName'),
			'compatabilityLevel' => 859,
			'siteID' => 0
		);
		$site_id = 0;
		$ebayAccounts = $shopifyStore->ebayAccounts()->where('is_valid','1')->get();
		$ebay_token = 	$ebayAccounts->access_token;

		//$siteIDs = ['0'];
           Log::info($ebay_token);
		foreach($siteIDs as $site_id){
			$_EBAY['siteID'] = $site_id;
			$ebayClient = new Ebay($ebay_token,$_EBAY['devid'],$_EBAY['appid'],$_EBAY['certid'],$_EBAY['trade'],$_EBAY['compatabilityLevel'],$_EBAY['siteID'],"GeteBayDetails");
			$requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
			$requestXmlBody .= '<GeteBayDetailsRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$requestXmlBody .= '<RequesterCredentials>';
			$requestXmlBody .= '<eBayAuthToken>'.$ebay_token.'</eBayAuthToken>';
			$requestXmlBody .= '</RequesterCredentials>';
			$requestXmlBody .= '<ErrorLanguage>en_US</ErrorLanguage>';
			$requestXmlBody .= '<WarningLevel>High</WarningLevel>';
			$requestXmlBody .= '<DetailName>ShippingServiceDetails</DetailName>';
			$requestXmlBody .= '<DetailLevel>ReturnAll</DetailLevel>';
			$requestXmlBody .= '</GeteBayDetailsRequest>';
			$responseXml = $ebayClient->sendHttpRequest($requestXmlBody);
			$responseXml = simplexml_load_string($responseXml);

			if(isset($responseXml->Ack) && $responseXml->Ack=="Success"){
				if(isset($responseXml->ShippingServiceDetails)){
					$responseXml = (array)$responseXml;
					$shippingServiceDetails = $responseXml["ShippingServiceDetails"];
	
					EbayShippingService::where('ebay_site',$site_id)->delete();
					EbayShippingServiceType::where('ebay_site',$site_id)->delete();
					EbayShippingServiceTypeMapping::where('ebay_site',$site_id)->delete();
	
					$serviceTypes = array();
					foreach($shippingServiceDetails as $service){					
						$service_types = (is_object($service->ServiceType)) ? (array) $service->ServiceType : (string) $service->ServiceType;
						if(is_array($service_types)){
							foreach($service_types as $service_type){
								if(!in_array($service_type,$serviceTypes)) $serviceTypes[] = $service_type;
							}
						}
						else if(!in_array($service_types,$serviceTypes)){
							$serviceTypes[] = $service_types;
						}
					}
					if($serviceTypes){
						foreach($serviceTypes as $serviceType){
							$ebayShippingServiceTypeData = array("service_type"=>$serviceType,"ebay_site"=>$site_id);
							EbayShippingServiceType::create($ebayShippingServiceTypeData);
						}
	
						foreach($shippingServiceDetails as $service){
							$description = (string) $service->Description;
							$international_service = (isset($service->InternationalService) && $service->InternationalService) ? 1 : 0;
							$shipping_service = (string) $service->ShippingService;
							$shipping_service_id = (int) $service->ShippingServiceID;
							$shipping_time_max = (isset($service->ShippingTimeMax)) ? (int) $service->ShippingTimeMax : 0;
							$shipping_time_min = (isset($service->ShippingTimeMin)) ? (int) $service->ShippingTimeMin : 0;
							$valid_for_selling_flow = ($service->ValidForSellingFlow) ? 1 : 0;
							$shipping_carrier = (isset($service->ShippingCarrier)) ? (string) $service->ShippingCarrier : "";
							$weight_required = (isset($service->WeightRequired) && $service->WeightRequired) ? 1 : 0;
							$shipping_category = (isset($service->ShippingCategory)) ? (string) $service->ShippingCategory : "";
							
							
							$ebayShippingServiceData = array("description"=>$description,"international_service"=>$international_service,"shipping_service"=>$shipping_service,"shipping_service_id"=>$shipping_service_id,"shipping_time_max"=>$shipping_time_max,"shipping_time_min"=>$shipping_time_min,"valid_for_selling_flow"=>$valid_for_selling_flow,"shipping_carrier"=>$shipping_carrier,"weight_required"=>$weight_required,"shipping_category"=>$shipping_category,"ebay_site"=>$site_id);
							$ebayShippingService = EbayShippingService::create($ebayShippingServiceData);
							if($ebayShippingService->id){
								$service_types = (array) $service->ServiceType;
								if($service_types){
									foreach($service_types as $service_type){
										$ebayShippingServiceType = EbayShippingServiceType::where("service_type",$service_type)->where("ebay_site",$site_id)->first();
										if($ebayShippingServiceType){
											$ebayShippingServiceTypeMappingData = array("service_id" => $ebayShippingService->id,"service_type_id" => $ebayShippingServiceType->id,"ebay_site" => $site_id);
											EbayShippingServiceTypeMapping::create($ebayShippingServiceTypeMappingData);
											 Log::info('shipping serice ended');
										}
									}
								}
							}
						}
					}
				}
			}

		}


	}

	public function updateEbaySalesTaxStates(Request $request){
		$environment = config('ebay.environment');
		$siteIDs = array('0','2','3','15','16','23','71','77','100','101','123','146','186','193','201','203','205','207','210','211','212','216');
		if($request->has('siteid')){
			$siteid = ($request->has('siteid')) ? $request->input('siteid') : 0;
			$siteIDs = [$siteid];
		}

		$_EBAY = array(
			'trade'  => config('ebay.'.$environment.'trade'),
			'signin' => config('ebay.'.$environment.'signin'),
			'devid'  => config('ebay.'.$environment.'devid'),
			'appid'  => config('ebay.'.$environment.'appid'),
			'certid' => config('ebay.'.$environment.'certid'),
			'RuName' => config('ebay.'.$environment.'RuName'),
			'compatabilityLevel' => 859,
			'siteID' => 0
		);
		$site_id = 0;
		//$ebay_token = config('ebay.'.$environment.'token');
		$ebayAccounts = $shopifyStore->ebayAccounts()->where('is_valid','1')->get();
		$ebay_token = 	$ebayAccounts->access_token;

		//$siteIDs = ['0'];

		foreach($siteIDs as $site_id){

			$_EBAY['siteID'] = $site_id;
			$ebayClient = new Ebay($ebay_token,$_EBAY['devid'],$_EBAY['appid'],$_EBAY['certid'],$_EBAY['trade'],$_EBAY['compatabilityLevel'],$_EBAY['siteID'],"GeteBayDetails");
			$requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
			$requestXmlBody .= '<GeteBayDetailsRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$requestXmlBody .= '<RequesterCredentials>';
			$requestXmlBody .= '<eBayAuthToken>'.$ebay_token.'</eBayAuthToken>';
			$requestXmlBody .= '</RequesterCredentials>';
			$requestXmlBody .= '<ErrorLanguage>en_US</ErrorLanguage>';
			$requestXmlBody .= '<WarningLevel>High</WarningLevel>';
			$requestXmlBody .= '<DetailName>TaxJurisdiction</DetailName>';
			$requestXmlBody .= '<DetailLevel>ReturnAll</DetailLevel>';
			$requestXmlBody .= '</GeteBayDetailsRequest>';
			$responseXml = $ebayClient->sendHttpRequest($requestXmlBody);
			$responseXml = simplexml_load_string($responseXml);

			if(isset($responseXml->Ack) && $responseXml->Ack=="Success"){
				if(isset($responseXml->TaxJurisdiction)){
					$responseXml = (array)$responseXml;
					$taxJurisdictions = $responseXml["TaxJurisdiction"];
					EbaySalesTaxState::where('ebay_site',$site_id)->delete();
					foreach($taxJurisdictions as $taxJurisdiction){
						$ebaySalesTaxStatesData = array("ebay_state_id"=>$taxJurisdiction->JurisdictionID,"ebay_state_name"=>$taxJurisdiction->JurisdictionName,"ebay_site"=>$site_id);
						EbaySalesTaxState::create($ebaySalesTaxStatesData);
					}
				}
			}

		}
		
	}

	public function updateEbayPaymentOption(Request $request){
	     Log::info('Payment Option Starts');
		$siteIDs = array('0','2','3','15','16','23','71','77','100','101','123','146','186','193','201','203','205','207','210','211','212','216');
		if($request->has('siteid')){
			$siteid = ($request->has('siteid')) ? $request->input('siteid') : 0;
			$siteIDs = [$siteid];
		}
			
		$environment = config('ebay.environment');
		

		$_EBAY = array(
			'trade'  => config('ebay.'.$environment.'trade'),
			'signin' => config('ebay.'.$environment.'signin'),
			'devid'  => config('ebay.'.$environment.'devid'),
			'appid'  => config('ebay.'.$environment.'appid'),
			'certid' => config('ebay.'.$environment.'certid'),
			'RuName' => config('ebay.'.$environment.'RuName'),
			'compatabilityLevel' => 859,
			'siteID' => 0
		);
		$site_id = 0;
		//$ebay_token = config('ebay.'.$environment.'token');
		$ebayAccounts = $shopifyStore->ebayAccounts()->where('is_valid','1')->get();
		$ebay_token = 	$ebayAccounts->access_token;
		//$siteIDs = ['0'];
        Log::info($ebay_token);
		foreach($siteIDs as $site_id){

			$_EBAY['siteID'] = $site_id;
			$ebayClient = new Ebay($ebay_token,$_EBAY['devid'],$_EBAY['appid'],$_EBAY['certid'],$_EBAY['trade'],$_EBAY['compatabilityLevel'],$_EBAY['siteID'],"GeteBayDetails");
			
			$requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
			$requestXmlBody .= '<GeteBayDetailsRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$requestXmlBody .= '<RequesterCredentials>';
			$requestXmlBody .= '<eBayAuthToken>'.$ebay_token.'</eBayAuthToken>';
			$requestXmlBody .= '</RequesterCredentials>';
			$requestXmlBody .= '<ErrorLanguage>en_US</ErrorLanguage>';
			$requestXmlBody .= '<WarningLevel>High</WarningLevel>';
			$requestXmlBody .= '<DetailName>PaymentOptionDetails</DetailName>';
			$requestXmlBody .= '<DetailLevel>ReturnAll</DetailLevel>';
			$requestXmlBody .= '</GeteBayDetailsRequest>';
			$responseXml = $ebayClient->sendHttpRequest($requestXmlBody);
			$responseXml = simplexml_load_string($responseXml);

			//echo '<pre>';
			//print_r($responseXml);

			if(isset($responseXml->Ack) && $responseXml->Ack=="Success"){
				if(isset($responseXml->PaymentOptionDetails)){
					$responseXml = (array)$responseXml;
					$paymentOptionDetails = $responseXml["PaymentOptionDetails"];
					EbayPaymentOption::where('ebay_site',$site_id)->delete();			
					foreach($paymentOptionDetails as $paymentOption){					
						$payment_option = (string) $paymentOption->PaymentOption;
						$description = (string) $paymentOption->Description;
						$ebayPaymentOptionData = array("payment_option"=>$payment_option,"description"=>$description,"ebay_site"=>$site_id);
						EbayPaymentOption::create($ebayPaymentOptionData);
	                  Log::info('Payment Option ended');
					}
				}
			}

		}

		return response()->json(['success' => 'ebay payment options updated'],200);
	}

	public function updateEbayProfiles($store_id = NULL){
		$environment = config('eb.environment');
		$_EBAY = array(
			'trade'  => config('ebay.'.$environment.'trade'),
			'signin' => config('ebay.'.$environment.'signin'),
			'devid'  => config('ebay.'.$environment.'devid'),
			'appid'  => config('ebay.'.$environment.'appid'),
			'certid' => config('ebay.'.$environment.'certid'),
			'RuName' => config('ebay.'.$environment.'RuName'),
			'compatabilityLevel' => 859,
			'siteID' => 0
		);

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

		$errors = [];

		if($store_id) $shopifyStores = ShopifyStore::where('status',"active")->where('id',$store_id)->get();
		else $shopifyStores = ShopifyStore::where('status',"active")->get();
		
		$shopifyStores = ShopifyStore::where('status',"active")->where('id',16)->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);

				$ebayAccounts = $shopifyStore->ebayAccounts()->where('is_valid','1')->limit(1)->get();
				if($ebayAccounts->count() > 0){
					foreach($ebayAccounts as $ebayAccount){

						try{
							$site_id = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
							$_EBAY["siteID"] = $site_id;
							$ebay_token = $ebayAccount->access_token;

							$globalId = Constants\GlobalIds::US;
							if($site_id == 2){
								$globalId = Constants\GlobalIds::ENCA;
							}
							else if($site_id == 3){
								$globalId = Constants\GlobalIds::GB;
							}
							else if($site_id == 15){
								$globalId = Constants\GlobalIds::AU;
							}
							else if($site_id == 23){
								$globalId = Constants\GlobalIds::FRBE;
							}
							else if($site_id == 71){
								$globalId = Constants\GlobalIds::FR;
							}
							else if($site_id == 77){
								$globalId = Constants\GlobalIds::DE;
							}
							else if($site_id == 203){
								$globalId = Constants\GlobalIds::IN;
							}
							else if($site_id == 210){
								$globalId = Constants\GlobalIds::FRCA;
							}
							else if($site_id == 216){
								$globalId = Constants\GlobalIds::SG;
							}
							else if($site_id == 207){
								$globalId = Constants\GlobalIds::MY;
							}
							else if($site_id == 205){
								$globalId = Constants\GlobalIds::IE;
							}
							else if($site_id == 186){
								$globalId = Constants\GlobalIds::ES;
							}
							else if($site_id == 101){
								$globalId = Constants\GlobalIds::IT;
							}


							$ebayService = new Services\BusinessPoliciesManagementService([
								'credentials' => $ebayCredentials['credentials'],
								'authToken'   => $ebay_token,
								'globalId'    => $globalId
							]);

							$ebayRequest = new Types\GetSellerProfilesRequest();
							$ebayResponse = $ebayService->getSellerProfiles($ebayRequest);
							$ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();

							Log::info($ebayResponse);

							if($ebayResponse && $ebayResponse["ack"] == "Success"){
								$paymentProfiles = (isset($ebayResponse["paymentProfileList"])) ? $ebayResponse["paymentProfileList"]["PaymentProfile"] : array();

								if($paymentProfiles){
									foreach($paymentProfiles as $profile){
										$profileId = $profile["profileId"];
										$profileType = $profile["profileType"];
										$profileName = $profile["profileName"];
										$sellerProfile = EbaySellerProfile::where("store_id",$shopifyStore->id)->where("account_id",$ebayAccount->id)->where("seller_profile_id",$profileId)->where("type",$profileType)->first();
										if($sellerProfile){
											$sellerProfile->name = $profileName;
											$sellerProfile->save();
										}
										else{
											$proData = array(
												"seller_profile_id"=>$profileId,
												"name"=>$profileName,
												"type"=>$profileType,
												"account_id"=>$ebayAccount->id,
												"store_id"=>$shopifyStore->id,
												"user_id"=>$shopifyStore->user_id
											);
											EbaySellerProfile::create($proData);
										}
									}
								}

								$returnPolicyProfiles = (isset($ebayResponse["returnPolicyProfileList"])) ? $ebayResponse["returnPolicyProfileList"]["ReturnPolicyProfile"] : array();

								if($returnPolicyProfiles){
									foreach($returnPolicyProfiles as $profile){
										$profileId = $profile["profileId"];
										$profileType = $profile["profileType"];
										$profileName = $profile["profileName"];
										$sellerProfile = EbaySellerProfile::where("store_id",$shopifyStore->id)->where("account_id",$ebayAccount->id)->where("seller_profile_id",$profileId)->where("type",$profileType)->first();
										if($sellerProfile){
											$sellerProfile->name = $profileName;
											$sellerProfile->save();
										}
										else{
											$proData = array(
												"seller_profile_id"=>$profileId,
												"name"=>$profileName,
												"type"=>$profileType,
												"account_id"=>$ebayAccount->id,
												"store_id"=>$shopifyStore->id,
												"user_id"=>$shopifyStore->user_id
											);
											EbaySellerProfile::create($proData);
										}
									}
								}

								$shippingPolicyProfiles = (isset($ebayResponse["shippingPolicyProfile"])) ? $ebayResponse["shippingPolicyProfile"]["ShippingPolicyProfile"] : array();

								if($shippingPolicyProfiles){
									foreach($shippingPolicyProfiles as $profile){
										$profileId = $profile["profileId"];
										$profileType = $profile["profileType"];
										$profileName = $profile["profileName"];
										$sellerProfile = EbaySellerProfile::where("store_id",$shopifyStore->id)->where("account_id",$ebayAccount->id)->where("seller_profile_id",$profileId)->where("type",$profileType)->first();
										if($sellerProfile){
											$sellerProfile->name = $profileName;
											$sellerProfile->save();
										}
										else{
											$proData = array(
												"seller_profile_id"=>$profileId,
												"name"=>$profileName,
												"type"=>$profileType,
												"account_id"=>$ebayAccount->id,
												"store_id"=>$shopifyStore->id,
												"user_id"=>$shopifyStore->user_id
											);
											EbaySellerProfile::create($proData);
										}
									}
								}
							}
						}
						catch(\Exception $e){
							report($e);
							$errors[] = $e->getMessage();
						}						
					}
				}
			}
		}

		return response()->json(['success' => 'ebay seller profiles list updated',"errors" => $errors],200);
    }

	public function ebayPaymentOption(Request $request){
	    	Log::info('ebayPaymentOption starts here');
		$siteid = ($request->has('siteid')) ? $request->input('siteid') : 0;
		$ebayPaymentOptions = EbayPaymentOption::where('ebay_site',$siteid)->get();
		return response()->json(['payment_options' => $ebayPaymentOptions],200);
	}

	public function ebayShippingService(Request $request){
	    	Log::info('ebayShippingService starts here');
		$siteid = ($request->has('siteid')) ? $request->input('siteid') : 0;
		
		$ebayShippingServicesInternational = EbayShippingServiceType::with(array('ShippingServices'=>function($query){
			$query->select()->where('ebay_shipping_services.international_service',1);
		}))->where('ebay_site',$siteid)->get();

		$ebayShippingServicesNonInternational = EbayShippingServiceType::with(array('ShippingServices'=>function($query){
			$query->select()->where('ebay_shipping_services.international_service',0);
		}))->where('ebay_site',$siteid)->get();

		return response()->json(['international' => $ebayShippingServicesInternational,'non_international' => $ebayShippingServicesNonInternational],200);
	}

	public function getCategoryTreeName($category,$category_name){
		$pcategory = EbayCategory::find($category->parent_category_id);
		if($pcategory){
			$category_name[] = $pcategory->category_name;
			if($pcategory->parent_category_id > 0) $this->getCategoryTreeName($pcategory,$category_name);
		}
		return $category_name;
	}

	public function searchEbayCategory(Request $request){
		$query = ($request->has('query')) ? $request->input('query') : null;
		if(!$query || strlen($query) < 3) return response()->json(['status' => 'error','msg' => "query is required"],401);

		$shopifyStore = AppHelper::getShopifyStore($request);
		if(!$shopifyStore) return response()->json(['status' => 'error','msg' => "invalid request"],403);

		$ebayAccount = $shopifyStore->ebayAccounts()->where("is_valid","1")->first();
		if(!$ebayAccount) return response()->json(['status' => 'error','msg' => "invalid request"],403);

		$siteid = $ebayAccount->siteid;
		$account_id = $ebayAccount->id;
		$store_id = $shopifyStore->id;

		$ebayCategories = EbayCategory::where('category_tree_name','like',"%".$query."%")->where('ebay_site', $siteid)->where('is_last_level',1)->get();

		if($ebayCategories->count()){
			$ebayCategories = $ebayCategories->toArray();
			foreach($ebayCategories as $key => $ebayCategory){
				$category_attributes = ($ebayCategory["category_attributes"]) ? json_decode($ebayCategory["category_attributes"],true) : [];
				if(!$category_attributes || !isset($category_attributes[0]["min_values"])){
					$category_attributes = $this->getEbayCategorySpecifics($ebayCategory["ebay_category_id"],$siteid);
					$ebayCategories[$key]["category_attributes"] = $category_attributes;
				}
				else $ebayCategories[$key]["category_attributes"] = $category_attributes;
			}
		}
		return $ebayCategories;
    }

// 	public function ebaySpecificData(Request $request){
	  
// 	    Log::info('ebaySpecificData starts here');
// 		$shopifyStore = AppHelper::getShopifyStore($request);
// 		if(!$shopifyStore) return response()->json(['status' => 'error','msg' => "invalid request"],403);

// 		//$siteid = ($request->has('siteid')) ? $request->input('siteid') : 0;
// 		//$store_id = ($request->has('store_id')) ? $request->input('store_id') : 0;
// 		//$account_id = ($request->has('account_id')) ? $request->input('account_id') : 0;

// 		$ebayAccount = $shopifyStore->ebayAccounts()->where("is_valid","1")->first();
// 		if(!$ebayAccount) return response()->json(['status' => 'error','msg' => "invalid request"],403);

// 		$siteid = $ebayAccount->siteid;
// 		$account_id = $ebayAccount->id;
// 		$store_id = $shopifyStore->id;



// 		$ebaySpecificData = array();

// 		$payment_methods = array();
// 		$ebayPaymentOptions = EbayPaymentOption::where('ebay_site',$siteid)->get();
// 		if($ebayPaymentOptions->count() > 0){
// 			foreach($ebayPaymentOptions as $ebayPaymentOption){
// 			    Log::info('ebayPaymentOption found');
// 				$payment_methods[] = array("id" => $ebayPaymentOption->payment_option,"value" => $ebayPaymentOption->description);
// 			}
// 		}
// 		$ebaySpecificData["payment_methods"] = $payment_methods;


// 		$ebprofiles = $ebayAccount->ebaySellerProfiles()->get();
// 		if(!$ebprofiles || $ebprofiles->count() <= 0){
// 			$data = $this->updateEbayProfiles($shopifyStore->id);
// 		}

// 		$shipping_profiles = array();
// 		$shprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"SHIPPING")->get();
// 		if($shprofiles->count() > 0){
// 		     Log::info(' shipping profile found');
// 			foreach($shprofiles as $shprofile){
// 				$shipping_profiles[] = array("name"=>$shprofile->name,"id"=>$shprofile->id,"value"=>$shprofile->name);
// 			}
// 			/////////////////////////////////////////////////////////////////////////////////////
// 		    	Log::info(' sssssssssssssssssssssssssssss ');
// 				$dprofile = $shopifyStore->profiles()->first();
// 				if($dprofile->shipping_profile   == null){
// 				    Log::info('shipping profile in profile is empty ');
// 					$dprofile->shipping_profile   = $shprofiles[0]->id;
// 					$dprofile->save();
// 					Log::info('shipping profile is set to 1st shipping profile from ebay seller profile  ');
// 				}
// 				/////////////////////////////////////////////////////////////////////////////////////
// 		}
// 		$ebaySpecificData["shipping_profiles"] = $shipping_profiles;

// 		$payment_profiles = array();
// 		$pyprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"PAYMENT")->get();
// 		if($pyprofiles->count() > 0){
// 		     Log::info(' PAYMENT profile found');
// 			foreach($pyprofiles as $pyprofile){
// 				$payment_profiles[] = array("name"=>$pyprofile->name,"id"=>$pyprofile->id,"value"=>$pyprofile->name);
// 			}
// 			/////////////////////////////////////////////////////////////////////////////////////
// 				Log::info(' pppppppppppppppppppppppppp ');
// 			$dprofile = $shopifyStore->profiles()->first();
// 			if($dprofile->payment_profile == null){
// 			     Log::info('payment profile in profile is empty ');
// 				$dprofile->payment_profile = $pyprofiles[0]->id;
// 				$dprofile->save();
// 				Log::info('payment profile is set to 1st payment profile from ebay seller profile  ');
// 			}
// 		    /////////////////////////////////////////////////////////////////////////////////////
// 		}
// 		$ebaySpecificData["payment_profiles"] = $payment_profiles;

// 		$return_policy_profiles = array();
// 		$rpolprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"RETURN_POLICY")->get();
// 		if($rpolprofiles->count() > 0){
// 		     Log::info('RETURN_POLICY found');
// 			foreach($rpolprofiles as $rpolprofile){
// 				$return_policy_profiles[] = array("name"=>$rpolprofile->name,"id"=>$rpolprofile->id,"value"=>$rpolprofile->name);
// 			}
// 			/////////////////////////////////////////////////////////////////////////////////////
// 			Log::info(' rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr ');
// 			$dprofile = $shopifyStore->profiles()->first();
// 			if($dprofile->return_profile  == null){
// 			        Log::info('return profile in profile is empty ');
// 				$dprofile->return_profile  = $rpolprofiles[0]->id;
// 				$dprofile->save();
// 				Log::info('return profile is set to 1st return profile from ebay seller profile  ');
// 			}
// 		    /////////////////////////////////////////////////////////////////////////////////////
// 		}
// 		$ebaySpecificData["return_profiles"] = $return_policy_profiles;


// 		$domestic_shipping = array();
// 		$domestic_ship_services = array();
// 		$ebayShippingServicesNonInternational = EbayShippingServiceType::with(array('ShippingServices'=>function($query){
// 			$query->select()->where('ebay_shipping_services.international_service',0);
// 		}))->where('ebay_site',$siteid)->get();
// 		if($ebayShippingServicesNonInternational->count() > 0){
// 			foreach($ebayShippingServicesNonInternational as $ebayShippingServiceNonInternational){
// 				if($ebayShippingServiceNonInternational->ShippingServices->count() > 0){
// 					$domestic_shipping[] = array("id"=>$ebayShippingServiceNonInternational->service_type,"value"=>$ebayShippingServiceNonInternational->service_type);
// 					foreach($ebayShippingServiceNonInternational->ShippingServices as $shippingService){
// 						$domestic_ship_services[$ebayShippingServiceNonInternational->service_type][] = array("id"=>$shippingService->shipping_service,"value"=>$shippingService->description);
// 					}
// 				}
// 			}
// 			$domestic_shipping[] = array("id"=>"NotSpecified","value"=>"NotSpecified");
// 		}
// 		$ebaySpecificData["domestic_shipping"] = $domestic_shipping;
// 		$ebaySpecificData["domestic_ship_services"] = $domestic_ship_services;


// 		$intl_shipping = array();
// 		$intl_ship_services = array();
// 		$ebayShippingServicesInternational = EbayShippingServiceType::with(array('ShippingServices'=>function($query){
// 			$query->select()->where('ebay_shipping_services.international_service',1);
// 		}))->where('ebay_site',$siteid)->get();
// 		if($ebayShippingServicesInternational->count() > 0){
// 			foreach($ebayShippingServicesInternational as $ebayShippingServiceInternational){
// 				if($ebayShippingServiceInternational->ShippingServices->count() > 0){
// 					$intl_shipping[] = array("id"=>$ebayShippingServiceInternational->service_type,"value"=>$ebayShippingServiceInternational->service_type);
// 					foreach($ebayShippingServiceInternational->ShippingServices as $shippingService){
// 						$intl_ship_services[$ebayShippingServiceInternational->service_type][] = array("id"=>$shippingService->shipping_service,"value"=>$shippingService->description);
// 					}
// 				}
// 			}
// 			$intl_shipping[] = array("id"=>"NotSpecified","value"=>"NotSpecified");
// 		}
// 		$ebaySpecificData["intl_shipping"] = $intl_shipping;
// 		$ebaySpecificData["intl_ship_services"] = $intl_ship_services;

// 		$sales_tax_states = array();
// 		$ebaySalesTaxStates = EbaySalesTaxState::where('ebay_site',$siteid)->get();
// 		if($ebaySalesTaxStates->count() > 0){
// 			foreach($ebaySalesTaxStates as $ebaySalesTaxState){
// 				$sales_tax_states[] = array("id"=>$ebaySalesTaxState->ebay_state_id,"value"=>$ebaySalesTaxState->ebay_state_name);
// 			}
// 		}
// 		$ebaySpecificData["sales_tax_states"] = $sales_tax_states;

// 		$ebaySpecificData["ebay_categories"] = [];

// 		/*
// 		$ebayCategories = EbayCategory::select('id','category_tree_name','category_attributes')->where('ebay_site', $siteid)->where('is_last_level',1)->get();
		
// 		//$ebayCategories = EbayCategory::where('ebay_site', $siteid)->where('is_last_level',1)->limit(1000)->get();
// 		//$ebayCategories = EbayCategory::where('ebay_site', $siteid)->where('parent_category_id',0)->get();
// 		if($ebayCategories->count()){
// 			$ebayCategories = $ebayCategories->toArray();
// 			foreach($ebayCategories as $key => $ebayCategory){
// 				$ebayCategories[$key]["category_attributes"] = ($ebayCategory["category_attributes"]) ? json_decode($ebayCategory["category_attributes"],true) : [];
// 			}
// 		}
// 		$ebaySpecificData["ebay_categories"] = $ebayCategories;
// 		*/

// 		$ebaySpecificData["ebay_store_categories"] = array();
// 		if($store_id && $account_id){
// 			$ebayStoreCategories = $ebayAccount->ebayStoreCategories()->get();
// 			if($ebayStoreCategories->count() > 0){
// 				$ebaySpecificData["ebay_store_categories"] = $ebayStoreCategories->toArray();
// 			}
			
// 				Log::info(' ebayyyyyyyyyyyyyy ');
				
// 			$profile_specific = $shopifyStore->profiles()->first();
				
// 			if($profile_specific->item_specifics  == null || $profile_specific->item_specifics  == [] || $profile_specific->item_specifics  == ""){
			  
			   
// 				$ebay_category_1 = $profile_specific->ebay_category_1;
// 				$EbayAccount = EbayAccount::where('store_id',$store_id)->first();
// 					Log::info(' site idddddddddddddd '.$EbayAccount->siteid);
// 				$item_specific_data = EbayCategory::where('id',$ebay_category_1)->where('ebay_site', $EbayAccount->siteid)->first();

// 				//$item_specific_data = $shopifyStore->EbayCategory()->where("id",$ebay_category_1)->first();
// 				$item_specifics = $item_specific_data->category_attributes;
				
// 				   Log::info(' here is the item specifics '.json_encode($item_specifics,true));
// 			    //$arr = "";
// 				foreach(json_decode($item_specifics,true) as $item_specific){
// 				    if(isset($item_specific['values'][0])){
// 				        $name = $item_specific["name"];
// 				    	$values = $item_specific['values'][0];
// 					     //$arr[] = array($name => $values);
// 					      $arr[$name] = $values;
// 				    	  Log::info(' here is the name '.$name . ' and here is the first value of it '.$values);
// 				    }else{
// 				        continue;
// 				    }
					
// 				}
// 				 Log::info(' here is the array '.json_encode($arr,true));
				
// 				 $profile_specific->item_specifics  = json_encode($arr);
// 				 $profile_specific->save();
// 				Log::info(' done ');
// 			}
			
// 		}

// 		return response()->json($ebaySpecificData,200);
// 	}

public function ebaySpecificData(Request $request){
	    Log::info('ebaySpecificData starts here');
		$shopifyStore = AppHelper::getShopifyStore($request);
		if(!$shopifyStore) return response()->json(['status' => 'error','msg' => "invalid request"],403);

		//$siteid = ($request->has('siteid')) ? $request->input('siteid') : 0;
		//$store_id = ($request->has('store_id')) ? $request->input('store_id') : 0;
		//$account_id = ($request->has('account_id')) ? $request->input('account_id') : 0;

		$ebayAccount = $shopifyStore->ebayAccounts()->where("is_valid","1")->first();
		if(!$ebayAccount) return response()->json(['status' => 'error','msg' => "invalid request"],403);

		$siteid = $ebayAccount->siteid;
		$account_id = $ebayAccount->id;
		$store_id = $shopifyStore->id;



		$ebaySpecificData = array();

		$payment_methods = array();
		$ebayPaymentOptions = EbayPaymentOption::where('ebay_site',$siteid)->get();
		if($ebayPaymentOptions->count() > 0){
			foreach($ebayPaymentOptions as $ebayPaymentOption){
			    Log::info('ebayPaymentOption found');
				$payment_methods[] = array("id" => $ebayPaymentOption->payment_option,"value" => $ebayPaymentOption->description);
			}
		}
		$ebaySpecificData["payment_methods"] = $payment_methods;


		$ebprofiles = $ebayAccount->ebaySellerProfiles()->get();
		if(!$ebprofiles || $ebprofiles->count() <= 0){
			$data = $this->updateEbayProfiles($shopifyStore->id);
		}

		$shipping_profiles = array();
		$shprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"SHIPPING")->get();
		if($shprofiles->count() > 0){
		     Log::info(' shipping profile found');
			foreach($shprofiles as $shprofile){
				$shipping_profiles[] = array("name"=>$shprofile->name,"id"=>$shprofile->id,"value"=>$shprofile->name);
			}
			/////////////////////////////////////////////////////////////////////////////////////
		    	Log::info(' sssssssssssssssssssssssssssss ');
				$dprofile = $shopifyStore->profiles()->first();
				if($dprofile->shipping_profile   == null){
				    Log::info('shipping profile in profile is empty ');
					$dprofile->shipping_profile   = $shprofiles[0]->id;
					$dprofile->save();
					Log::info('shipping profile is set to 1st shipping profile from ebay seller profile  ');
				}
				/////////////////////////////////////////////////////////////////////////////////////
		}
		$ebaySpecificData["shipping_profiles"] = $shipping_profiles;

		$payment_profiles = array();
		$pyprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"PAYMENT")->get();
		if($pyprofiles->count() > 0){
		     Log::info(' PAYMENT profile found');
			foreach($pyprofiles as $pyprofile){
				$payment_profiles[] = array("name"=>$pyprofile->name,"id"=>$pyprofile->id,"value"=>$pyprofile->name);
			}
			/////////////////////////////////////////////////////////////////////////////////////
				Log::info(' pppppppppppppppppppppppppp ');
			$dprofile = $shopifyStore->profiles()->first();
			if($dprofile->payment_profile == null){
			     Log::info('payment profile in profile is empty ');
				$dprofile->payment_profile = $pyprofiles[0]->id;
				$dprofile->save();
				Log::info('payment profile is set to 1st payment profile from ebay seller profile  ');
			}
		    /////////////////////////////////////////////////////////////////////////////////////
		}
		$ebaySpecificData["payment_profiles"] = $payment_profiles;

		$return_policy_profiles = array();
		$rpolprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"RETURN_POLICY")->get();
		if($rpolprofiles->count() > 0){
		     Log::info('RETURN_POLICY found');
			foreach($rpolprofiles as $rpolprofile){
				$return_policy_profiles[] = array("name"=>$rpolprofile->name,"id"=>$rpolprofile->id,"value"=>$rpolprofile->name);
			}
			/////////////////////////////////////////////////////////////////////////////////////
			Log::info(' rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr ');
			$dprofile = $shopifyStore->profiles()->first();
			if($dprofile->return_profile  == null){
			        Log::info('return profile in profile is empty ');
				$dprofile->return_profile  = $rpolprofiles[0]->id;
				$dprofile->save();
				Log::info('return profile is set to 1st return profile from ebay seller profile  ');
			}
		    /////////////////////////////////////////////////////////////////////////////////////
		}
		$ebaySpecificData["return_profiles"] = $return_policy_profiles;


		$domestic_shipping = array();
		$domestic_ship_services = array();
		$ebayShippingServicesNonInternational = EbayShippingServiceType::with(array('ShippingServices'=>function($query){
			$query->select()->where('ebay_shipping_services.international_service',0);
		}))->where('ebay_site',$siteid)->get();
		if($ebayShippingServicesNonInternational->count() > 0){
			foreach($ebayShippingServicesNonInternational as $ebayShippingServiceNonInternational){
				if($ebayShippingServiceNonInternational->ShippingServices->count() > 0){
					$domestic_shipping[] = array("id"=>$ebayShippingServiceNonInternational->service_type,"value"=>$ebayShippingServiceNonInternational->service_type);
					foreach($ebayShippingServiceNonInternational->ShippingServices as $shippingService){
						$domestic_ship_services[$ebayShippingServiceNonInternational->service_type][] = array("id"=>$shippingService->shipping_service,"value"=>$shippingService->description);
					}
				}
			}
			$domestic_shipping[] = array("id"=>"NotSpecified","value"=>"NotSpecified");
		}
		$ebaySpecificData["domestic_shipping"] = $domestic_shipping;
		$ebaySpecificData["domestic_ship_services"] = $domestic_ship_services;


		$intl_shipping = array();
		$intl_ship_services = array();
		$ebayShippingServicesInternational = EbayShippingServiceType::with(array('ShippingServices'=>function($query){
			$query->select()->where('ebay_shipping_services.international_service',1);
		}))->where('ebay_site',$siteid)->get();
		if($ebayShippingServicesInternational->count() > 0){
			foreach($ebayShippingServicesInternational as $ebayShippingServiceInternational){
				if($ebayShippingServiceInternational->ShippingServices->count() > 0){
					$intl_shipping[] = array("id"=>$ebayShippingServiceInternational->service_type,"value"=>$ebayShippingServiceInternational->service_type);
					foreach($ebayShippingServiceInternational->ShippingServices as $shippingService){
						$intl_ship_services[$ebayShippingServiceInternational->service_type][] = array("id"=>$shippingService->shipping_service,"value"=>$shippingService->description);
					}
				}
			}
			$intl_shipping[] = array("id"=>"NotSpecified","value"=>"NotSpecified");
		}
		$ebaySpecificData["intl_shipping"] = $intl_shipping;
		$ebaySpecificData["intl_ship_services"] = $intl_ship_services;

		$sales_tax_states = array();
		$ebaySalesTaxStates = EbaySalesTaxState::where('ebay_site',$siteid)->get();
		if($ebaySalesTaxStates->count() > 0){
			foreach($ebaySalesTaxStates as $ebaySalesTaxState){
				$sales_tax_states[] = array("id"=>$ebaySalesTaxState->ebay_state_id,"value"=>$ebaySalesTaxState->ebay_state_name);
			}
		}
		$ebaySpecificData["sales_tax_states"] = $sales_tax_states;

		$ebaySpecificData["ebay_categories"] = [];

		/*
		$ebayCategories = EbayCategory::select('id','category_tree_name','category_attributes')->where('ebay_site', $siteid)->where('is_last_level',1)->get();

		//$ebayCategories = EbayCategory::where('ebay_site', $siteid)->where('is_last_level',1)->limit(1000)->get();
		//$ebayCategories = EbayCategory::where('ebay_site', $siteid)->where('parent_category_id',0)->get();
		if($ebayCategories->count()){
			$ebayCategories = $ebayCategories->toArray();
			foreach($ebayCategories as $key => $ebayCategory){
				$ebayCategories[$key]["category_attributes"] = ($ebayCategory["category_attributes"]) ? json_decode($ebayCategory["category_attributes"],true) : [];
			}
		}
		$ebaySpecificData["ebay_categories"] = $ebayCategories;
		*/

		$ebaySpecificData["ebay_store_categories"] = array();
		if($store_id && $account_id){
			$ebayStoreCategories = $ebayAccount->ebayStoreCategories()->get();
			if($ebayStoreCategories->count() > 0){
				$ebaySpecificData["ebay_store_categories"] = $ebayStoreCategories->toArray();
			}

				Log::info(' ebayyyyyyyyyyyyyy ');

			$profile_specific = $shopifyStore->profiles()->first();

			if($profile_specific->item_specifics  == null || $profile_specific->item_specifics  == [] || $profile_specific->item_specifics  == ""){


				$ebay_category_1 = $profile_specific->ebay_category_1;
				$EbayAccount = EbayAccount::where('store_id',$store_id)->first();
					Log::info(' site idddddddddddddd '.$EbayAccount->siteid);
				$item_specific_data = EbayCategory::where('id',$ebay_category_1)->where('ebay_site', $EbayAccount->siteid)->first();

				//$item_specific_data = $shopifyStore->EbayCategory()->where("id",$ebay_category_1)->first();
				$item_specifics = $item_specific_data->category_attributes;

				   Log::info(' here is the item specifics '.json_encode($item_specifics,true));
			    //$arr = "";
				foreach(json_decode($item_specifics,true) as $item_specific){
				    if(isset($item_specific['values'][0])){
				        $name = $item_specific["name"];
				    	$values = $item_specific['values'][0];
					     //$arr[] = array($name => $values);
					      $arr[$name] = $values;
				    	  Log::info(' here is the name '.$name . ' and here is the first value of it '.$values);
				    }else{
				        continue;
				    }

				}
				 Log::info(' here is the array '.json_encode($arr,true));

				 $profile_specific->item_specifics  = json_encode($arr);
				 $profile_specific->save();
				Log::info(' done ');
			}

		}

		return response()->json($ebaySpecificData,200);
	}

	public function updateEbayCategoryJson(Request $request){
		
		//$siteIDs = array('0','2','3','15','16','23','71','77','100','101','123','146','186','193','201','203','205','207','210','211','212','216');
		$siteIDs = array('100');
		
		if($request->has('siteid')){
			$siteid = ($request->input('siteid')) ? $request->input('siteid') : 0;
			$siteIDs = [$siteid];
		}
		
		foreach($siteIDs as $site_id){
			$ebayCategories = EbayCategory::select('id','category_tree_name')->where('is_last_level',1)->where('ebay_site',$site_id)->get();
			if($ebayCategories->count() > 0){
				$ebayCategories = $ebayCategories->toArray();
				/*foreach($ebayCategories as $key => $ebayCategory){
					$ebayCategories[$key]["category_attributes"] = ($ebayCategory["category_attributes"]) ? json_decode($ebayCategory["category_attributes"],true) : [];
				}*/
				file_put_contents("public/category-json/categories_".$site_id.".json",json_encode($ebayCategories));
			}
		}

		return response()->json(['success' => 'ebay category json updated'],200);
	}

// 	public function fetchEbayProfiles(Request $request){
// 	    	Log::info('fetchEbayProfiles starts here');
// 		$environment = config('eb.environment');
// 		$_EBAY = array(
// 			'trade'  => config('ebay.'.$environment.'trade'),
// 			'signin' => config('ebay.'.$environment.'signin'),
// 			'devid'  => config('ebay.'.$environment.'devid'),
// 			'appid'  => config('ebay.'.$environment.'appid'),
// 			'certid' => config('ebay.'.$environment.'certid'),
// 			'RuName' => config('ebay.'.$environment.'RuName'),
// 			'compatabilityLevel' => 859,
// 			'siteID' => 0
// 		);

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

// 		$shopify_url = $request->input("shopify_url");

// 		$shopifyStores = ($shopify_url) ? ShopifyStore::where('shopify_url',$shopify_url)->where('status',"active")->get() : [];
// 		if($shopifyStores && $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);

// 				$ebayAccounts = $shopifyStore->ebayAccounts()->where('is_valid','1')->limit(1)->get();
// 				if($ebayAccounts->count() > 0){
// 					foreach($ebayAccounts as $ebayAccount){
// 	           Log::info('found ebayAccount');
// 						try{
// 							$site_id = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
// 							$_EBAY["siteID"] = $site_id;
// 							$ebay_token = $ebayAccount->access_token;

// 							$globalId = Constants\GlobalIds::US;
// 							if($site_id == 2){
// 								$globalId = Constants\GlobalIds::ENCA;
// 							}
// 							else if($site_id == 3){
// 								$globalId = Constants\GlobalIds::GB;
// 							}
// 							else if($site_id == 15){
// 								$globalId = Constants\GlobalIds::AU;
// 							}
// 							else if($site_id == 23){
// 								$globalId = Constants\GlobalIds::FRBE;
// 							}
// 							else if($site_id == 71){
// 								$globalId = Constants\GlobalIds::FR;
// 							}
// 							else if($site_id == 77){
// 								$globalId = Constants\GlobalIds::DE;
// 							}
// 							else if($site_id == 203){
// 								$globalId = Constants\GlobalIds::IN;
// 							}
// 							else if($site_id == 210){
// 								$globalId = Constants\GlobalIds::FRCA;
// 							}
// 							else if($site_id == 216){
// 								$globalId = Constants\GlobalIds::SG;
// 							}
// 							else if($site_id == 207){
// 								$globalId = Constants\GlobalIds::MY;
// 							}
// 							else if($site_id == 205){
// 								$globalId = Constants\GlobalIds::IE;
// 							}
// 							else if($site_id == 186){
// 								$globalId = Constants\GlobalIds::ES;
// 							}
// 							else if($site_id == 101){
// 								$globalId = Constants\GlobalIds::IT;
// 							}


// 							$ebayService = new Services\BusinessPoliciesManagementService([
// 								'credentials' => $ebayCredentials['credentials'],
// 								'authToken'   => $ebay_token,
// 								'globalId'    => $globalId
// 							]);

// 							$ebayRequest = new Types\GetSellerProfilesRequest();
// 							$ebayResponse = $ebayService->getSellerProfiles($ebayRequest);
// 							$ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();

// 							Log::info("this is the ebay response from ebay ".json_encode($ebayResponse,true));

// 							if($ebayResponse && $ebayResponse["ack"] == "Success"){
//                                 Log::info("ebayy reponse recvd");
// 								EbaySellerProfile::where("store_id",$shopifyStore->id)->where("account_id",$ebayAccount->id)->delete();

// 								$paymentProfiles = (isset($ebayResponse["paymentProfileList"])) ? $ebayResponse["paymentProfileList"]["PaymentProfile"] : array();

// 								if($paymentProfiles){
// 									foreach($paymentProfiles as $profile){
// 									     Log::info("ebayy payment profile recvd");
// 										$profileId = $profile["profileId"];
// 										$profileType = $profile["profileType"];
// 										$profileName = $profile["profileName"];
// 										$sellerProfile = EbaySellerProfile::where("store_id",$shopifyStore->id)->where("account_id",$ebayAccount->id)->where("seller_profile_id",$profileId)->where("type",$profileType)->first();
// 										if($sellerProfile){
// 											$sellerProfile->name = $profileName;
// 											$sellerProfile->save();
// 										}
// 										else{
// 											$proData = array(
// 												"seller_profile_id"=>$profileId,
// 												"name"=>$profileName,
// 												"type"=>$profileType,
// 												"account_id"=>$ebayAccount->id,
// 												"store_id"=>$shopifyStore->id,
// 												"user_id"=>$shopifyStore->user_id
// 											);
// 											EbaySellerProfile::create($proData);
// 											 Log::info('$paymentProfiles created');
// 										}
// 									}
// 								}

// 								$returnPolicyProfiles = (isset($ebayResponse["returnPolicyProfileList"])) ? $ebayResponse["returnPolicyProfileList"]["ReturnPolicyProfile"] : array();
//                                 Log::info('returnPolicyProfiles started');
// 								if($returnPolicyProfiles){
// 								     Log::info("ebayy reponse return policy recvd");
// 									foreach($returnPolicyProfiles as $profile){
// 										$profileId = $profile["profileId"];
// 										$profileType = $profile["profileType"];
// 										$profileName = $profile["profileName"];
// 										$sellerProfile = EbaySellerProfile::where("store_id",$shopifyStore->id)->where("account_id",$ebayAccount->id)->where("seller_profile_id",$profileId)->where("type",$profileType)->first();
// 										if($sellerProfile){
// 										     Log::info("ebayy profile in in db already");
// 											$sellerProfile->name = $profileName;
// 											$sellerProfile->save();
// 										}
// 										else{
// 										     Log::info("ebayy profile was not in db already");
// 											$proData = array(
// 												"seller_profile_id"=>$profileId,
// 												"name"=>$profileName,
// 												"type"=>$profileType,
// 												"account_id"=>$ebayAccount->id,
// 												"store_id"=>$shopifyStore->id,
// 												"user_id"=>$shopifyStore->user_id
// 											);
// 											EbaySellerProfile::create($proData);
// 											 Log::info('returnPolicyProfiles saved as it was not in db');
// 										}
// 									}
// 								}

// 								$shippingPolicyProfiles = (isset($ebayResponse["shippingPolicyProfile"])) ? $ebayResponse["shippingPolicyProfile"]["ShippingPolicyProfile"] : array();
//                                 Log::info('shippingPolicyProfiles starts');
// 								if($shippingPolicyProfiles){
// 									foreach($shippingPolicyProfiles as $profile){
// 										$profileId = $profile["profileId"];
// 										$profileType = $profile["profileType"];
// 										$profileName = $profile["profileName"];
// 										$sellerProfile = EbaySellerProfile::where("store_id",$shopifyStore->id)->where("account_id",$ebayAccount->id)->where("seller_profile_id",$profileId)->where("type",$profileType)->first();
// 										if($sellerProfile){
// 											$sellerProfile->name = $profileName;
// 											$sellerProfile->save();
// 										}
// 										else{
// 											$proData = array(
// 												"seller_profile_id"=>$profileId,
// 												"name"=>$profileName,
// 												"type"=>$profileType,
// 												"account_id"=>$ebayAccount->id,
// 												"store_id"=>$shopifyStore->id,
// 												"user_id"=>$shopifyStore->user_id
// 											);
// 											EbaySellerProfile::create($proData);
// 											Log::info('shippingPolicyProfiles ended');
// 										}
// 									}
// 								}
// 							}
// 						}
// 						catch(\Exception $e){
// 							report($e);
// 							$errors[] = $e->getMessage();
// 						}						
// 					}
// 				}
// 			}
// 		}

// 		$ebayAccount = $shopifyStore->ebayAccounts()->where("is_valid","1")->first();
		
// 		$shipping_profiles = array();
// 		$shprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"SHIPPING")->get();
// 		if($shprofiles->count() > 0){
// 			foreach($shprofiles as $shprofile){
// 				$shipping_profiles[] = array("name"=>$shprofile->name,"id"=>$shprofile->id,"value"=>$shprofile->name);
// 			}
// 		}
// 		$ebaySpecificData["shipping_profiles"] = $shipping_profiles;

// 		$payment_profiles = array();
// 		$pyprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"PAYMENT")->get();
// 		if($pyprofiles->count() > 0){
// 			foreach($pyprofiles as $pyprofile){
// 				$payment_profiles[] = array("name"=>$pyprofile->name,"id"=>$pyprofile->id,"value"=>$pyprofile->name);
// 			}
// 		}
// 		$ebaySpecificData["payment_profiles"] = $payment_profiles;

// 		$return_policy_profiles = array();
// 		$rpolprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"RETURN_POLICY")->get();
// 		if($rpolprofiles->count() > 0){
// 			foreach($rpolprofiles as $rpolprofile){
// 				$return_policy_profiles[] = array("name"=>$rpolprofile->name,"id"=>$rpolprofile->id,"value"=>$rpolprofile->name);
// 			}
// 		}
// 		$ebaySpecificData["return_profiles"] = $return_policy_profiles;


// 		return response()->json($ebaySpecificData,200);
//     }


public function fetchEbayProfiles(Request $request){
	    	Log::info('fetchEbayProfiles starts here');
		$environment = config('eb.environment');
		$_EBAY = array(
			'trade'  => config('ebay.'.$environment.'trade'),
			'signin' => config('ebay.'.$environment.'signin'),
			'devid'  => config('ebay.'.$environment.'devid'),
			'appid'  => config('ebay.'.$environment.'appid'),
			'certid' => config('ebay.'.$environment.'certid'),
			'RuName' => config('ebay.'.$environment.'RuName'),
			'compatabilityLevel' => 859,
			'siteID' => 0
		);

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

		$shopifyStore = [];
		$ebaySpecificData = array();

		$shopify_url = $request->input("shopify_url");

		$shopifyStores = ($shopify_url) ? ShopifyStore::where('shopify_url',$shopify_url)->where('status',"active")->get() : [];
		if($shopifyStores && $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);

				$ebayAccounts = $shopifyStore->ebayAccounts()->where('is_valid','1')->limit(1)->get();
				if($ebayAccounts->count() > 0){
					foreach($ebayAccounts as $ebayAccount){
	           Log::info('found ebayAccount');
						try{
							$site_id = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
							$_EBAY["siteID"] = $site_id;
							$ebay_token = $ebayAccount->access_token;

							$globalId = Constants\GlobalIds::US;
							if($site_id == 2){
								$globalId = Constants\GlobalIds::ENCA;
							}
							else if($site_id == 3){
								$globalId = Constants\GlobalIds::GB;
							}
							else if($site_id == 15){
								$globalId = Constants\GlobalIds::AU;
							}
							else if($site_id == 23){
								$globalId = Constants\GlobalIds::FRBE;
							}
							else if($site_id == 71){
								$globalId = Constants\GlobalIds::FR;
							}
							else if($site_id == 77){
								$globalId = Constants\GlobalIds::DE;
							}
							else if($site_id == 203){
								$globalId = Constants\GlobalIds::IN;
							}
							else if($site_id == 210){
								$globalId = Constants\GlobalIds::FRCA;
							}
							else if($site_id == 216){
								$globalId = Constants\GlobalIds::SG;
							}
							else if($site_id == 207){
								$globalId = Constants\GlobalIds::MY;
							}
							else if($site_id == 205){
								$globalId = Constants\GlobalIds::IE;
							}
							else if($site_id == 186){
								$globalId = Constants\GlobalIds::ES;
							}
							else if($site_id == 101){
								$globalId = Constants\GlobalIds::IT;
							}


							$ebayService = new Services\BusinessPoliciesManagementService([
								'credentials' => $ebayCredentials['credentials'],
								'authToken'   => $ebay_token,
								'globalId'    => $globalId
							]);

							$ebayRequest = new Types\GetSellerProfilesRequest();
							$ebayResponse = $ebayService->getSellerProfiles($ebayRequest);
							$ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();

							Log::info("this is the ebay response from ebay ".json_encode($ebayResponse,true));

							if($ebayResponse && $ebayResponse["ack"] == "Success"){
                                Log::info("ebayy reponse recvd");
								EbaySellerProfile::where("store_id",$shopifyStore->id)->where("account_id",$ebayAccount->id)->delete();

								$paymentProfiles = (isset($ebayResponse["paymentProfileList"])) ? $ebayResponse["paymentProfileList"]["PaymentProfile"] : array();

								if($paymentProfiles){
									foreach($paymentProfiles as $profile){
									     Log::info("ebayy payment profile recvd");
										$profileId = $profile["profileId"];
										$profileType = $profile["profileType"];
										$profileName = $profile["profileName"];
										$sellerProfile = EbaySellerProfile::where("store_id",$shopifyStore->id)->where("account_id",$ebayAccount->id)->where("seller_profile_id",$profileId)->where("type",$profileType)->first();
										if($sellerProfile){
											$sellerProfile->name = $profileName;
											$sellerProfile->save();
										}
										else{
											$proData = array(
												"seller_profile_id"=>$profileId,
												"name"=>$profileName,
												"type"=>$profileType,
												"account_id"=>$ebayAccount->id,
												"store_id"=>$shopifyStore->id,
												"user_id"=>$shopifyStore->user_id
											);
											EbaySellerProfile::create($proData);
											 Log::info('$paymentProfiles created');
										}
									}
								}

								$returnPolicyProfiles = (isset($ebayResponse["returnPolicyProfileList"])) ? $ebayResponse["returnPolicyProfileList"]["ReturnPolicyProfile"] : array();
                                Log::info('returnPolicyProfiles started');
								if($returnPolicyProfiles){
								     Log::info("ebayy reponse return policy recvd");
									foreach($returnPolicyProfiles as $profile){
										$profileId = $profile["profileId"];
										$profileType = $profile["profileType"];
										$profileName = $profile["profileName"];
										$sellerProfile = EbaySellerProfile::where("store_id",$shopifyStore->id)->where("account_id",$ebayAccount->id)->where("seller_profile_id",$profileId)->where("type",$profileType)->first();
										if($sellerProfile){
										     Log::info("ebayy profile in in db already");
											$sellerProfile->name = $profileName;
											$sellerProfile->save();
										}
										else{
										     Log::info("ebayy profile was not in db already");
											$proData = array(
												"seller_profile_id"=>$profileId,
												"name"=>$profileName,
												"type"=>$profileType,
												"account_id"=>$ebayAccount->id,
												"store_id"=>$shopifyStore->id,
												"user_id"=>$shopifyStore->user_id
											);
											EbaySellerProfile::create($proData);
											 Log::info('returnPolicyProfiles saved as it was not in db');
										}
									}
								}

								$shippingPolicyProfiles = (isset($ebayResponse["shippingPolicyProfile"])) ? $ebayResponse["shippingPolicyProfile"]["ShippingPolicyProfile"] : array();
                                Log::info('shippingPolicyProfiles starts');
								if($shippingPolicyProfiles){
									foreach($shippingPolicyProfiles as $profile){
										$profileId = $profile["profileId"];
										$profileType = $profile["profileType"];
										$profileName = $profile["profileName"];
										$sellerProfile = EbaySellerProfile::where("store_id",$shopifyStore->id)->where("account_id",$ebayAccount->id)->where("seller_profile_id",$profileId)->where("type",$profileType)->first();
										if($sellerProfile){
											$sellerProfile->name = $profileName;
											$sellerProfile->save();
										}
										else{
											$proData = array(
												"seller_profile_id"=>$profileId,
												"name"=>$profileName,
												"type"=>$profileType,
												"account_id"=>$ebayAccount->id,
												"store_id"=>$shopifyStore->id,
												"user_id"=>$shopifyStore->user_id
											);
											EbaySellerProfile::create($proData);
											Log::info('shippingPolicyProfiles ended');
										}
									}
								}
							}
						}
						catch(\Exception $e){
							report($e);
							$errors[] = $e->getMessage();
						}
					}
				}
			}
		}

		$ebayAccount = $shopifyStore->ebayAccounts()->where("is_valid","1")->first();

		$shipping_profiles = array();
		$shprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"SHIPPING")->get();
		if($shprofiles->count() > 0){
			foreach($shprofiles as $shprofile){
				$shipping_profiles[] = array("name"=>$shprofile->name,"id"=>$shprofile->id,"value"=>$shprofile->name);
			}
		}
		$ebaySpecificData["shipping_profiles"] = $shipping_profiles;

		$payment_profiles = array();
		$pyprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"PAYMENT")->get();
		if($pyprofiles->count() > 0){
			foreach($pyprofiles as $pyprofile){
				$payment_profiles[] = array("name"=>$pyprofile->name,"id"=>$pyprofile->id,"value"=>$pyprofile->name);
			}
		}
		$ebaySpecificData["payment_profiles"] = $payment_profiles;

		$return_policy_profiles = array();
		$rpolprofiles = $ebayAccount->ebaySellerProfiles()->where('type',"RETURN_POLICY")->get();
		if($rpolprofiles->count() > 0){
			foreach($rpolprofiles as $rpolprofile){
				$return_policy_profiles[] = array("name"=>$rpolprofile->name,"id"=>$rpolprofile->id,"value"=>$rpolprofile->name);
			}
		}
		$ebaySpecificData["return_profiles"] = $return_policy_profiles;


		return response()->json($ebaySpecificData,200);
    }

public function testnewreturn(){
	/*	$validationRules = [
			'name' => 'required',
			'payment_methods' => 'required',
			'immediate_payment' => 'in:0,1',
			'paypal_email' => 'email'
		];
		$validator = Validator::make($request->all(),$validationRules);
		
		if($validator->fails()) return response()->json(['status' => 'error', 'msg' => '', 'errors' => $validator->errors()],406);
	*/
	$ebayAccount = EbayAccount::where('is_valid',1)->where('store_id',1366 )->orderBy('created_at','DESC')->first();
		if(!$ebayAccount) return response()->json(['status' => 'error', 'msg' => 'invalid request'],403);

			$environment = config('eb.environment');
		$_EBAY = array(
			'trade'  => config('ebay.'.$environment.'trade'),
			'signin' => config('ebay.'.$environment.'signin'),
			'devid'  => config('ebay.'.$environment.'devid'),
			'appid'  => config('ebay.'.$environment.'appid'),
			'certid' => config('ebay.'.$environment.'certid'),
			'RuName' => config('ebay.'.$environment.'RuName'),
			'compatabilityLevel' => 859,
			'siteID' => 0
		);

		$ebayCredentials = array(
			'credentials' => [
				'devId' => config('ebay.'.$environment.'devid'),
				'appId' => config('ebay.'.$environment.'appid'),
				'certId' => config('ebay.'.$environment.'certid'),
				'authToken' => '',
			],
			'authToken' => '',
			'oauthUserToken' => '',
			'ruName' => config('ebay.'.$environment.'RuName')
		);
		try{
			$payment_methods = "PayPal";
			//if(!is_array($payment_methods)) $payment_methods = explode(",",$payment_methods);

			$payment_instructions = "testnew";
			$paypal_email = 'infoshorejpr@gmail.com';
			$profile_name = 'new payment';
			$profile_type = "paymentProfile";
			$immediate_payment = 1;

			$site_id = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
			$_EBAY["siteID"] = $site_id;

			$ebay_token = $ebayAccount->access_token;

			$globalId = Constants\GlobalIds::US;

			$ebayService = new Services\BusinessPoliciesManagementService([
								'credentials' => $ebayCredentials['credentials'],
								'authToken'   => $ebay_token,
								'globalId'    => $globalId
							]);
		$ebayRequest = new Types\AddSellerProfileRequest();
			$paymentProfile = new Types\PaymentProfile();

			$paymentInfo = new Types\PaymentInfo(); 
			$paymentInfo->acceptedPaymentMethod =  array('PAYPAL'); 
             // $paymentInfo->PaymentOption = Enums\BuyerPaymentMethodCodeType::C_PAY_PAL;

			
		//	 Log::channel('PolicyControllerLog')->info("ebay_paymentInfo ".json_encode($paymentInfo,true));
		
			if($payment_instructions) $paymentInfo->paymentInstructions = "newtextnew";
			if($paypal_email) $paymentInfo->paypalEmailAddress = array('infoshorejpr@gmail.com');
			if($immediate_payment == "1") $paymentInfo->immediatePay = true;
			else $paymentInfo->immediatePay = false;

			$paymentProfile->paymentInfo = $paymentInfo;
			$paymentProfile->profileName = "vdsgsfsdhf";
			$paymentProfile->profileType = "PAYMENT";

			$ebayRequest->paymentProfile = $paymentProfile;

			//file_put_contents("profilereq.json",json_encode($ebayRequest->toArray()));
             
             // Log::channel('PolicyControllerLog')->info("ebay Requestttttttttttt".json_encode($ebayRequest->toArray(),true));
              
			$ebayResponse = $ebayService->addSellerProfile($ebayRequest);
			print_r($ebayResponse);
        die();

			if($ebayResponse && isset($ebayResponse->Ack) && $ebayResponse->Ack !== 'Failure'){
				return response()->json(['status' => 'success','msg' => 'payment profile added successfully'],200);
			}
		}
		catch(\Exception $e){
			report($e);
			return response()->json(['status' => 'error','msg' => $e->getMessage()],406);
		}
	}

	public function simpleXmlToArray($xmlObject){
		$array = [];
		foreach($xmlObject->children() as $node){
			$array[$node->getName()] = is_array($node) ? simplexml_to_array($node) : (string) $node;
		}
		return $array;
	}
	
}