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

	// $conn = new mysqli($host, $username, $password, $dbname);
	// // Check connection
	// if ($conn->connect_error) {
	// 	// TODO: Add some logging and email notification here
	// 	die("Connection failed: " . $conn->connect_error);
	// }
	
    $user_id =  1217;
    $result = $conn->query("select * from users where id = ".$user_id);
    if($result->num_rows < 1){
        die("invalid user id");
    }
    $row = $result->fetch_assoc();
    $shopurl = $row['shopurl'];
    $token = $row['token'];
	// $conn->query("delete from shopifyproducts where id = ".$user_id);
	$existingSKUs = array();
	$result = $conn->query("select * from shopifyproducts where user_id = ".$user_id ." limit 2 ");
	// if ($result->num_rows > 0) {
	// 	while($row = $result->fetch_assoc()) {	
	// 		$existingSKUs[] = $row['productid'];
	// 	}
	// }
	// mysqli_autocommit($conn, FALSE);
	// fetchCatalog($user_id, $shopurl, $token, $existingSKUs, "");
	// mysqli_commit($conn);
	// mysqli_autocommit($conn, TRUE);    
	
	// function fetchCatalog($user_id, $shopurl, $token, $existingSKUs, $nextLink){
	// 	global $conn;
	// 	$productUrl = $nextLink;
	// 	if($nextLink == ""){
	// 		$productUrl="https://".$shopurl."/admin/api/2023-10/products.json?limit=100";
	// 	}		
	// 	$session = curl_init();
	// 	curl_setopt($session, CURLOPT_URL, $productUrl);
	// 	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);
	// 		$products_array = json_decode($body, true);	
          
	// 		if($products_array){
	// 			// foreach($products_array['products'] as $product) {	
	// 			// 	$product_id = $product["id"];
	// 			// 	$title = $product["title"];
	// 			// 	if (in_array($product_id, $existingSKUs)) {
	// 			// 		continue;
	// 			// 	}
	// 			// 	$product_type = $product["product_type"];
	// 			// 	$gid_shopifyproductid = $product["admin_graphql_api_id"];
	// 			// 	$variants = $product["variants"];

                    

    //             //     //exit(0);
	// 			// 	//$conn->query("insert into test_1250(shopifyproductid, imgarr, created_at) values ('".$product_id."', '".mysqli_real_escape_string($conn, $product['tags'])."', now())");
	// 			// 	foreach($variants as $variant){
	// 			// 		$variant_id = $variant["id"];	
	// 			// 		$gid_shopifyvariantid = $variant["admin_graphql_api_id"];
	// 			// 		$sku = $variant["sku"];
	// 			// 		$price = $variant["price"];
	// 			// 		$compare_at_price = $variant["compare_at_price"];
	// 			// 		$qty = $variant["inventory_quantity"];
	// 			// 		//$qty = $variant["weight"];

	// 			// 		//echo "<pre>weight".$weight."      </pre> ";
	// 			// 		//exit(0);
	// 			// 	//	echo "insert into shopifyproducts_1250(user_id, productid, variantid, gid_shopifyproductid, gid_shopifyvariantid, sku, price, qty, dateofmodification) values ('".$user_id."', '".$product_id."','".$variant_id."','".mysqli_real_escape_string($conn, $gid_shopifyproductid)."','".mysqli_real_escape_string($conn, $gid_shopifyvariantid)."','".mysqli_real_escape_string($conn, $sku)."','".$price."','".$qty."', now())";exit;
	// 			// 	//	$conn->query("insert into shopifyproducts(user_id, title, productid, variantid, gid_shopifyproductid, gid_shopifyvariantid, sku, price, qty, compare_at_price, dateofmodification) values ('".$user_id."', '".mysqli_real_escape_string($conn, $title)."', '".$product_id."','".$variant_id."','".mysqli_real_escape_string($conn, $gid_shopifyproductid)."','".mysqli_real_escape_string($conn, $gid_shopifyvariantid)."','".mysqli_real_escape_string($conn, $sku)."','".$price."','".$qty."', '".$compare_at_price."', now())");
    //             //     echo "ffdffge";
    //             //     echo $variant_id;
    //             //     die();
	// 			// 	    // $conn->query("insert into shopifyproducts(user_id, productid, variantid, gid_shopifyproductid, gid_shopifyvariantid, sku, price, qty, dateofmodification) values ('".$user_id."', '".$product_id."','".$variant_id."','".mysqli_real_escape_string($conn, $variant["weight"])."','".mysqli_real_escape_string($conn, $gid_shopifyvariantid)."','".mysqli_real_escape_string($conn,$sku)."','".$price."','".$qty."', now())");
	// 			// 	}	
	// 			// }					
	// 			mysqli_commit($conn);
	// 		}
	// 		$pattern = '/rel="previous",\s*<(.*)>;\s*rel="next"/smiU';
	// 		$res1 = preg_match_all($pattern, $header, $result1);
	// 		sleep(1);
	// 		if($res1){			
	// 			$nextLink = isset($result1[1][0])?trim($result1[1][0]):"";			
	// 			fetchCatalog($user_id, $shopurl, $token, $existingSKUs, $nextLink);
	// 		} else {
	// 		    $pattern = '/Link:\s*<(.*)>;\s*rel="next"/smiU';
	// 		    $res1 = preg_match_all($pattern, $header, $result1);
	// 		    if($res1){			
	// 			    $nextLink = isset($result1[1][0])?trim($result1[1][0]):"";			
	// 			    fetchCatalog($user_id, $shopurl, $token, $existingSKUs, $nextLink);
	// 		    } else {
	// 		        echo $productUrl;
	// 	            //print_r($response_arr);        
	// 		    }
	// 		}
	// 	} else if(strstr(($response_arr[0]), "HTTP/2 500")){
	// 	    sleep(1);
	// 	    fetchCatalog($user_id, $shopurl, $token, $existingSKUs, $nextLink);
	// 	} else if(strstr(($response_arr[0]), "HTTP/2 429")){
	// 	    sleep(2);
	// 	    fetchCatalog($user_id, $shopurl, $token, $existingSKUs, $nextLink);
	// 	} else {
	// 	    echo $productUrl;
	// 	    //print_r($response_arr);
	// 	}		
	// }







$priceArr = array();
$priceArrDb = array();
$result = $conn->query("SELECT * FROM shopifyproducts WHERE user_id = ".$user_id);
// print_r($result );
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $variantid = $row['variantid'];
        $qty = $row['qty'];
        $price = $row['price'];
		echo $variantid . "  ";
		echo $price . "  ";
		echo $qty . "  ";

        // Corrected SQL query with proper concatenation
		$result112 = $conn->query("SELECT * FROM product_variants WHERE user_id = $user_id AND shopifyvariantid = $variantid");

		$priceflag =0;
		$quantityflag =0;

        if ($result112) {
			$row2 = $result112->fetch_assoc();
		    $shopifyvariantid  = $row2['shopifyvariantid'];
		    $Dbprice    = $row2['price'];
			$Dbquantity =  $row2['quantity'];
			echo $Dbprice . " Dbprice ";
			echo $Dbquantity . " Dbquantity ";
		  
       
		if($qty  !=  $Dbquantity ){
		   	echo " quantity mismatch " ;
			$quantityflag = 1;
			echo $qty ;
			echo $qty ;
		}

		if($price  !=   $Dbprice  ){
			echo " price mismatch " ;
		
			$priceflag = 1;
		}
		
		if($priceflag == 1 || $quantityflag == 1){

			echo "  uuuppp ";
			 die();

			updateInventoryAndPrice($shopifyvariantid, $priceflag, $quantityflag, $Dbprice, $Dbquantity , $token,  $shopurl);
			exit();
		}
	} else {
		// Handle query failure
		echo "Error executing SQL: " . $conn->error;
	}
    }
}

//  print_r($priceArr);
 
$data = array();

function updateInventoryAndPrice($shopifyvariantid, $priceflag, $quantityflag, $Dbprice, $Dbquantity , $token,  $shopurl){


    if ($priceflag == 1 && $quantityflag == 1) {
		$data = array(
			"variant" => array(
				"id" => $shopifyvariantid,
				"price" => number_format($Dbprice, 2, '.', ''),
				"quantity" => $Dbquantity
			)
		);
		

	} elseif ($quantityflag == 1 && $priceflag != 1) {
		$data = array(
			"variant" => array(
				"id" => $shopifyvariantid,
				"quantity" => $Dbquantity
			)
		);
		// print_r($data);

	} elseif ($quantityflag != 1 && $priceflag == 1) {
		$data = array(
			"variant" => array(
				"id" => $shopifyvariantid,
				"price" => number_format($Dbprice, 2, '.', ''),
			)
		);
		print_r($data);

	} else {
		echo " error ";
	}

	// die(0);
                global $conn;
                $url = "https://".$shopurl."/admin/api/2023-04/variants/". $shopifyvariantid .".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);	
				print_r($response_arr);
                
          
                return true;
    

// if($result1->num_rows > 0){
// 	while($row = $result1->fetch_assoc()){
// 		$shopifyvariantid = $row['shopifyvariantid'];
// 		$price = $row['price'];
        
// 		$price = number_format($price, 2, '.', '');
// 		//echo $shopifyvariantid;
// 		$orig_price = $row['orig_price'];
// 		if($orig_price > 0){
// 		    $price = $orig_price;
// 		}
// 		$quantity = $row['quantity'];
      
		
//         echo "   DBquantity>>>>>>   ";
//         // echo $quantity;

// 		echo "       ";
//          echo $priceArr[$shopifyvariantid];
// 		// echo "  <<<<shopffiyproduct  ";
        
  
// 		if(array_key_exists($shopifyvariantid, $priceArr) && $priceArr[$shopifyvariantid] != $quantity){
// 		    echo $shopifyvariantid." - ".$priceArr[$shopifyvariantid]." <> ".$quantity."---<br />";
// 			echo "final";
// 		}
// 	}
// 	echo "price in our db";


// }
}