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

$user_id = 1217;
$configResult = $conn->query("select * from etsy_keys where valid = 1 and user_id = 1217");
echo $configResult;
echo "ddd";
if ($configResult->num_rows > 0) {
    $configRow = $configResult->fetch_assoc();
    $shop_id = $configRow['shop_id'];
    $access_token = $configRow['access_token'];
    $refresh_token = $configRow['refresh_token'];
    $api_key = $etsyConfig['api_key'];
    // echo "changedeep14" ;
    // echo $api_key ;
    // echo "changedeep17" ;
    $existingSKUs = array();
    $result = $conn->query("select distinct etsylistingid from products where user_id = " . $user_id);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $existingSKUs[] = $row['etsylistingid'];
        }
    }

} 
// print_r($configResult);
// echo "changedeep" ;
// echo $configResult ;





	global $conn;
echo "dhhh";
	echo $shop_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 . '/listings?state=active&limit=100&offset=0',
			CURLOPT_HTTPHEADER => $header,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_RETURNTRANSFER => true
		));
		$r_body = curl_exec($curl);
		echo $r_body ;
		curl_close($curl);
		$r = json_decode($r_body);
		print_r($r);
		die();
try{

		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, $access_token) . "',refresh_token = '" . mysqli_real_escape_string($conn, $refresh_token) . "', updated_at = now() where user_id = " . $user_id);
				// fetchCatalog($user_id, $shop_id, $access_token, $refresh_token, $existingSKUs, $api_key);
			}
		} else {
			insertProducts($user_id, $shop_id, $access_token, $refresh_token, $existingSKUs, $api_key, $r);
		}
	}   catch (OAuthException $e) {
		print_r($e);
		error_log($e->getMessage());
		error_log(print_r($oauth->getLastResponse(), true));
		error_log(print_r($oauth->getLastResponseInfo(), true));
	}

function insertProducts($user_id, $shop_id, $access_token, $refresh_token, $existingSKUs, $api_key, $r)
{
	global $conn;
	$header = array("Authorization: Bearer " . $access_token, "x-api-key: " . $api_key);

		if ($r->count > 0) {
			$c = $r->count;
			$c = $c / 100;
			$c = intval($c);
			$c = $c + 1;
			for ($q = 0; $q <= $c; $q++) {
				$offset = $q * 100;

				$curl = curl_init();
				curl_setopt_array($curl, array(
					CURLOPT_URL => 'https://openapi.etsy.com/v3/application/shops/' . $shop_id . '/listings?state=active&includes=Translations&limit=100&offset=' . $offset,
					CURLOPT_HTTPHEADER => $header,
					CURLOPT_SSL_VERIFYPEER => false,
					CURLOPT_RETURNTRANSFER => true
				));
				$response_body = curl_exec($curl);
				curl_close($curl);
				echo $response_body;
				$response = json_decode($response_body);

				if ($response->results != '') {
					foreach ($response->results as $listing) {
						if (!isset($listing->listing_id)) {
							// TODO: Listing id missing
							continue;
						}
						$etsy_listing_id = $listing->listing_id;
						if (in_array($etsy_listing_id, $existingSKUs)) {
							// TODO: Listing id already exists
							continue;
						}
						$title = "";
						$description = "";
						$tags = "";
						$materials = "";
						$who_made = "";
						$is_supply = "";
						$when_made = "";
						$section_id = "";
						$section_name = "";
						$images = array();
						$category_path = "";
						$etsy_state = "";
						$variations = array();
						print_r("anjali listing id ".$etsy_listing_id);
						if (isset($listing->title)) {
							$title = $listing->title;
						}

						if (isset($listing->description)) {
							$description = $listing->description;
						}

						$tagsArr = array();
						if (isset($listing->tags)) {
							$tagsLength = count($listing->tags);
							for ($i = 0; $i < $tagsLength; $i++) {
								$tagsArr[] = $listing->tags[$i];
							}
						}
						$tags = implode(", ", $tagsArr);

						$materialsArr = array();
						if (isset($listing->materials)) {
							$materialsLength = count($listing->materials);
							for ($i = 0; $i < $materialsLength; $i++) {
								$materialsArr[] = $listing->materials[$i];
							}
						}
						$materials = implode(", ", $materialsArr);

						if (isset($listing->who_made)) {
							$who_made = $listing->who_made;
						}
						if (isset($listing->is_supply)) {
							$is_supply = $listing->is_supply;
						}
						if (isset($listing->when_made)) {
							$when_made = $listing->when_made;
						}

						$arr = array('materials' => $materials, 'who_made' => $who_made, 'is_supply' => $is_supply, 'when_made' => $when_made);
						$attributes  = json_encode($arr);

						//if (isset($listing->Section)) {
							$section_id = $listing->shop_section_id;
						//}
						if ($section_id != "") {
							$section_name = getSectionName($user_id, $access_token, $refresh_token, $shop_id, $section_id);
						}

						$category = array();
						if (isset($listing->category_path)) {
							$category_pathLength = count($listing->category_path);
							for ($i = 0; $i < $category_pathLength; $i++) {
								$category[] = $listing->category_path[$i];
							}
						}
						$category_path = implode(", ", $category);
						if (isset($listing->state)) {
							$etsy_state = $listing->state;
						}

						$curl = curl_init();
						curl_setopt_array($curl, array(
							CURLOPT_URL => 'https://openapi.etsy.com/v3/application/shops/' . $shop_id . '/listings/' . $etsy_listing_id . '/images',
							CURLOPT_HTTPHEADER => $header,
							CURLOPT_SSL_VERIFYPEER => false,
							CURLOPT_RETURNTRANSFER => true
						));
						$image_body = curl_exec($curl);
						curl_close($curl);
						$imgResponse = json_decode($image_body);

						if ($imgResponse != "") {
							if (isset($imgResponse->results)) {
								$pictureLength = count($imgResponse->results);
								for ($i = 0; $i < $pictureLength; $i++) {
									if (isset($imgResponse->results[$i]->url_fullxfull)) {
										$images[] = $imgResponse->results[$i]->url_fullxfull;
									} else if (isset($imgResponse->results[$i]->url_570xN)) {
										$images[] = $imgResponse->results[$i]->url_570xN;
									} else if (isset($imgResponse->results[$i]->url_170x135)) {
										$images[] = $imgResponse->results[$i]->url_170x135;
									} else if (isset($imgResponse->results[$i]->url_75x75)) {
										$images[] = $imgResponse->results[$i]->url_75x75;
									} else {
										$images[] = array();
									}
								}
							}
						}

						if ($listing->has_variations == 1) {
							$curl = curl_init();
							curl_setopt_array($curl, array(
								CURLOPT_URL => 'https://openapi.etsy.com/v3/application/listings/' . $etsy_listing_id . '/inventory',
								CURLOPT_HTTPHEADER => $header,
								CURLOPT_SSL_VERIFYPEER => false,
								CURLOPT_RETURNTRANSFER => true
							));
							$response_body1 = curl_exec($curl);
							curl_close($curl);
							$variation = json_decode($response_body1);

							if ($variation != "") {
								if (isset($variation->products)) {
									$varLength = count($variation->products);
									for ($i = 0; $i < $varLength; $i++) {
										if (isset($variation->products[$i]->product_id)) {
											$variations[$i]['sku'] = $variation->products[$i]->sku;
										} else {
											$variations[$i]['sku'] = "";
										}
										if (isset($variation->products[$i]->property_values[0]->property_name)) {
											$variations[$i]['option1name'] = $variation->products[$i]->property_values[0]->property_name;
										} else {
											$variations[$i]['option1name'] = "";
										}

										if (isset($variation->products[$i]->property_values[0]->values[0])) {
											$variations[$i]['option1val'] = $variation->products[$i]->property_values[0]->values[0];
										} else {
											$variations[$i]['option1val'] = "";
										}

										if (isset($variation->products[$i]->property_values[1]->property_name)) {
											$variations[$i]['option2name'] = $variation->products[$i]->property_values[1]->property_name;
										} else {
											$variations[$i]['option2name'] = "";
										}

										if (isset($variation->products[$i]->property_values[1]->values[0])) {
											$variations[$i]['option2val'] = $variation->products[$i]->property_values[1]->values[0];
										} else {
											$variations[$i]['option2val'] = "";
										}

										if (isset($variation->products[$i]->offerings[0]->price->amount)) {
											$variations[$i]['price'] = $variation->products[$i]->offerings[0]->price->amount / $variation->products[$i]->offerings[0]->price->divisor;
											
										} else {
											$variations[$i]['price'] = "";
										}

										if (isset($variation->products[$i]->offerings[0]->quantity)) {
											$variations[$i]['quantity'] = $variation->products[$i]->offerings[0]->quantity;
										} else {
											$variations[$i]['quantity'] = "";
										}
									}
								}

								$productQuery = "INSERT INTO products(title, description, tags, attributes, section_id, section_name, category_path, etsylistingid, etsy_state, option1name, option2name, user_id, created_at, updated_at) VALUES('" . mysqli_real_escape_string($conn, $title) . "', '" . mysqli_real_escape_string($conn, $description) . "', '" . mysqli_real_escape_string($conn, $tags) . "', '" . mysqli_real_escape_string($conn, $attributes) . "', '" . mysqli_real_escape_string($conn, $section_id) . "', '" . mysqli_real_escape_string($conn, $section_name) . "', '" . mysqli_real_escape_string($conn, $category_path) . "', '" . mysqli_real_escape_string($conn, $etsy_listing_id) . "', '" . mysqli_real_escape_string($conn, $etsy_state) . "', '" . mysqli_real_escape_string($conn, $variations[0]['option1name']) . "', '" . mysqli_real_escape_string($conn, $variations[0]['option2name']) . "', '" . $user_id . "', now(), now())";
								$productResult = mysqli_query($conn, $productQuery);
								$product_id = $conn->insert_id;

								foreach ($variations as $productVariant) {
									$productVariantQuery = "INSERT INTO product_variants(product_id, sku, option1val, option2val, price, quantity, user_id, created_at, updated_at) VALUES('" . mysqli_real_escape_string($conn, $product_id) . "', '" . mysqli_real_escape_string($conn, $productVariant['sku']) . "', '" . mysqli_real_escape_string($conn, $productVariant['option1val']) . "', '" . mysqli_real_escape_string($conn, $productVariant['option2val']) . "', '" . mysqli_real_escape_string($conn, $productVariant['price']) . "', '" . mysqli_real_escape_string($conn, $productVariant['quantity']) . "', '" . $user_id . "', now(), now())";
									$productVariantResult = mysqli_query($conn, $productVariantQuery);
								}
								unset($variations);
								if (!empty($images)) {
									foreach ($images as $imgurl) {
										$productImageQuery = "INSERT INTO product_images(product_id, imgurl, user_id, created_at, updated_at) VALUES('" . mysqli_real_escape_string($conn, $product_id) . "', '" . mysqli_real_escape_string($conn, $imgurl) . "', '" . $user_id . "', now(), now())";
										$productImageResult = mysqli_query($conn, $productImageQuery);
									}
								}
							}
						} else {
							$price = 0.0;
							$quantity = 0;
							$sku = "";
							if (isset($listing->price)) {
								if (isset($listing->price->amount)) {
									$price = $listing->price->amount / $listing->price->divisor;
								}
							}
							if (isset($listing->quantity)) {
								$quantity = $listing->quantity;
							}
							if (isset($listing->skus[0])) {
								$sku = $listing->skus[0];
							}
							// $productQuery = "INSERT INTO products(title, description, tags, attributes, section_id, section_name, category_path, etsylistingid, etsy_state, user_id, created_at, updated_at) VALUES('" . mysqli_real_escape_string($conn, $title) . "', '" . mysqli_real_escape_string($conn, $description) . "', '" . mysqli_real_escape_string($conn, $tags) . "', '" . mysqli_real_escape_string($conn, $attributes) . "', '" . mysqli_real_escape_string($conn, $section_id) . "', '" . mysqli_real_escape_string($conn, $section_name) . "', '" . mysqli_real_escape_string($conn, $category_path) . "', '" . mysqli_real_escape_string($conn, $etsy_listing_id) . "', '" . mysqli_real_escape_string($conn, $etsy_state) . "', '" . $user_id . "', now(), now())";
							// $productResult = mysqli_query($conn, $productQuery);
							// $product_id = $conn->insert_id;

							if (!empty($images)) {
								foreach ($images as $imgurl) {
									// $productImageQuery = "INSERT INTO product_images(product_id, imgurl, user_id, created_at, updated_at) VALUES('" . mysqli_real_escape_string($conn, $product_id) . "', '" . mysqli_real_escape_string($conn, $imgurl) . "', '" . $user_id . "', now(), now())";
									// $productImageResult = mysqli_query($conn, $productImageQuery);
								}
							}

							// $productVariantQuery = "INSERT INTO product_variants(product_id, sku, price, quantity, user_id, created_at, updated_at) VALUES('" . mysqli_real_escape_string($conn, $product_id) . "', '" . mysqli_real_escape_string($conn, $sku) . "', '" . mysqli_real_escape_string($conn, $price) . "', '" . mysqli_real_escape_string($conn, $quantity) . "', '" . $user_id . "', now(), now())";
							// $productVariantResult = mysqli_query($conn, $productVariantQuery);
						}
					}
				}
			}
		}
	
}
?>