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

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

    $row = $result->fetch_assoc();

    $shopurl = $row['shopurl'];
	 $token = $row['token'];	
      echo $token;
    $productResult = $conn->query("select * from products where  shopifyproductid != '' and user_id = 561");
	if($productResult->num_rows > 0){
		while($productRow = $productResult->fetch_assoc()){
			$shopifyproductid = $productRow['shopifyproductid'];
            $sectionname = $productRow['section_name'];
            echo $sectionname;
             $data = array(
                "product"=>array(
                    "id"=>$shopifyproductid,
                    "tags"=>$sectionname
                )
             ); 

            print_r($data);

            $res = updateShopifyproduct($token, $shopurl, $shopifyproductid, $data);
            
			echo "done";
            
        }
    }


echo "updated";
function updateShopifyproduct($token, $shopurl, $shopifyproductid, $data){
	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);
	}
	
	return false;
}
?>