<?php
echo "00";
set_time_limit(0);
ini_set('memory_limit', '-1');
require_once("includes/config.php");
//require_once("includes/sendgrid/sendgrid-php.php");
require_once("includes/etsyv3/vendor/autoload.php");
echo "1";
use OAuth\Client;
// $cronQuery = $conn->query("select * from crons where crontype = 'cronordersgen'");
// $cronrow = $cronQuery->fetch_assoc();
// if ($cronrow['isrunning'] == 1) {
// 	@mail("khariwal.rohit@gmail.com", "cronordersgen: Cron already running", "cronordersgen: Cron already running");
// 	addlog("Stopped due to previous cron already running", "INFO");
// 	die("");
// }
// echo " narang ";
// $conn->query("update crons set lastrun = now(), isrunning = 1 where crontype = 'cronordersgen'");
echo "rrr";
$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 u.sync = 1  and u.id  in (select user_id from etsy_keys where apiversion = 'v3' ) and u.id = 1217");
echo " ppp ";

if ($userResult->num_rows > 0) {
	while ($userRow = $userResult->fetch_assoc()) {
		$user_id = $userRow["id"];
		$shopurl = $userRow['shopurl'];
		$token = $userRow['token'];
		$shopifyorders_action = $userRow['shopifyorders_action'];
		echo  "and user id is" .$user_id;
		$inventoryUpdates = array();		

		$orderResult = $conn->query("SELECT max(orderid) as maxid FROM `shopifyorders` where user_id = " . $user_id);
            echo " qqq ";     
            echo $orderResult->num_rows." rows "; 
		if ($orderResult->num_rows == 0) {			
			@mail("khariwal.rohit@gmail.com", "Store skipped due to no existing orders - ".$user_id, "Store skipped due to no existing orders - ".$user_id);
			addlog("Store skipped due to no existing orders - ".$user_id, "ERROR");
			echo "222";
			continue;
		}
            
		$orderRow = $orderResult->fetch_assoc();
	      
        $maxorderid = $orderRow['maxid'];
            echo  "and order id is" .$maxorderid;
        if($maxorderid > 0){
			//processStore($user_id, $shopurl, $token, $shopifyorders_action, $maxorderid);
			echo "pankaj narang";
            $date = date("Y-m-d H:m:s", strtotime('-540 hours'));
			$datetime = new DateTime($date);
            $minDate = $datetime->format("Y-m-d\TH:i:s.v");
            $minDate = $minDate."-00:00";
			echo "  it is here";
			processStoreDate($user_id, $shopurl, $token, $shopifyorders_action, $minDate,$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'");

function processStoreDate($user_id, $shopurl, $token, $shopifyorders_action, $minDate,$conn)
{
      echo "1";
	global $conn;
	// Fetch orders
	$order_url = "https://" . $shopurl . "/admin/api/" . SHOPIFY_API_VERSION . "/orders.json?status=any&limit=100&created_at_min=" . $minDate;
	$session = curl_init();
	curl_setopt($session, CURLOPT_URL, $order_url);
	curl_setopt($session, CURLOPT_HTTPGET, 1);
	curl_setopt($session, CURLOPT_HEADER, true);
	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);
	$response_arr = explode("\n", $response);
	//print_r($response_arr);
	if (strstr(($response_arr[0]), "200")) {
		$header_size = curl_getinfo($session, CURLINFO_HEADER_SIZE);
		curl_close($session);
		$header = substr($response, 0, $header_size);
		$body = substr($response, $header_size);
		$orders_array = json_decode($body, true);
	//	print_r($orders_array);
		if ($orders_array) {
			foreach ($orders_array['orders'] as $order) {
				echo $order["id"]."####".$order["created_at"]."$$";
				processOrder($user_id, $order, $shopifyorders_action,$conn);
                //exit;
			}
		}
	}
}

function processStore($user_id, $shopurl, $token, $shopifyorders_action, $maxorderid,$conn)
{ 
      echo "fetch order1";
	global $conn;
	// Fetch orders
	$order_url = "https://" . $shopurl . "/admin/api/" . SHOPIFY_API_VERSION . "/orders.json?status=any&limit=100&since_id=" . $maxorderid;
	$session = curl_init();
	curl_setopt($session, CURLOPT_URL, $order_url);
	curl_setopt($session, CURLOPT_HTTPGET, 1);
	curl_setopt($session, CURLOPT_HEADER, true);
	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);
	
      $response_arr = explode("\n", $response);
      print_r($response_arr);
	if (strstr(($response_arr[0]), "200")) {
		$header_size = curl_getinfo($session, CURLINFO_HEADER_SIZE);
		curl_close($session);
		$header = substr($response, 0, $header_size);
		$body = substr($response, $header_size);
		$orders_array = json_decode($body, true);
		if ($orders_array) {
			foreach ($orders_array['orders'] as $order) {
				processOrder($user_id, $order, $shopifyorders_action,$conn);
			}
		}
	}
}

function processOrder($user_id, $order, $shopifyorders_action,$conn)
{
	global $conn, $inventoryUpdates;
	$order_id = $order["id"];
	$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");	
        echo "exit";	
		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['line_items'];
    
	foreach ($line_items as $line_item) {
		$product_id = "" . $line_item['product_id'];
		$variant_id = "" . $line_item['variant_id'];
		$quantity = $line_item['quantity'];
		$sku = $line_item['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);
            //echo "fjsddsgjd".json_encode($inventoryUpdates);
            // die();
		}
        // else {
        //     echo "not match";
        //     continue;
        // }
	}

   if(!empty($inventoryUpdates)){
	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) . "'");
	$resp = updateInventory($user_id, $shopifyorders_action,$inventoryUpdates,$conn);
	$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."@@");
	$inventoryUpdates = array();
   }
   else{
     return false;
   }

}

function updateInventory($user_id, $shopifyorders_action,$conn)
{
    global $conn, $etsyConfig, $inventoryUpdates;
	$api_key = $etsyConfig['api_key'];
	$api_secret = $etsyConfig['api_secret'];    

    $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();     
    $access_token = $etsyRow['access_token'];
	$refresh_token = $etsyRow['refresh_token'];
    
    $shopid = $etsyRow['shop_id']; 
    $resp = array();
    foreach ($inventoryUpdates as $inventoryUpdate) {
        $variantRow = $inventoryUpdate['variantRow'];
		$qtysold = $inventoryUpdate['qtysold'];        
        
        $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']);
        $variantRow = $varResult->fetch_assoc();	
        $oldQty = $variantRow['quantity'];
        echo $oldQty - $qtysold;
        // die();
	    if($oldQty - $qtysold > 0) {    		
    	    $propertyIds = array();
    		$productsArr = array();
    		$etsyOption1Values = array();
    		$etsyOption2Values = array();    	    
        	$property_values = array();
        	    
    		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,
            		"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,
            		"property_name" => $productRow['option2name'],
            		"values" => array($variantRow['option2val'])
            	);
            	$property_values[] = $option2Array;
            }
            	
            $variantArr = array();
    		$variantArr["property_values"] = array();
    		if($property_values){
    			$variantArr["property_values"] = $property_values;
    		}
    		if($variantRow['sku']) $variantArr["sku"] = $variantRow['sku'];
    		$retail_price = number_format((float)$variantRow['price'],2,'.','');
    		$vquantity = $oldQty - $qtysold;
    		$variantArr["offerings"] = array(
    			array(
    				/*'price' => $retail_price,*/
    				'quantity' => $vquantity,
    				'is_enabled' => 1
    			)	
    		);
    		$productsArr[] = $variantArr;
    		if($productsArr){
    			$inventoryData = array(
    				'listing_id' => (int)$productRow['etsylistingid'],
    				'quantity_on_property' => implode(",",$propertyIds),
    				'sku_on_property' => implode(",",$propertyIds),
    				'products' => json_encode($productsArr,JSON_UNESCAPED_UNICODE)
    			);
    			
                $json_data =$inventoryData;
	addlog("order data". $json_data, "INFO");
   //print_r($json_data);
    // Prepare the API endpoint
    $url = "https://api.etsy.com/v3/application/listings/{$listing_id}/inventory";
    
   // print_r("url".$url."access token",$access_token);
    // Set the headers
    $headers = array(
        'Authorization: Bearer ' . $access_token,
        "x-api-key: " . $api_key,
        'Content-Type: application/json'
    );
    //print_r(json_encode($headers));
    $result = getres($url,$json_data,$headers);
    $r = json_decode($result);
    if (isset($r->error) && $r->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);
            $url = "https://api.etsy.com/v3/application/listings/{$listing_id}/inventory";
            $json_data =$inventoryData;
            // Set the headers
            $headers = array(
                'Authorization: Bearer ' . $access_token,
                "x-api-key: " . $api_key,
                'Content-Type: application/json'
            );
            $result = getres($url,$json_data,$headers);
           $r = json_decode($result);
        }
    } 

	addlog("order data res". $r, "INFO");

    $resp[] = json_encode( $r);
$conn->query("update shopifyorders set resp = '".mysqli_real_escape_string($conn, json_encode($r))."' where user_id = ".$user_id." and id = ".$row_id);
@mail("pankajnarang81@gmail.com", "cronordersgen_v3: new cron executed", "Order Number - ".$order_id."@@");
    			/*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 {
            print_r(json_encode($inventoryData));
              //  die();
    	//    $updateListingStatusRes = updateEtsyListingStatus($api_key,$api_secret,$oauth_token,$oauth_token_secret,$productRow['etsylistingid'],"inactive");
        $listing_id11 = $productRow['etsylistingid'];
           $url = "https://openapi.etsy.com/v3/application/shops/{$shopid}/listings/{$listing_id11}";
    
           $json_data = array("listing_id" => $listing_id11,"state" => "inactive");
            $headers = array(
                'Authorization: Bearer ' . $access_token,
                "x-api-key: " . $api_key,
                'Content-Type: application/json'
            );
            print_r(json_encode($json_data));
            
            $result = getres($url,$json_data,$headers);
            $r = json_decode($result);
            print_r($r );
            if (isset($r->error) && $r->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);
                    $url = "https://openapi.etsy.com/v3/application/shops/{$shopid}/listings/{$listing_id}";
                    $json_data = array("listing_id" => $listing_id11,"state" => "inactive");
                    // Set the headers
                    $headers = array(
                        'Authorization: Bearer ' . $access_token,
                        "x-api-key: " . $api_key,
                        'Content-Type: application/json'
                    );
                    $result = getres($url,$json_data,$headers);
                   $r = json_decode($result);
                }
            } 
    	   $conn->query("update products set etsy_state = 'inactive' where product_id = ".$productRow['product_id']);
		   $resp[] = json_encode( $r);
    	 }
    }
    //die();
    return json_encode( $resp);
}


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


////    backup.......

<!-- <?php
echo "00";
set_time_limit(0);
ini_set('memory_limit', '-1');
require_once("includes/config.php");
//require_once("includes/sendgrid/sendgrid-php.php");
require_once("includes/etsyv3/vendor/autoload.php");
echo "1";
use OAuth\Client;

$logfile = fopen("logs/cronordersgen_v3_july.txt", "a+") or die("Unable to open log file!");
addlog("Execution Started", "INFO");
echo "2";
$cronQuery = $conn->query("select * from crons where crontype = 'cronordersgen_v3'");
$cronrow = $cronQuery->fetch_assoc();
if ($cronrow['isrunning'] == 1) {
	echo "already running";
	@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("");
}
$conn->query("update crons set lastrun = now(), isrunning = 1 where crontype = 'cronordersgen_v3'");
$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 u.sync = 1 and s.shopifyorders = 1 and u.id  in (select user_id from etsy_keys where apiversion = 'v3' ) ");
if ($userResult->num_rows > 0) {
	while ($userRow = $userResult->fetch_assoc()) {
       
		$user_id = $userRow["id"];
        addlog("user id".$user_id, "INFO");
		//print_r("user_id".$user_id);
		$shopurl = $userRow['shopurl'];
		$token = $userRow['token'];
		$shopifyorders_action = "end";

		$inventoryUpdates = array();		

		$orderResult = $conn->query("SELECT max(orderid) as maxid FROM `shopifyorders` where user_id = " . $user_id);
		if ($orderResult->num_rows < 1) {			
			continue;
		}
		$orderRow = $orderResult->fetch_assoc();
		$maxorderid = $orderRow['maxid'];
		//print_r("maxorder_id".$maxorderid);
        if($maxorderid > 0){
			processStore($user_id, $shopurl, $token, $shopifyorders_action, $maxorderid);
		} else {
			$date = date("Y-m-d H:m:s", strtotime('-48 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->query("update crons set lastrun = now(), isrunning = 0 where crontype = 'cronordersgen_v3'");
function processStoreDate($user_id, $shopurl, $token, $shopifyorders_action, $minDate)
{
	global $conn;

	$order_url = "https://" . $shopurl . "/admin/api/2023-04/orders.json?status=any&limit=100&created_at_min=" . $minDate;
	$session = curl_init();
	curl_setopt($session, CURLOPT_URL, $order_url);
	curl_setopt($session, CURLOPT_HTTPGET, 1);
	curl_setopt($session, CURLOPT_HEADER, true);
	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);
	$response_arr = explode("\n", $response);
	if (strstr(($response_arr[0]), "200")) {
		$header_size = curl_getinfo($session, CURLINFO_HEADER_SIZE);
		curl_close($session);
		$header = substr($response, 0, $header_size);
		$body = substr($response, $header_size);
		$orders_array = json_decode($body, true);
		if ($orders_array) {
			foreach ($orders_array['orders'] as $order) {
				processOrder($user_id, $order, $shopifyorders_action);
			}
		}
	}
}

function processStore($user_id, $shopurl, $token, $shopifyorders_action, $maxorderid)
{
	global $conn;
    echo "  2  ".$maxorderid. "   ";
	$order_url = "https://" . $shopurl . "/admin/api/2023-04/orders.json?status=any&limit=100&since_id=" . $maxorderid;
	$session = curl_init();
	curl_setopt($session, CURLOPT_URL, $order_url);
	curl_setopt($session, CURLOPT_HTTPGET, 1);
	curl_setopt($session, CURLOPT_HEADER, true);
	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);
	$response_arr = explode("\n", $response);
	if (strstr(($response_arr[0]), "200")) {
		$header_size = curl_getinfo($session, CURLINFO_HEADER_SIZE);
		curl_close($session);
		$header = substr($response, 0, $header_size);
		$body = substr($response, $header_size);
		$orders_array = json_decode($body, true);
		echo " size of orders are ".sizeof($orders_array);
		//print_r(json_encode($orders_array));
		
		if ($orders_array) {
			foreach ($orders_array['orders'] as $order) {
				echo "   "."ffff";
				processOrder($user_id, $order, $shopifyorders_action);
				echo "   "."ggg";
			}
		}
	}
}
function processOrder($user_id, $order, $shopifyorders_action)
{
	global $conn, $etsyConfig, $inventoryUpdates;
	$order_id = $order["id"];
	addlog("order id".$order_id, "INFO");
	//print_r("order_id".$order_id);
	//echo "434343";
    $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();    
    $access_token = $etsyRow['access_token'];
	$refresh_token = $etsyRow['refresh_token'];
    $api_key = $etsyConfig['api_key']; 
	$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) {
		//print_r("already exits".$order_id);
		addlog("Order [".$order_id."] already exists for Store - ".$user_id, "INFO");		
		return false;
	}
	//print_r("does Not already exits ".$order_id);
	$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;
	//print_r("insert row  order id  ".$row_id);
	$line_items = $order['line_items'];
echo "anjali";
	foreach ($line_items as $line_item) {
		$product_id = "" . $line_item['product_id'];
		$variant_id = "" . $line_item['variant_id'];
		$quantity = $line_item['quantity'];
        addlog("order  sold quantity".$quantity, "INFO");
		$sku = $line_item['sku'];
        
        $vres =  $conn->query("select * from product_variants where user_id =" . $user_id . " and shopifyproductid = ".$product_id);
        $vp1resv ='';
        $vp11= $conn->query("select option1name,option2name,etsylistingid from products where user_id =" . $user_id . " and shopifyproductid = ".$product_id);
        if($vp11->num_rows > 0){
        $vp1resv = $vp11->fetch_assoc();
        }
        $property_id1 = getEtsyPropertyID($vp1resv['option1name']);
        echo "";
        $property_id2 = getEtsyPropertyID($vp1resv['option2name']);
        $listing_id =  $vp1resv['etsylistingid'];
$variants = array();
$inactive = 0;
$qtyup =0;
$size = mysqli_num_rows($vres->fetch_assoc());
if($vres->num_rows > 0){
while ($rowv1 = $vres->fetch_assoc()) {
    echo "dd";
    $qty = 0;
	$qtyup =0;
   
    if ($variant_id == $rowv1['shopifyvariantid']) {
        addlog("varinat old quantity".$rowv1['quantity'], "INFO");
        $qty = $rowv1['quantity'] - $quantity;
        addlog("varinat new quantity". $qty, "INFO");
        addQty($variant_id, $quantity, $rowv1);
		$qtyup = $qty ;
       
    } else {
        $qty = $rowv1['quantity'];
    }
    echo "qqty";
    //$property_id1 
   
    $variants[] = array(
        'sku' => $rowv1['sku'],
        'property_values' => array(
            array(
                'property_id' => $property_id1,
                'property_name' => $vp1resv['option1name'],
                'values' => array($rowv1['option1val'])
            ),
            array(
                'property_id' => $property_id2,
                'property_name' => $vp1resv['option2name'],
                'values' => array($rowv1['option2val'])
            )
        ),
        'offerings' => array(
            array(
                'price' => $rowv1['price'],
                'quantity' => $qty,
                'is_enabled' => true
            )
        )
    );
   
}
}
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) . "'");

    $data = array(
        'products' => $variants,
        'price_on_property'=> array($property_id1, $property_id2),
        'quantity_on_property' => array($property_id1, $property_id2),
        'sku_on_property' => array($property_id1, $property_id2)
    );
    $json_data =json_encode($data);
	addlog("order data". $json_data, "INFO");
   //print_r($json_data);
    // Prepare the API endpoint
    $url = "https://api.etsy.com/v3/application/listings/{$listing_id}/inventory";
    
   // print_r("url".$url."access token",$access_token);
    // Set the headers
    $headers = array(
        'Authorization: Bearer ' . $access_token,
        "x-api-key: " . $api_key,
        'Content-Type: application/json'
    );
    //print_r(json_encode($headers));
    $result = getres($url,$json_data,$headers);
    $r = json_decode($result);
    if (isset($r->error) && $r->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);
            $url = "https://api.etsy.com/v3/application/listings/{$listing_id}/inventory";
    
            // Set the headers
            $headers = array(
                'Authorization: Bearer ' . $access_token,
                "x-api-key: " . $api_key,
                'Content-Type: application/json'
            );
            $result = getres($url,$json_data,$headers);
           $r = json_decode($result);
        }
    } 

	addlog("order data res". $r, "INFO");


$conn->query("update shopifyorders set resp = '".mysqli_real_escape_string($conn, json_encode($r))."' where user_id = ".$user_id." and id = ".$row_id);
@mail("pankajnarang81@gmail.com", "cronordersgen_v3: new cron executed", "Order Number - ".$order_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 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_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 deletelistings($url,$headers){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    //curl_setopt($ch, CURLOPT_POSTFIELDS, $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;
	}
    else if(strpos($optionName,'test1') !== false){
		$property_id = 513;
	}
    else if(strpos($optionName,'test2') !== false){
		$property_id = 514;
	}
    return $property_id;
}

//  $api_key = $etsyConfig['api_key'];
//  $api_secret = $etsyConfig['api_secret'];    
//  $user_id = 2241;
//  $etsyResult = $conn->query("SELECT * FROM `etsy_keys` where user_id = 2241");
//  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'];
//     echo $refresh_token;
// 	$listing_id = 1078071701;
// 	$api_key = $etsyConfig['api_key'];
//     $data = array(
//         'products' => array(
//             array(
//                 'sku' => 'aa14',
//                 'property_values' => array(
//                     array(
//                         'property_id' => 513,
//                         'property_name' => 'test1',
                      
//                         'values' => array('green')
//                     ),
//                     array(
//                         'property_id' => 514,
//                         'property_name' => 'test2',
                      
//                         'values' => array('small')
//                     )
//                 ),
//                 'offerings' => array(
//                     array(
//                         "price"=>25.00,
//                         'quantity' => 19,
//                         'is_enabled' => true
//                     )
//                 )
//                     ), array(
//                         'sku' => 'aa15',
//                         'property_values' => array(
//                             array(
//                                 'property_id' => 513,
//                                 'property_name' => 'test1',
                              
//                                 'values' => array('green')
//                             ),
//                             array(
//                                 'property_id' => 514,
//                                 'property_name' => 'test2',
                              
//                                 'values' => array('medium')
//                             )
//                         ),
//                         'offerings' => array(
//                             array(
//                                 "price"=>26.27,
//                                 'quantity' => 19,
//                                 'is_enabled' => true
//                             )
//                         )
//                     )
//         ),
//         'price_on_property'=> array(513, 514),
//         'quantity_on_property' => array(513, 514),
//         'sku_on_property' => array(513, 514)
//     );
    
//     // Convert the payload to JSON
//     $json_data = json_encode($data);
    


    


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);
?> -->
