<?php

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



// $conn = new mysqli($dbhost, $dbusername, $password, $dbname);

// // Check connection
// if ($conn->connect_error) {
// echo"hjfghjghjghjghjg";
// 	die("");
// }

// mysqli_set_charset($conn, "utf8");


$result = $conn->query("select * from users where id = 2732");//(s.inventory_sync = 1 or s.price_sync = 1) and
// 958, 3409, 3794 - activated without paid plan to just import // 3784 don't ever use this as user is doing manual changes in inventory.
// 7512,16735,3720,6067,16968,17450,7073,12617,19060,12092,12202,39844,38737
if ($result->num_rows > 0) {
	while($row = $result->fetch_assoc()) {	
		$id = $row['id'];
		$shopurl = $row['shopurl'];
		$token = $row['token'];		
		
	
		
		
	
		}
	
		
		updatePrice($id, $token, $shopurl);
		
		echo "price updated updated"; 	
	}

mysqli_autocommit($conn, TRUE);
$conn->query("update crons set isrunning = 0 where crontype = 'updateshopifyinventory2new'");



function updatePrice($user_id, $token, $shopurl){
	global $conn;
	$gidsMapping = array();
	
	
	$result = $conn->query("select * from product_variants where user_id = ".$user_id." and  shopifyvariantid != '' ");
	if ($result->num_rows > 0) {
		$count = 1;
		$jsonStr = "";
		while($row = $result->fetch_assoc()) {	
			$shopifyvariantid =$row['shopifyvariantid'];
			$rowid = $row['id'];
			$price = $row['price'];
            echo "price afterrrbeforer fixxx ".$price;

		    $price = applyPriceMarkup($price);



            echo "price afterrrr fixxx ".$price;

            // die();
            $gid_shopifyvariantid = "gid://shopify/ProductVariant/".$shopifyvariantid;
			$jsonStr = $jsonStr.'
			                variant'.$rowid.':productVariantUpdate(input: 
							{id:"'.$gid_shopifyvariantid.'",
							price:"'.$price.'"
							}) {
																	userErrors {
																	  field
																	  message
																	}
							}';
			$count++;
			if($count > 99){
				$jsonStr = 'mutation{'.$jsonStr.'}';
				priceUpdate($user_id, $shopurl, $token, $jsonStr);
				sleep(10);
				$count = 1;
				$jsonStr = "";
			}
		}
		if($count > 1) {
		    $jsonStr = 'mutation{'.$jsonStr.'}';
		    priceUpdate($user_id, $shopurl, $token, $jsonStr);
		}
	}
}
	function priceUpdate($user_id, $shopurl, $token, $jsonStr) {
	    global $conn;
	    echo $jsonStr;
		$iurl = "https://".$shopurl."/admin/api/".SHOPIFY_API_VERSION."/graphql.json";
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $iurl);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/graphql', 'X-Shopify-Access-Token:'.$token));
		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, $jsonStr);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		$response = curl_exec ($curl);
		curl_close ($curl);
		$response_arr = explode("\n",$response);
		print_r($response_arr);
        mysqli_autocommit($conn, FALSE);
		if( (strstr(($response_arr[0]), "200")) ){
			$respJson = end($response_arr);
			$respArr = json_decode($respJson, true);
			if(isset($respArr['data'])){
			    foreach($respArr['data'] as $k => $v){
			        $rowid = str_replace("variant", "", $k);
			        if(count($v['userErrors']) < 1){
			            //$conn->query("update product_variants set priceflag = 0 where user_id = ".$user_id." and id = ".$rowid);
						echo "price updated for the .".$k. " and ".$v;
			            echo $rowid.'----';
			        }
			    }
			}
		}
		else {
          
			 echo "2nd try to update price";
			echo $jsonStr;
			$iurl = "https://".$shopurl."/admin/api/".SHOPIFY_API_VERSION."/graphql.json";
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $iurl);
			curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/graphql', 'X-Shopify-Access-Token:'.$token));
			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, $jsonStr);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			$response = curl_exec ($curl);
			curl_close ($curl);
			$response_arr = explode("\n",$response);
			print_r($response_arr);
			mysqli_autocommit($conn, FALSE);
			if( (strstr(($response_arr[0]), "200")) ){
				$respJson = end($response_arr);
				$respArr = json_decode($respJson, true);
				if(isset($respArr['data'])){
					foreach($respArr['data'] as $k => $v){
						$rowid = str_replace("variant", "", $k);
						if(count($v['userErrors']) < 1){
							$conn->query("update product_variants set priceflag = 0 where user_id = ".$user_id." and id = ".$rowid);
							echo "price updated for the .".$k. " and ".$v;
							echo $rowid.'----';
						}
					}
				}
			}
		}
		mysqli_commit($conn);
		mysqli_autocommit($conn, TRUE);
	}





    function applyPriceMarkup($price){

        $newprice = $price;
        $newprice=$newprice*0.79;


        return number_format($newprice, 2, ".","");

    }

function updateShopifyVariant($token, $shopurl, $variant_id, $data, $rowid, $user_id){
	global $conn;
	$url = "https://".$shopurl."/admin/api/".SHOPIFY_API_VERSION."/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);

	$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);
	}
	if( (strstr(($response_arr[0]), "200")) || (strstr(($response_arr[1]), "200")) || (strstr(($response_arr[2]), "200")) ) {
	    sleep(1);
		return true;
	} else if(strstr(($response_arr[0]), "HTTP/1.1 404 Not Found")){
		$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;
}



	// Start adding functions to handle multiple locatio
	

	
	function applyMarkup4697($price) {
		$newprice = $price;
		if($price < 50){
			$newprice = $price*0.904;
		} else if($price < 100){
			$newprice = $price*0.906;
		} else if($price < 250){
			$newprice = $price*0.911;
		} else if($price < 500){
			$newprice = $price*0.925;
		} else if($price < 1000){
			$newprice = $price*0.928;
		} else if($price < 2000){
			$newprice = $price*0.9425;
		} else if($price < 3000){
			$newprice = $price*0.949;
		} else if($price < 6000){
			$newprice = $price*0.9545;
		} else if($price < 999999){
			$newprice = $price*0.959;
		}
		if($price > 100){
			$newprice = ceil($newprice);
		}
		return number_format($newprice, 2, ".","");
	}

	
	
?>