<?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/updateshopifyinventoryfgfdg.txt", "a+") or die("Unable to open log file!");
addlog("Execution Started", "INFO");


$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 = 561 ");

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_561 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 " updated"; 	
		// mysqli_commit($conn);		
	}
}
mysqli_autocommit($conn, TRUE);


function fetchFromEtsy($user_id, $shop_id, $access_token, $refresh_token) {
	global $conn, $etsyConfig;
	$api_key = $etsyConfig['api_key'];
	
		

	$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'];
			
			
		//	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?includes=Listing',
                    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?includes=Listing',
                            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));
		    }
		    $listing = $inventoryData->listing;
           $etsylistingid =$listing->listing_id;
           $section_id = $listing->shop_section_id;
           $section_name ='';
           if ($section_id != "") {
               $section_name = getSectionName($user_id, $access_token, $refresh_token, $shop_id, $section_id);
           }

			 $conn->query("update products set section_id = '".mysqli_real_escape_string($conn, $section_id)."',section_name = '".mysqli_real_escape_string($conn,  $section_name)."' where  etsylistingid = '".mysqli_real_escape_string($conn,  $etsylistingid)."' and user_id = ".$user_id)or die("error in query"); 
             echo "update products set section_id = '".mysqli_real_escape_string($conn, $section_id)."',section_name = '".mysqli_real_escape_string($conn,  $section_name)."' where  etsylistingid = '".mysqli_real_escape_string($conn,  $etsylistingid)."' and user_id = ".$user_id;
              echo "etsylistingid".$etsylistingid."section_id".$section_id."section_name".$section_name;
				
			
		}
	}				
}

function getSectionName($user_id, $access_token, $refresh_token, $shop_id, $section_id)
{
	global $conn, $etsyConfig;
	$section_name = "";
	$sResult = $conn->query("SELECT * FROM `etsy_section` where shop_section_id = '" . $section_id . "'");
	if ($sResult->num_rows > 0) {
		$sRow = $sResult->fetch_assoc();
		$section_name = $sRow["title"];
	} else {
		$api_key = $etsyConfig['api_key'];
		$header = array("Authorization: Bearer " . $access_token, "x-api-key: " . $api_key);
		try {
			$curl = curl_init();
			curl_setopt_array($curl, array(
				CURLOPT_URL => 'https://openapi.etsy.com/v3/application/shops/' . $shop_id . '/sections',
				CURLOPT_HTTPHEADER => $header,
				CURLOPT_SSL_VERIFYPEER => false,
				CURLOPT_RETURNTRANSFER => true
			));
			$r_body = curl_exec($curl);
			curl_close($curl);
			$r = json_decode($r_body, true);
			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, $refreshTokenArray['access_token']) . "',refresh_token = '" . mysqli_real_escape_string($conn, $refreshTokenArray['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/shops/' . $shop_id . '/sections',
						CURLOPT_HTTPHEADER => $header,
						CURLOPT_SSL_VERIFYPEER => false,
						CURLOPT_RETURNTRANSFER => true
					));
					$r_body = curl_exec($curl);
					curl_close($curl);
					$r = json_decode($r_body, true);
					insertSections($user_id, $r);
				}
			} else {
				insertSections($user_id, $r);
			}
			$sResult = $conn->query("SELECT * FROM `etsy_section` where shop_section_id = '" . $section_id . "'");
			if ($sResult->num_rows > 0) {
				$sRow = $sResult->fetch_assoc();
				$section_name = $sRow["title"];
			}
		} catch (OAuthException $e) {
			print_r($e);
			error_log($e->getMessage());
			error_log(print_r($oauth->getLastResponse(), true));
			error_log(print_r($oauth->getLastResponseInfo(), true));
		}
	}
	return $section_name;
}

function insertSections($user_id, $r)
{
	global $conn;
	if ($r["count"] > 0) {
		if ($r["results"] != '') {
			foreach ($r["results"] as $section) {
				$shop_section_id = $section["shop_section_id"];
				$sResult = $conn->query("SELECT * FROM `etsy_section` where shop_section_id = " . $shop_section_id);
				if ($sResult->num_rows > 0) {
					continue;
				}
				$title = $section["title"];
				$etsy_user_id = $section["user_id"];
				$conn->query("insert into etsy_section(shop_section_id, title, etsy_user_id, user_id) values ('" . mysqli_real_escape_string($conn, $shop_section_id) . "','" . mysqli_real_escape_string($conn, $title) . "','" . mysqli_real_escape_string($conn, $etsy_user_id) . "','" . mysqli_real_escape_string($conn, $user_id) . "')");
			}
		}
	}
}

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/2023-04/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/2023-04/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/2023-04/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/2023-04/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/2023-04/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/2023-04/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/2023-04/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);
?>