<?php
set_time_limit(0);
ini_set('memory_limit', '-1');
require_once("includes/config.php");

require_once("includes/etsyv3/vendor/autoload.php");
use OAuth\Client;

$logfile = fopen("logs/updateshopifyinventory.txt", "a+") or die("Unable to open log file!");
addlog("Execution Started", "INFO");

$cronQuery = $conn->query("select isrunning from crons where crontype = 'updateshopifyinventory_v3'");
$cronrow = $cronQuery->fetch_assoc();
if($cronrow['isrunning'] == 1){
	@mail("khariwal.rohit@gmail.com", "ETSY: updateshopifyinventory_v3: Cron already running", "updateshopifyinventory_v3: Cron already running");
	die("");
}

$conn->query("update crons set lastrun = now(), isrunning = 1 where crontype = 'updateshopifyinventory_v3'");

$result = $conn->query("select u.id as user_id, u.shopurl, u.token, s.inventory_sync, s.price_sync, s.markupenabled, s.markuptype, s.markupval, s.markupvalfixed, s.markupround, s.outofstock_action, eb.*, s.shopifylocationid from users u, setting s, etsy_keys eb where eb.user_id = u.id and s.user_id = u.id and eb.valid = 1 and (s.inventory_sync = 1 or s.price_sync = 1) and u.status = 'active' and u.installationstatus = 1 and eb.apiversion = 'v3' and u.id  = 1552");

if ($result->num_rows > 0) {// 
	while($row = $result->fetch_assoc()) {
	    $markupenabled = $row['markupenabled'];
		$markuptype = $row['markuptype'];
		$markupval = $row['markupval'];
		$markupvalfixed = $row['markupvalfixed'];
		$markupround = $row['markupround'];
		
		$id = $row['user_id'];
		$shopurl = $row['shopurl'];
		$token = $row['token'];		
		$shop_id = $row['shop_id'];
		$access_token = $row['access_token'];
		$refresh_token = $row['refresh_token'];
		$location_id = $row['shopifylocationid'];
		if($location_id == ""){
			$location_id = getMainLocation($id, $shopurl, $token);
			if(!$location_id){
				@mail("khariwal.rohit@gmail.com", "ETSY:updateshopifyinventory_v3 Location ID missing", $id);
				continue;
			}
		}
		$inventory_sync = $row['inventory_sync'];
		$outofstock_action = $row['outofstock_action'];
		$price_sync = $row['price_sync'];		
		addlog("fetchFromEtsy: Process started for user_id - ".$id, "INFO");
		fetchFromEtsy($id, $shop_id, $access_token, $refresh_token);
		addlog("updateInventoryAndPrice: Process started for user_id - ".$id, "INFO");
		mysqli_autocommit($conn, FALSE);
		// updateInventoryAndPrice($id, $token, $shopurl, $inventory_sync,$outofstock_action, $price_sync, $location_id, $markupenabled, $markuptype, $markupval, $markupvalfixed, $markupround);  
     echo "price updated"; 	
		mysqli_commit($conn);		
	}
}
mysqli_autocommit($conn, TRUE);
$conn->query("update crons set isrunning = 0 where crontype = 'updateshopifyinventory_v3'");


function fetchFromEtsy($user_id, $shop_id, $access_token, $refresh_token) {
	global $conn, $etsyConfig;
	$api_key = $etsyConfig['api_key'];
	// Prepare existing data in array
	$existingItems = array();
	$result = $conn->query("select * from product_variants where user_id = ".$user_id);
	
	if($result->num_rows > 0){
		while($row = $result->fetch_assoc()){
			$product_id = $row['product_id'];
			$variant_id = $row['id'];
			$option1val = $row['option1val'];
			$option2val = $row['option2val'];
			$option3val = $row['option3val'];
			$price = $row['price'];
			$quantity = $row['quantity'];
		
			$productResult = $conn->query("select * from products where product_id = ".$product_id." and user_id = ".$user_id);
			if($productResult->num_rows < 1){
				continue;
			}
			$productRow = $productResult->fetch_assoc();
			$etsylistingid = $productRow['etsylistingid'];
			$option1name = $productRow['option1name'];
			$option2name = $productRow['option2name'];
			$option3name = $productRow['option3name'];

			$temp = array("etsylistingid" => $etsylistingid, "price" => $price, "quantity" => $quantity, "variant_id" => $variant_id);
			if(strlen($option1name) > 0){
				$temp[$option1name] = $option1val;
			}
			if(strlen($option2name) > 0){
				$temp[$option2name] = $option2val;
			}
			if(strlen($option3name) > 0){
				$temp[$option3name] = $option3val;
			}
			$existingItems[$etsylistingid][] = $temp;		
		}
	}	
	
	$productResult = $conn->query("select * from products where user_id = ".$user_id);
	if($productResult->num_rows > 0){
		while($productRow = $productResult->fetch_assoc()){
			$product_id = $productRow['product_id'];
			$etsylistingid = $productRow['etsylistingid'];
			if(!array_key_exists($etsylistingid, $existingItems)){
				continue;
			}
			$existingItemData = $existingItems[$etsylistingid];
		//	print_r($existingItemData);
			try {
    			$header = array("Authorization: Bearer ".$access_token,"x-api-key: ".$api_key);
			    $curl = curl_init();
				curl_setopt_array($curl, array(
                    CURLOPT_URL => 'https://openapi.etsy.com/v3/application/listings/'.$etsylistingid.'/inventory',
                    CURLOPT_HTTPHEADER => $header,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_RETURNTRANSFER => true
                ));
                $response_body1 = curl_exec($curl);
                curl_close($curl);	
                $inventoryData = json_decode($response_body1);
               
                if(isset($inventoryData->error) && $inventoryData->error == 'invalid_token'){  	 
                    $client = new Etsy\OAuth\Client($api_key);
                    $refreshTokenArray = $client->refreshAccessToken($refresh_token);
                    if(isset($refreshTokenArray->access_token)){
                        $access_token = $refreshTokenArray->access_token;
                        $refresh_token = $refreshTokenArray->refresh_token;
                        $conn->query("update etsy_keys set access_token = '".mysqli_real_escape_string($conn, $access_token)."',refresh_token = '".mysqli_real_escape_string($conn, $refresh_token)."', updated_at = now() where user_id = ".$user_id); 
                        $header = array("Authorization: Bearer ".$access_token,"x-api-key: ".$api_key);
        			    $curl = curl_init();
        				curl_setopt_array($curl, array(
                            CURLOPT_URL => 'https://openapi.etsy.com/v3/application/listings/'.$etsylistingid.'/inventory',
                            CURLOPT_HTTPHEADER => $header,
                            CURLOPT_SSL_VERIFYPEER => false,
                            CURLOPT_RETURNTRANSFER => true
                        ));
                        $response_body1 = curl_exec($curl);
                        curl_close($curl);	
                        $inventoryData = json_decode($response_body1);
                    }
                }
    			
        		//print_r($inventoryData);
			} catch (OAuthException $e) {
    			print_r($e);
    			error_log($e->getMessage());
    			error_log(print_r($oauth->getLastResponse(), true));
    			error_log(print_r($oauth->getLastResponseInfo(), true));
		    }
		    print_r($inventoryData);
			if($productRow['option1name'] == ""){ // Without variants
				$price = 0.0;
				$quantity = 0;
                if(isset($inventoryData->products[0]->offerings[0]->price->amount)){
					$price = $inventoryData->products[0]->offerings[0]->price->amount / 100;
					$price = str_replace(",","",$price);
				}
				
				if(isset($inventoryData->products[0]->offerings[0]->quantity)){
					$quantity = $inventoryData->products[0]->offerings[0]->quantity;
				}
				$priceflag = 0;
				$quantityflag = 0;
				if($price > 0 && $price != $existingItemData[0]['price']){
					$priceflag = 1;
				}				
				if($quantity != $existingItemData[0]['quantity']){
					$quantityflag = 1;
				}					
				 if($priceflag == 1){
					$conn->query("update product_variants set price = '".mysqli_real_escape_string($conn, $price)."', priceflag = 1 where id = ".$existingItemData[0]['variant_id']." and user_id = ".$user_id);
				} 
			} else {
				$variations = array();
				$option1name = "";
				$option2name = "";
				$option3name = "";
				if(isset($inventoryData->products)){								
					$varLength = count($inventoryData->products);
					for($i = 0; $i < $varLength; $i++) {
						$variations[$i] = array();
						if(isset($inventoryData->products[$i]->product_id)){
							$variations[$i]['sku'] = $inventoryData->products[$i]->sku;
						} else {
							$variations[$i]['sku'] = "";
						}
						if(isset($inventoryData->products[$i]->property_values[0]->property_name) && isset($inventoryData->products[$i]->property_values[0]->values[0])){
							$variations[$i][$inventoryData->products[$i]->property_values[0]->property_name] = $inventoryData->products[$i]->property_values[0]->values[0];
						}
						
						if(isset($inventoryData->products[$i]->property_values[1]->property_name) && isset($inventoryData->products[$i]->property_values[1]->values[0])){
							$variations[$i][$inventoryData->products[$i]->property_values[1]->property_name] = $inventoryData->products[$i]->property_values[1]->values[0];
						}

						if(isset($inventoryData->products[$i]->offerings[0]->price->amount)){
							$variations[$i]['price'] = $inventoryData->products[$i]->offerings[0]->price->amount / 100;
							$variations[$i]['price'] = str_replace(",","",$variations[$i]['price']);
						} else {
							$variations[$i]['price'] = 0;
						}

						if(isset($inventoryData->products[$i]->offerings[0]->quantity)){
							$variations[$i]['quantity'] = $inventoryData->products[$i]->offerings[0]->quantity;
						} else {
							$variations[$i]['quantity'] = 0;
						}
					}
				}
		//		print_r($variations);
				foreach($variations as $variation){
					foreach($existingItemData as $pk => $existingVariation){
						$ismatched = true;
						foreach($existingVariation as $k => $v){
							if($k == 'sku' || $k == 'processed' || $k == 'orig_price' || $k == 'price' || $k == 'etsylistingid' || $k == 'quantity' || $k == 'variant_id'){
								continue;
							}
						//	echo $variation[$k].'--'.$v.'--'.($variation[$k] != $v)."<br /><br />";
							if($variation[$k] != $v){
								$ismatched = false;
								break;
							}
						}
						if(!$ismatched){
							continue;
						}
						$existingItemData[$pk]['processed'] = 1;
						$priceflag = 0;
						$quantityflag = 0;
						if($variation['price'] > 0 && $variation['price'] != $existingVariation['price']){
							$priceflag = 1;
						}
												
						 if($priceflag == 1){
							$conn->query("update product_variants set price = '".mysqli_real_escape_string($conn, $variation['price'])."', priceflag = 1 where id = '".$existingVariation['variant_id']."' and user_id = ".$user_id);
						} 
						break;							
					}
				}
				foreach($existingItemData as $existingVariation){
					if(!isset($existingVariation['processed']) && $existingVariation['quantity'] > 0){
						$conn->query("update product_variants set quantity = 0, quantityflag = 1 where id = '".$existingVariation['variant_id']."' and user_id =".$user_id );
					}
				}
			}
		}
	}				
}

function updateInventoryAndPrice($user_id, $token, $shopurl, $inventory_sync,$outofstock_action, $price_sync, $location_id, $markupenabled, $markuptype, $markupval, $markupvalfixed, $markupround){
	global $conn;
	$result = $conn->query("select * from product_variants where shopifyvariantid != '' and (quantityflag = 1 or priceflag = 1) and block = 0 and deleted = 0 and user_id = ".$user_id);
	if ($result->num_rows > 0) {
		$i = 0;
		while($row = $result->fetch_assoc()) {			
			$rowid = $row['id'];
			$shopifyproductid = $row['shopifyproductid'];
			$shopifyvariantid = $row['shopifyvariantid'];
			$shopifyinventoryid = $row['shopifyinventoryid'];
			$shopifylocationid = $row['shopifylocationid'];
			if($shopifylocationid == ''){
				$shopifylocationid = $location_id;
			}
			$priceflag = $row['priceflag'];
			$quantityflag = $row['quantityflag'];
			$sku = $row['sku'];					
			$quantity = $row['quantity'];
			$price = $row['price'];
			if($markupenabled == 1){
    		  //  $price = applyPriceMarkup($price, $markuptype, $markupval, $markupround);
    		    //$price = $price + $markupvalfixed;
    		}
			$data = array();
			if($price_sync == 1 && $priceflag == 1){
				$data = array(
							"variant"=>array(
								"id" => $shopifyvariantid,		
								"price" => number_format($price, 2, '.', '')
							)
						);				
				$res = updateShopifyVariant($token, $shopurl, $shopifyvariantid, $data, $rowid, $user_id);
				if($res){
					$conn->query("update product_variants set priceflag = 0 where user_id = ".$user_id." and id = ".$rowid);
					$i++;
				}
			}
			if($inventory_sync == 1 && $quantityflag == 1 && $shopifyinventoryid == ''){
				$shopifyinventoryid = getInventoryId($user_id, $token, $shopurl, $shopifyvariantid);
				$conn->query("update product_variants set shopifyinventoryid = '".mysqli_real_escape_string($conn, $shopifyinventoryid)."' where user_id = ".$user_id." and id = ".$rowid);
			}
			if($inventory_sync == 1 && $quantityflag == 1 && $shopifyinventoryid != ''){
			    if($outofstock_action == 'unpublish' &&  $quantity < 1){
			        $data = array(
						"product"=>array(
							"id" => $shopifyproductid,		
							"status" => 'draft'
						)
					);		
					$res = updateShopifyproduct($token, $shopurl, $shopifyproductid,$data,$rowid, $user_id);	
			    }else if($outofstock_action == 'delete' &&  $quantity < 1){
			        $res = deleteShopifyProduct($user_id, $token, $shopurl, $shopifyproductid);
			    }else{
			        $res = updateShopifyInventory($rowid, $user_id, $token, $shopurl, $shopifyinventoryid, $shopifylocationid, $quantity);
			    }
				//if($res){
					$conn->query("update product_variants set quantityflag = 0 where id = ".$rowid);
					$i++;
				//}
			}				
			if($i > 50){
				echo "incommit";
				mysqli_commit($conn);
				$i = 0;
			}
		}
		mysqli_commit($conn);		
	}
}

function updateShopifyproduct($token, $shopurl, $shopifyproductid, $data, $rowid, $user_id){
	global $conn;
	$url = "https://".$shopurl."/admin/api/2023-04/products/".$shopifyproductid.".json";
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-Shopify-Access-Token:'.$token, 'Content-Type: application/json; charset=utf-8'));
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_VERBOSE, 0);
	curl_setopt($curl, CURLOPT_HEADER, 1);
	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
	curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$response = curl_exec ($curl);
	curl_close ($curl);
    echo $response;
	$response_arr = explode("\n",$response);	
	$climit = -1;
	foreach($response_arr as $obj){
		if (strpos($obj, 'X-Shopify-Shop-Api-Call-Limit') !== false) {
			$tempArr = explode(":", $obj);
			$climit = substr(trim(end($tempArr)), 0, -3);
		}
	}	
	if(intval($climit) > 35){
		sleep(5);
	} else {
	    sleep(1);
	}
	if( (strstr(($response_arr[0]), "200")) || (strstr(($response_arr[1]), "200")) || (strstr(($response_arr[2]), "200")) ) {
		return true;
	} else if(strstr(($response_arr[0]), "404")){
		$conn->query("update product_variants set quantityflag = 0, priceflag = 0, deleted = 1 where user_id = ".$user_id." and id = ".$rowid);
	} else if(strstr(($response_arr[0]), "429")){
		sleep(1);
	}
	return false;
}

function updateShopifyVariant($token, $shopurl, $variant_id, $data, $rowid, $user_id){
	global $conn;
	$url = "https://".$shopurl."/admin/api/" . SHOPIFY_API_VERSION . "/variants/".$variant_id.".json";
	
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-Shopify-Access-Token:'.$token, 'Content-Type: application/json; charset=utf-8'));
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_VERBOSE, 0);
	curl_setopt($curl, CURLOPT_HEADER, 1);
	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
	curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$response = curl_exec ($curl);
	curl_close ($curl);
    echo $response;
	$response_arr = explode("\n",$response);	
	$climit = -1;
	foreach($response_arr as $obj){
		if (strpos($obj, 'X-Shopify-Shop-Api-Call-Limit') !== false) {
			$tempArr = explode(":", $obj);
			$climit = substr(trim(end($tempArr)), 0, -3);
		}
	}	
	if(intval($climit) > 35){
		sleep(5);
	} else {
	    sleep(1);
	}
	if( (strstr(($response_arr[0]), "200")) || (strstr(($response_arr[1]), "200")) || (strstr(($response_arr[2]), "200")) ) {
		return true;
	} else if(strstr(($response_arr[0]), "404")){
		$conn->query("update product_variants set quantityflag = 0, priceflag = 0, deleted = 1 where user_id = ".$user_id." and id = ".$rowid);
	} else if(strstr(($response_arr[0]), "429")){
		sleep(1);
	}
	return false;
}

function deleteShopifyProduct($user_id, $token, $shopurl, $product_id){
	global $conn;
	$url = "https://".$shopurl."/admin/api/" . SHOPIFY_API_VERSION . "/products/".$product_id.".json";
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-Shopify-Access-Token:'.$token, 'Content-Type: application/json; charset=utf-8'));
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_VERBOSE, 0);
	curl_setopt($curl, CURLOPT_HEADER, 1);
	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$response = curl_exec ($curl);
	curl_close($curl);
	$response_arr = explode("\n",$response);
	if( (strstr(($response_arr[0]), "200")) || (strstr(($response_arr[1]), "200")) || (strstr(($response_arr[2]), "200")) ){
		//$conn->query("update products set shopifyproductid = '', status ='Ready to Import' where user_id = ".$user_id." and shopifyproductid = '".$product_id."'");
		//$conn->query("update product_variants set shopifyproductid = '', shopifyvariantid = '', status ='Ready to Import' where user_id = ".$user_id." and shopifyproductid = '".$product_id."'");
		//$conn->query("delete from shopifyproducts where user_id = ".$user_id." and productid = '".$product_id."'");	
		return true;		
	} else {
		return false;	
	}
}

	// Start adding functions to handle multiple location
	function getMainLocation($user_id, $shopurl, $token){
		global $conn;
		$result = $conn->query("select * from locations where user_id = ".$user_id." order by shopifylocationid * 1");
		if($result->num_rows > 0){
			$row = $result->fetch_assoc();
			$location_id = $row['shopifylocationid'];
			return $location_id;
		} else{
			// Try to fetch all possible locations
			$location_id = fetchLocations($user_id, $shopurl, $token);
			if($location_id){
				return $location_id;
			}
		}
		return false;
	}
	
	function fetchLocations($user_id, $shopurl, $token) {
		global $conn;		
		$existingLocations = array();
		$result = $conn->query("select * from locations where user_id = ".$user_id);
		if($result->num_rows > 0){
			while($row = $result->fetch_assoc()){
				$existingLocations[] = $row['shopifylocationid'];
			}
		}

		$apiurl = "https://".$shopurl."/admin/api/" . SHOPIFY_API_VERSION . "/locations.json";
		$session = curl_init();
		curl_setopt($session, CURLOPT_URL, $apiurl);
		curl_setopt($session, CURLOPT_HTTPGET, 1);
		curl_setopt($session, CURLOPT_HEADER, false);
		curl_setopt($session, CURLOPT_HTTPHEADER, array('X-Shopify-Access-Token:'.$token));
		curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($session,CURLOPT_SSL_VERIFYPEER,false);
		$response = curl_exec($session);	
		echo $response;
		curl_close($session);
		$session = "";
		if($response){
			$respObj = json_decode($response, true);
			if(isset($respObj['locations'])){
				$locationArr = $respObj['locations'];
				foreach($locationArr as $locationObj){
					$locName = $locationObj['name'];
					$shopifylocationid = $locationObj['id'];
					if(in_array($shopifylocationid, $existingLocations)){
						continue;
					}
					$legacy = 0;
					if($locationObj['legacy']){
						$legacy = 1;
					}
					$conn->query("insert into locations(name, legacy, status, shopifylocationid, user_id, created_at, updated_at) values('".mysqli_real_escape_string($conn, $locName)."', ".$legacy.", 'active', ".mysqli_real_escape_string($conn, $shopifylocationid).", ".$user_id.", now(), now())");
					$existingLocations[] = $shopifylocationid;
				}
			}
		}
		if(count($existingLocations) > 0){
			sort($existingLocations, SORT_NUMERIC); 
			return $existingLocations[0];
		} else {
			return false;
		}
	}

	function getInventoryId($user_id, $token, $shopurl, $shopifyvariantid){
		global $conn;
		$apiurl = "https://".$shopurl."/admin/api/" . SHOPIFY_API_VERSION . "/variants/".$shopifyvariantid.".json";		
		$session = curl_init();
		curl_setopt($session, CURLOPT_URL, $apiurl);
		curl_setopt($session, CURLOPT_HTTPGET, 1);
		curl_setopt($session, CURLOPT_HEADER, false);
		curl_setopt($session, CURLOPT_HTTPHEADER, array('X-Shopify-Access-Token:'.$token));
		curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($session,CURLOPT_SSL_VERIFYPEER,false);
		$response = curl_exec($session);
		echo $response;
		if($response){
			$resObj = json_decode($response, true);
			if(isset($resObj['variant']) && isset($resObj['variant']['inventory_item_id'])){
				return trim($resObj['variant']['inventory_item_id']);
			}
		}
		sleep(1);
		return "";
	}

	function updateShopifyInventory($rowid, $user_id, $token, $shopurl, $inventory_item_id, $location_id, $quantity){
		global $conn;
		$data = array("location_id" => $location_id, "inventory_item_id" => $inventory_item_id, "available" => $quantity);
		$url = "https://".$shopurl."/admin/api/" . SHOPIFY_API_VERSION . "/inventory_levels/set.json";

		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-Shopify-Access-Token:'.$token, 'Content-Type: application/json; charset=utf-8'));
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_VERBOSE, 0);
		curl_setopt($curl, CURLOPT_HEADER, 1);
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		$response = curl_exec ($curl);
		curl_close ($curl);
		$response_arr = explode("\n", $response);
		print_r($response_arr);
		$climit = -1;
		foreach($response_arr as $obj){
			if (strpos($obj, 'X-Shopify-Shop-Api-Call-Limit') !== false) {
				$tempArr = explode(":", $obj);
				$climit = substr(trim(end($tempArr)), 0, -3);
			}
		}
		if(intval($climit) > 35){
			sleep(5);
		}
		sleep(2);
		if( (strstr(($response_arr[0]), "200")) || (strstr(($response_arr[1]), "200")) || (strstr(($response_arr[2]), "200")) ) {
			return true;
		} else if((strstr(($response_arr[0]), "403")) || (strstr(($response_arr[0]), "422")) || (strstr(($response_arr[0]), "HTTP/2 404"))) {
			$new_location_id = getLocationId($token, $shopurl, $inventory_item_id);
			if($new_location_id){
				$data = array("location_id" => $new_location_id, "inventory_item_id" => $inventory_item_id, "available" => $quantity);
				$url = "https://".$shopurl."/admin/api/" . SHOPIFY_API_VERSION . "/inventory_levels/set.json";
				$curl = curl_init();
				curl_setopt($curl, CURLOPT_URL, $url);
				curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-Shopify-Access-Token:'.$token, 'Content-Type: application/json; charset=utf-8'));
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($curl, CURLOPT_VERBOSE, 0);
				curl_setopt($curl, CURLOPT_HEADER, 1);
				curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
				curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
				curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
				$response = curl_exec ($curl);	
				curl_close ($curl);
				$response_arr = explode("\n", $response);
				print_r($response_arr);
				$climit = -1;
				foreach($response_arr as $obj){
					if (strpos($obj, 'X-Shopify-Shop-Api-Call-Limit') !== false) {
						$tempArr = explode(":", $obj);
						$climit = substr(trim(end($tempArr)), 0, -3);
					}
				}
				if(intval($climit) > 35){
					sleep(5);
				}
				sleep(1);
				if( (strstr(($response_arr[0]), "200")) || (strstr(($response_arr[1]), "200")) || (strstr(($response_arr[2]), "200")) ) {
					$conn->query("update product_variants set shopifylocationid = '".mysqli_real_escape_string($conn, $new_location_id)."' where user_id = ".$user_id." and id = ".$rowid);
					$conn->query("update settings set shopifylocationid = '".mysqli_real_escape_string($conn, $new_location_id)."' where user_id = ".$user_id);
					return true;
				} else if(strstr(($response_arr[0]), "404")){
            		$conn->query("update product_variants set quantityflag = 0, priceflag = 0, deleted = 1 where user_id = ".$user_id." and id = ".$rowid);
            	} else {
					return false;
				}
			}
		}
		return false;
	}
	
	function getLocationId($token, $shopurl, $inventory_item_id){		
		$apiurl = "https://".$shopurl."/admin/api/" . SHOPIFY_API_VERSION . "/inventory_levels.json?inventory_item_ids=".$inventory_item_id;
		$session = curl_init();
		curl_setopt($session, CURLOPT_URL, $apiurl);
		curl_setopt($session, CURLOPT_HTTPGET, 1);
		curl_setopt($session, CURLOPT_HEADER, false);
		curl_setopt($session, CURLOPT_HTTPHEADER, array('X-Shopify-Access-Token:'.$token));
		curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($session,CURLOPT_SSL_VERIFYPEER,false);
		$response = curl_exec($session);
		curl_close ($session);
		if($response){
			$resObj = json_decode($response, true);
			if(isset($resObj['inventory_levels']) && isset($resObj['inventory_levels'][0]['location_id'])){
				return trim($resObj['inventory_levels'][0]['location_id']);
			}			
		}		
		return false;
	}	

	function addlog($message, $type){
		global $logfile;
		$txt = date("Y-m-d H:i:s")." [".$type."]: ".$message."\n";
		fwrite($logfile, $txt);
	}
	addlog("Execution Finished", "INFO");
	fclose($logfile);
?>