<?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);
	// if ($result->num_rows > 0) {
	// 	while($row = $result->fetch_assoc()) {	
	// 		$existingSKUs[] = $row['productid'];
	// 	}
	// }
	mysqli_autocommit($conn, FALSE);
	$cursor = null;
	$hasNextPage = true;
	while ($hasNextPage) {
		$products = fetchShopifyProducts($cursor, $shopurl, $token);
	   // print_r($products);
		// echo "Product response: " . json_encode($products) . "\n";
		// echo '1';
		// die();
		if (!$products) {
			echo "No products found or an error occurred.\n";
			break;
		}
	
		$variantDataArray = [];
		foreach ($products['edges'] as $productEdge) {
			$product = $productEdge['node'];
			preg_match('/gid:\/\/shopify\/Product\/(\d+)/', $product['id'], $productMatches);
			$product_id = $productMatches[1] ?? null;
			$title = $product['title'];
			$tags = $product['tags'];
			$requiresSellingPlan = $product['requiresSellingPlan'];
			$cd = $product["createdAt"];
			$dateOnly = substr($cd, 0, 10);
			$timeOnly = substr($cd, 11, 19);
			$created_at = $dateOnly . ' ' . $timeOnly;
			$status = $product['status'];
			$product_type = $product['productType'];
			$gid_shopifyproductid = $product['id'];
			$variants1 = $product['variants']['edges'];
			
			$variantCursor = null;
			$variantHasNextPage = true;
			$hasMoreThan250Variants = false;
			
			while ($variantHasNextPage) {
				if ($hasMoreThan250Variants) {
					$variants = fetchProductVariants($variantCursor, $shopurl, $token, $gid_shopifyproductid);
					echo "Variant response: " . json_encode($variants) . "\n";
					if (!$variants) {
						echo "No variants found or an error occurred for product ID: $product_id.\n";
						break;
					}
					foreach ($variants['variants']['edges'] as $variantEdge) {
						$variant = $variantEdge['node'];
						preg_match('/gid:\/\/shopify\/ProductVariant\/(\d+)/', $variant['id'], $variantMatches);
						$variant_id = $variantMatches[1] ?? null;
						
						$gid_shopifyvariantid = $variant['id'];
						$sku = $variant['sku'];
						$price = (float)$variant['price'];
						$compare_at_price = $variant['compareAtPrice'];
						$qty = (int)$variant['inventoryQuantity'];
						
						if ($user_id == 9188) {
							$price = $compare_at_price;
						}
						
						$existingProductQuery = "SELECT id FROM shopifyproducts WHERE productid = '$product_id' AND variantid = '$variant_id'  AND user_id = '$user_id'";
						$existingProductResult = $conn->query($existingProductQuery);
						
						if ($existingProductResult->num_rows > 0) {
							continue;
						}
						
						if (empty($sku)) {
						$sku = $variant['barcode'] ?? '';
					}
					
					$variantDataArray[] = "('$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', '" .
					mysqli_real_escape_string($conn, $created_at) . "')";
				}
				// echo '2';
				
				if(isset($variants['pageInfo']['endCursor'])){
					$variantCursor = $variants['pageInfo']['endCursor'];
				}
				if(isset($variants['pageInfo']['hasNextPage'])){
					$variantHasNextPage = $variants['pageInfo']['hasNextPage'];
					if ($variantHasNextPage) {
						$hasMoreThan250Variants = true;
					} else{
						$hasMoreThan250Variants = false;
						$variantHasNextPage = false;
					}
				}else{
					$variantHasNextPage = false;
					$hasMoreThan250Variants = false;
				}
	
				}else{
	
					if (!$variants1) {
						echo "No variants found or an error occurred for product ID: $product_id.\n";
						break;
					}
					
					foreach ($variants1 as $variantEdge) {
						// echo '3';
						$variant = $variantEdge['node'];
						preg_match('/gid:\/\/shopify\/ProductVariant\/(\d+)/', $variant['id'], $variantMatches);
						$variant_id = $variantMatches[1] ?? null;
						// print_r($variant);
						// die();
						
						$gid_shopifyvariantid = $variant['id'];
						$sku = $variant['sku'];
						$price = (float)$variant['price'];
						$compare_at_price = $variant['compareAtPrice'];
						$qty = (int)$variant['inventoryQuantity'];
						
						if ($user_id == 9188) {
							$price = $compare_at_price;
						}
						
						$existingProductQuery = "SELECT id FROM shopifyproducts WHERE productid = '$product_id' AND variantid = '$variant_id'  AND user_id = '$user_id'";
						$existingProductResult = $conn->query($existingProductQuery);
						
						if ($existingProductResult->num_rows > 0) {
							continue;
						}
						
						if (empty($sku)) {
						$sku = $variant['barcode'] ?? '';
					}
					
					$variantDataArray[] = "('$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,$requiresSellingPlan) . "', '$price', '$qty', '" .
					mysqli_real_escape_string($conn, $created_at) . "')";
				}
				// print_r($variantDataArray);
				// echo '2';
				// die();
				if(isset($variants['pageInfo']['endCursor'])){
					$variantCursor = $variants['pageInfo']['endCursor'];
				}
				if(isset($variants['pageInfo']['hasNextPage'])){
					$variantHasNextPage = $variants['pageInfo']['hasNextPage'];
					if ($variantHasNextPage) {
						$hasMoreThan250Variants = true;
					} else{
						$hasMoreThan250Variants = false;
						$variantHasNextPage = false;
					}
				}else{
					$variantHasNextPage = false;
					$hasMoreThan250Variants = false;
				}
			}
			}
		}
		if (!empty($variantDataArray)) {
			$bulkInsertQuery = "
			INSERT INTO shopifyproducts 
			(user_id, productid, variantid, gid_shopifyproductid, gid_shopifyvariantid, sku, price, qty, dateofmodification)
			VALUES " . implode(',', $variantDataArray);
			// print_r($bulkInsertQuery);
			
			if ($conn->query($bulkInsertQuery) === TRUE) {
				echo "Variants inserted successfully.\n";
			} else {
				echo "Error inserting variants: " . $conn->error . "\n";
			}
			// echo 'Data inserted for 250 products<br>';
		}
	
		$cursor = $products['pageInfo']['endCursor'];
		if (isset($products['pageInfo']['hasNextPage'])) {
			$hasNextPage = $products['pageInfo']['hasNextPage'];
		} else {
			$hasNextPage = false;
		}
		
	}
	mysqli_commit($conn);
	mysqli_autocommit($conn, TRUE);    
	$conn->close();
	echo "Data successfully saved to the database.\n";
	
	function fetchShopifyProducts($cursor, $shopurl, $token) {
		$query = <<<GRAPHQL
		query (\$cursor: String, \$variantCursor: String) {
			products(first: 250, after: \$cursor, query: "status:active") {
				edges {
					node {
						id
						title
						tags
						createdAt
						status
						productType
						requiresSellingPlan
						variants(first: 250, after: \$variantCursor) {
							edges {
								node {
									id
									barcode
									sku
									price
									compareAtPrice
									inventoryQuantity
								}
							}
							pageInfo {
								hasNextPage
								endCursor
							}
						}
					}
				}
				pageInfo {
					hasNextPage
					endCursor
				}
			}
		}
		GRAPHQL;
	
		return executeGraphQLQuery($shopurl, $token, $query, ['cursor' => $cursor, 'variantCursor' => null]);
	}
	
	function fetchProductVariants($variantCursor, $shopurl, $token, $gid_shopifyproductid) {
		$query = <<<GRAPHQL
		query (\$variantCursor: String, \$productID: ID!) {
			product(id: \$productID) {
				variants(first: 250, after: \$variantCursor) {
					edges {
						node {
							id
							sku
							price
							compareAtPrice
							inventoryQuantity
							barcode
						}
					}
					pageInfo {
						hasNextPage
						endCursor
					}
				}
			}
		}
		GRAPHQL;
	
		return executeGraphQLQuery($shopurl, $token, $query, [
			'variantCursor' => $variantCursor,
			'productID' => $gid_shopifyproductid
		]);
	}
	
	function executeGraphQLQuery($shopurl, $token, $query, $variables) {
		$url = "https://{$shopurl}/admin/api/2024-10/graphql.json";
		$headers = [
			"Content-Type: application/json",
			"X-Shopify-Access-Token: {$token}"
		];
	
		$data = json_encode(['query' => $query, 'variables' => $variables]);
	
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	
		$response = curl_exec($ch);
		curl_close($ch);
	
		print_r($response);
		$result = json_decode($response, true);
		if (isset($result['errors'])) {
			echo "GraphQL Error: " . json_encode($result['errors']);
			return null;
		}
	
		// echo 'Print data: ';
		// print_r($result);
		// die();
	
		return $result['data']['product'] ?? $result['data']['products'];
	}

?>