<?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/ordergens".date('Y-m-d').".txt", "a+") or die("Unable to open log file!");
addlog("Execution Started", "INFO");
$cronQuery = $conn->query("select * from crons where crontype = 'cronordersgen_v3'");
$cronrow = $cronQuery->fetch_assoc();
if ($cronrow['isrunning'] == 1) {
	@mail("khariwal.rohit@gmail.com", "cronordersgen_v3: Cron already running", "cronordersgen_v3: Cron already running");
	addlog("Stopped due to previous cron already running", "INFO");
	die("cron is running");
}
$conn->query("update crons set lastrun = now(), isrunning = 1 where crontype = 'cronordersgen_v3'");
echo "start";
$inventoryUpdates = array();

$userResult = $conn->query("select u.id, u.shopurl, u.token from users u, setting s where u.id = s.user_id and u.installationstatus = 1  and s.shopifyorders = 1 and u.id = 3198");
if ($userResult->num_rows > 0) {
	while ($userRow = $userResult->fetch_assoc()) {
		$user_id = $userRow["id"];
		$shopurl = $userRow['shopurl'];
		$token = $userRow['token'];
		$shopifyorders_action = "end";
		echo "user_id ".$user_id;
		addlog("user_id ".$user_id, "INFO");
		$inventoryUpdates = array();		

		$orderResult = $conn->query("SELECT max(orderid) as maxid FROM `shopifyorders` where user_id = " . $user_id);
		addlog("SELECT max(orderid) as maxid FROM `shopifyorders` where user_id = " . $user_id,"INFO");
		// if ($orderResult->num_rows < 1) {			
		// 	continue;
		// }
		$orderRow = $orderResult->fetch_assoc();
		$maxorderid = $orderRow['maxid'];
        if($maxorderid > 0){
			addlog("maxid ".$maxorderid, "INFO");
			processStore($user_id, $shopurl, $token, $shopifyorders_action, $maxorderid,$conn);
		} else {
			$date = date("Y-m-d H:m:s", strtotime('-24 hours'));
			$datetime = new DateTime($date);
            $minDate = $datetime->format("Y-m-d\TH:i:s.v");
            $minDate = $minDate."-00:00";
			processStoreDate($user_id, $shopurl, $token, $shopifyorders_action, $minDate,$conn);
		}
	}
}
$conn->query("update crons set lastrun = now(), isrunning = 0 where crontype = 'cronordersgen_v3'");

function processStoreDate($user_id, $shopurl, $token, $shopifyorders_action, $minDate)
{
    echo "1";
	global $conn;

	$order_url = "https://" . $shopurl . "/admin/api/2024-10/graphql.json";
	$hasNextPage = true;
	$cursor = null;

	while ($hasNextPage) {
		$cursorQuery = $cursor ? ", after: \"$cursor\"" : "";

		$query = <<<GRAPHQL
		{
			orders(first: 50, query: "created_at:>=$minDate"{$cursorQuery}) {
				edges {
					cursor
					node {
						id
						createdAt
						lineItems(first: 50) {
							edges {
								node {
									title
									quantity
									product {
										id
									}
									variant {
										id
										sku
									}
								}
							}
						}
					}
				}
				pageInfo {
					hasNextPage
					endCursor
				}
			}
		}
		GRAPHQL;

		$session = curl_init();
		curl_setopt($session, CURLOPT_URL, $order_url);
		curl_setopt($session, CURLOPT_POST, 1);
		curl_setopt($session, CURLOPT_POSTFIELDS, json_encode(['query' => $query]));
		curl_setopt($session, CURLOPT_HTTPHEADER, [
			'Content-Type: application/json',
			'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);

		$result = json_decode($response, true);

		if (isset($result['data']['orders']['edges']) && count($result['data']['orders']['edges']) > 0) {
			foreach ($result['data']['orders']['edges'] as $edge) {
				$order = $edge['node'];
				echo "here in for loop \n";
				echo $order["id"] . "####" . $order["createdAt"] . "$$";
				// die();
                processOrder($user_id, $order, $shopifyorders_action);
			}
			$hasNextPage = $result['data']['orders']['pageInfo']['hasNextPage'];
			$cursor = $result['data']['orders']['pageInfo']['endCursor'];
		} else {
			$hasNextPage = false;
		}

		if (isset($result['extensions']['search'][0]['warnings'])) {
			echo "\n";
			print_r($result['extensions']['search'][0]['warnings']);
		}
	}
}
function processStore($user_id, $shopurl, $token, $shopifyorders_action, $maxorderid)
{
	$order_url = "https://" . $shopurl . "/admin/api/2024-10/graphql.json";

    // GraphQL query
    $query = <<<GRAPHQL
    {
        orders(first: 100, query: "id:>$maxorderid") {
            edges {
                node {
                    id
                    createdAt
                    lineItems(first: 50) {
                        edges {
                            node {
                                title
                                quantity
                                product {
                                    id
                                }
                                variant {
                                    id
                                    sku
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    GRAPHQL;
	echo $query;

	addlog('query : ');
	addlog($query);

    // Prepare the GraphQL request
    $session = curl_init();
    curl_setopt($session, CURLOPT_URL, $order_url);
    curl_setopt($session, CURLOPT_POST, true);
    curl_setopt($session, CURLOPT_POSTFIELDS, json_encode(['query' => $query]));
    curl_setopt($session, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        '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);
addlog( $response);
print_r($response);
    // Parse the GraphQL response
    $result = json_decode($response, true);

    // Process orders
    if (isset($result['data']['orders']['edges'])) {
        foreach ($result['data']['orders']['edges'] as $edge) {
            $order = $edge['node'];

            // Example of processing the order data
            echo "Order ID: " . str_replace("gid://shopify/Order/", "", $order['id']) . "\n";
            echo "Created At: " . $order['createdAt'] . "\n";

            foreach ($order['lineItems']['edges'] as $lineItem) {
                $item = $lineItem['node'];
                $productId = str_replace("gid://shopify/Product/", "", $item['product']['id']);
                $variantId = str_replace("gid://shopify/ProductVariant/", "", $item['variant']['id']);

                echo " - Product: " . $item['title'] . "\n";
                echo "   Product ID: " . $productId . "\n";
                echo "   Variant ID: " . $variantId . "\n";
                echo "   Quantity: " . $item['quantity'] . "\n";
            }

            // // Call your order processing function
            processOrder($user_id, $order, $shopifyorders_action);
        }
    }
}

function processOrder($user_id, $order, $shopifyorders_action)
{
	global $conn, $inventoryUpdates;
	$order_id = $order["id"];
	$order_id = str_replace("gid://shopify/Order/", "", $order["id"]);
	addlog("select * from shopifyorders where user_id = '" . $user_id . "' and orderid = '" . mysqli_real_escape_string($conn, $order_id) . "'","INFO");
	$checkExistanceQuery = $conn->query("select * from shopifyorders where user_id = '" . $user_id . "' and orderid = '" . mysqli_real_escape_string($conn, $order_id) . "'");
	if ($checkExistanceQuery->num_rows > 0) {
		addlog("Order [".$order_id."] already exists for Store - ".$user_id, "INFO");		
		return false;
	}
	$conn->query("insert into shopifyorders(orderid, user_id, orderdata, created_at, updated_at) values('" . mysqli_real_escape_string($conn, $order_id) . "', '" . $user_id . "', '" . mysqli_real_escape_string($conn, serialize($order)) . "',now(), now())");
	$row_id = $conn->insert_id;
	$line_items = $order['lineItems'];
    
	foreach ($line_items['edges'] as $line_item) {
		$line_item = $line_item['node'];
		$product =  $line_item['product'];
		$product_id = str_replace("gid://shopify/Product/", "", $product["id"]);
		// $variant_id = "" . $line_item['variant'];
		$variant_id = str_replace("gid://shopify/ProductVariant/", "", $line_item['variant']["id"]);
		$quantity = $line_item['quantity'];
		$sku = $line_item['variant']['sku'];
		$variantResult = $conn->query("select * from product_variants where shopifyvariantid !='' and shopifyproductid = '" . $product_id . "' and shopifyvariantid = '" . $variant_id . "' and user_id = " . $user_id);
		if ($variantResult->num_rows > 0) {
			$variantRow = $variantResult->fetch_assoc();
			$id = $variantRow['id'];
			addQty($id, $quantity, $variantRow);
		}
	}
	addlog("inventoryUpdates - " . json_encode($inventoryUpdates), "INFO");
	$conn->query("update shopifyorders set inventoryupdates = '" . mysqli_real_escape_string($conn, json_encode($inventoryUpdates)) . "' where user_id = " . $user_id . " and orderid = '" . mysqli_real_escape_string($conn, $order_id) . "'") or die("error in query");
	$resp = updateInventory($user_id, $shopifyorders_action,$inventoryUpdates);
	echo "upter update";
	$conn->query("update shopifyorders set resp = '".mysqli_real_escape_string($conn, $resp)."' where user_id = ".$user_id." and id = ".$row_id);
	@mail("rohit.khariwal@infoshore.biz", "cronordersgen: new cron executed", "Order Number - ".$order_id."@@");
	
}

function updateInventory($user_id, $shopifyorders_action)
{
    global $conn, $etsyConfig, $inventoryUpdates;
	$api_key = $etsyConfig['api_key'];
	$api_secret = $etsyConfig['api_secret'];    
	addlog("updateInventory - ", "INFO");
    $etsyResult = $conn->query("SELECT * FROM `etsy_keys` where user_id = ".$user_id);
    if($etsyResult->num_rows == 0) {
		return "No valid Etsy keys found!";
	}
    $etsyRow = $etsyResult->fetch_assoc();     
    $oauth_token = $etsyRow['oauth_token'];
    $oauth_token_secret = $etsyRow['oauth_token_secret'];
    $access_token = $etsyRow['access_token'];
	$refresh_token = $etsyRow['refresh_token']; 
    $shop_id = $etsyRow['shop_id'];
    $resp = array();
    foreach ($inventoryUpdates as $inventoryUpdate) {
        $variantRow = $inventoryUpdate['variantRow'];
		$qtysold = $inventoryUpdate['qtysold'];  
		addlog("inventoryUpdate VARIABLE ","INFO");      

		addlog(json_encode( $inventoryUpdate,true),"INFO");      
        
        $productResult = $conn->query("SELECT * FROM `products` where shopifyproductid = ".$variantRow['shopifyproductid']." and user_id = ".$variantRow['user_id']);
        $productRow = $productResult->fetch_assoc();
            
        if($productRow['etsy_state'] == 'draft'){
			// return "Related listing is not active.";
			continue;
		}
        $varResult = $conn->query("SELECT * FROM `product_variants` where id = '".$variantRow['id']."' and user_id = ".$user_id);
        $variantRow = $varResult->fetch_assoc();	
        $oldQty = $variantRow['quantity'];
		
	    if($oldQty - $qtysold > 0) {    
			 
    	    $propertyIds = array();
    		$productsArr = array();
    		$etsyOption1Values = array();
    		$etsyOption2Values = array();    	    
        	$property_values = array();
        	$vid = $variantRow['id'];
			
    		if(isset($productRow['option1name']) && $productRow['option1name'] != '' && $productRow['option1name'] != NULL && $productRow['option1name'] != ' '){
    			$option1val = $variantRow['option1val'];
            	if(!in_array($option1val,$etsyOption1Values)) $etsyOption1Values[] = $option1val;
            		
            	$property_id = getEtsyPropertyID($productRow['option1name']);
            	if(!$property_id) $property_id = 513;
            	if(!in_array($property_id,$propertyIds)) $propertyIds[] = $property_id;
            	$option1Array = array(
            		"property_id" => $property_id,
					"value_ids" => array($property_id),
					"scale_id"=>$property_id,
            		"property_name" => $productRow['option1name'],
            		"values" => array($variantRow['option1val'])
            	);
            	$property_values[] = $option1Array;
            }
           
            if(isset($productRow['option2name']) && $productRow['option2name'] != '' && $productRow['option2name'] != NULL && $productRow['option2name'] != ' '){
            	$option2val = $variantRow['option2val'];
            	if(!in_array($option2val,$etsyOption2Values)) $etsyOption2Values[] = $option2val;
            		
            	$property_id = getEtsyPropertyID($productRow['option2name']);
            	if(!$property_id) $property_id = 514;
            	if(!in_array($property_id,$propertyIds)) $propertyIds[] = $property_id;
            	$option2Array = array(
            		"property_id" => $property_id,
					"value_ids" => array($property_id),
					"scale_id"=>$property_id,
            		"property_name" => $productRow['option2name'],
            		"values" => array($variantRow['option2val'])
            	);
            	$property_values[] = $option2Array;
            }
            
            $variantArr = array();
			if($variantRow['sku']) $variantArr["sku"] = $variantRow['sku'];	
    		$variantArr["property_values"] = array();
    		if($property_values){
    			$variantArr["property_values"] = $property_values;
    		}
    		
    		$retail_price = number_format((float)$variantRow['price'],2,'.','');
    		$vquantity = $oldQty - $qtysold;
			$conn->query("update product_variants set quantity = '".$vquantity."' where id = '".$variantRow['id']."' and user_id = ".$user_id);
			
    		$variantArr["offerings"] = array(
    			array(
    				'price' => $retail_price,
    				'quantity' => $vquantity,
    				'is_enabled' => 1
    			)	
    		);
    		$productsArr[] = $variantArr;
			addlog("productsArr - ".json_encode($productsArr), "INFO");
    		if($productsArr){
				addlog("productsArr - ", "INFO");
    			$inventoryData = array(
    				'products' =>$productsArr,
    				'quantity_on_property' => implode(",",$propertyIds),
    				'sku_on_property' => implode(",",$propertyIds)

    				
    			);
				addlog("etsy requestdata".json_encode($inventoryData) , "INFO");	
    			$updateInventoryRes = updateEtsyInventory($api_key,$api_secret,$oauth_token,$oauth_token_secret,(int)$productRow['etsylistingid'],$inventoryData,$access_token, $refresh_token,$shop_id,$vid, $vquantity,$user_id);
				// print_r($updateInventoryRes);
				$rr = json_decode($updateInventoryRes,true);
				echo $rr;
				addlog("etsy response".json_encode($rr) , "INFO");
				//echo "update product_variants set quantity = '".$vquantity."' where product_id = '".$vid."' and user_id = ".$user_id;
				//echo "update product_variants set quantity = '".mysqli_real_escape_string($conn, $vquantity)."' where id = '".$variantRow['id']."' and user_id = ".$user_id;
                $updateInventoryRes = (isset($rr["response"])) ? $rr["response"] : $rr;	
				echo "sucess";
				print_r(json_encode($updateInventoryRes));	
				$resp[] = json_encode($updateInventoryRes);
				$inventoryUpdates = array();
    			/*if($updateInventoryRes && (isset($updateInventoryRes["results"]["products"])) && $updateInventoryRes["results"]["products"]){
    				if($productRow['etsy_state'] == "inactive"){
    				    $updateListingStatusRes = updateEtsyListingStatus($api_key,$api_secret,$oauth_token,$oauth_token_secret,$productRow['etsylistingid'],"active");
    	                $conn->query("update products set etsy_state = 'active' where product_id = ".$productRow['product_id']);      
    				}
    			}*/
    		}
    	} else {
		
    	   $updateListingStatusRes = updateEtsyListingStatus($api_key, $access_token, $refresh_token, (int)$productRow['etsylistingid'], $status,$shop_id,$user_id);
    	   $conn->query("update products set etsy_state = 'inactive' where product_id = '".$productRow['product_id']."' and user_id = ".$user_id);
		   $resp[] = json_encode($updateListingStatusRes);
		   $inventoryUpdates = array();
    	 }
    }
    return json_encode($resp);
}

function updateEtsyListingStatus($api_key, $access_token, $refresh_token, $listing_id, $status,$shop_id,$user_id){
    global $etsyConfig,$conn;
    $api_key = $etsyConfig['api_key'];
	$inventoryDatanew;
	addlog("updateEtsyListingStatus - ".$api_key, "INFO");
	$listingData = array("listing_id" => $listing_id,"state" => "inactive");
	$inv = json_encode($listingData);
	print_r($inv);
	echo "https://openapi.etsy.com/v3/application/shops/{$shop_id}/listings/{$listing_id}";
	try {
        $header = array("Authorization: Bearer ".$access_token,"x-api-key: ".$api_key,"Content-Type:application/json");
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://openapi.etsy.com/v3/application/shops/{$shop_id}/listings/{$listing_id}",
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'PUT',
            
            CURLOPT_POSTFIELDS =>$inv // Remove json_encode and update this line
        ));
        $response_body1 = curl_exec($curl);
        curl_close($curl);	
        $inventoryDatanew = json_decode($response_body1);
        print_r("response status".json_encode($inventoryDatanew));
		addlog("updateEtsyListingStatus - ".$api_key, "INFO");
        if(isset($inventoryDatanew->error) && $inventoryDatanew->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,"Content-Type:application/json");
                $curl = curl_init();
                curl_setopt_array($curl, array(
                    CURLOPT_URL => "https://openapi.etsy.com/v3/application/shops/{$shop_id}/listings/{$listing_id}",
                    CURLOPT_HTTPHEADER => $header,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_CUSTOMREQUEST => 'PUT',
                    CURLOPT_POSTFIELDS =>$inv // Remove json_encode and update this line
                ));
                $response_body1 = curl_exec($curl);
                curl_close($curl);	
                $inventoryDatanew = json_decode($response_body1);
                 print_r(json_encode($inventoryDatanew));
            }
        }
		sleep(1);
		
        //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);
	$response = array("response" => $inventoryDatanew);
	//print_r($response);
	return json_encode($response); 
}
	
function updateEtsyInventory($api_key,$api_secret,$oauth_token,$oauth_token_secret,$listing_id,$inventoryData,$access_token, $refresh_token,$shop_id,$vid,$qty,$user_id){
    global $etsyConfig,$conn;
	$inventoryDatanew;
    $api_key = $etsyConfig['api_key'];
	addlog("inventoryUpdates  response-  active afer etsy api keys ".$api_key , "INFO");
	//print_r(json_encode($inventoryData));
	$inv = json_encode($inventoryData);
	try {
        $header = array("Authorization: Bearer ".$access_token,"x-api-key: ".$api_key,"Content-Type:application/json");
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://openapi.etsy.com/v3/application/listings/'.$listing_id.'/inventory',
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'PUT',
            
            CURLOPT_POSTFIELDS =>$inv // Remove json_encode and update this line
        ));
        $response_body1 = curl_exec($curl);
        curl_close($curl);	
        $inventoryDatanew = json_decode($response_body1);
        print_r(json_encode($inventoryDatanew));
        if(isset($inventoryDatanew->error) && $inventoryDatanew->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,"Content-Type:application/json");
                $curl = curl_init();
                curl_setopt_array($curl, array(
                    CURLOPT_URL => 'https://openapi.etsy.com/v3/application/listings/'.$listing_id.'/inventory',
                    CURLOPT_HTTPHEADER => $header,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_CUSTOMREQUEST => 'PUT',
                    CURLOPT_POSTFIELDS =>$inv // Remove json_encode and update this line
                ));
                $response_body1 = curl_exec($curl);
                curl_close($curl);	
                $inventoryDatanew = json_decode($response_body1);
                print_r(json_encode($inventoryDatanew));
            }
        }
		sleep(1);
		
        //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);
	$response = array("response" => $inventoryDatanew);
	//print_r($response);
	return json_encode($response); 
}
	function getres($url,$json_data,$headers){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    // Execute the request
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    // Close cURL
    curl_close($ch);
    
    // Check the response
    if ($httpCode == 200) {
        addlog("Inventory updated successfully with response".json_encode($response), "INFO");
        // 'Inventory updated successfully.';
    } else {
        addlog("Failed to update inventory. Response: " . $response, "INFO");
        //echo 'Failed to update inventory. Response: ' . $response;
    }
  return $response;    
}
function getEtsyPropertyID($optionName){
	$optionName = strtolower($optionName);
	$property_id = null;

	if(strpos($optionName,'color') !== false || strpos($optionName,'colour') !== false){
		$property_id = 200;
	}
	else if(strpos($optionName,'size') !== false){
		$property_id = 100;
	}
	else if(strpos($optionName,'style') !== false){
		$property_id = 510;
	}
	else if(strpos($optionName,'flavor') !== false){
		$property_id = 503;
	}
	else if(strpos($optionName,'fabric') !== false){
		$property_id = 502;
	}
	else if(strpos($optionName,'pattern') !== false){
		$property_id = 508;
	}
	else if(strpos($optionName,'material') !== false){
		$property_id = 507;
	}
	else if(strpos($optionName,'device') !== false){
		$property_id = 515;
	}
	else if(strpos($optionName,'diameter') !== false){
		$property_id = 504;
	}
	else if(strpos($optionName,'dimensions') !== false){
		$property_id = 501;
	}
	else if(strpos($optionName,'finish') !== false){
		$property_id = 500;
	}
    return $property_id;
}
	
function addQty($variant_id, $quantity, $variantRow)
{
	global $inventoryUpdates;
	if (!array_key_exists($variant_id, $inventoryUpdates)) {
		$inventoryUpdates[$variant_id] = array("qtysold" => $quantity, "variantRow" => $variantRow);
	} else {
		$inventoryUpdates[$variant_id]["qtysold"] = $inventoryUpdates[$variant_id]["qtysold"] + $quantity;
	}
}

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