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

use OAuth\Client;
$logfile = fopen("logs/cronreimport-". date("Y-m-d") .".txt", "a+") or die("Unable to open log file!");
addlog("Execution Started", "INFO");

$cronQuery = $conn->query("select * from crons where crontype = 'cronreimport_v3'");
$cronrow = $cronQuery->fetch_assoc();
if ($cronrow['isrunning'] == 1) {
	@mail("khariwal.rohit@gmail.com", "cronreimport_v3: Cron already running", "cronreimport_v3: Cron already running");
	addlog("Stopped due to previous cron already running", "INFO");
	die("");
}
$conn->query("update crons set lastrun = now(), isrunning = 1 where crontype = 'cronreimport_v3'");


$result = $conn->query("select distinct user_id from products where status = 'reimport in progress' and user_id in (select user_id from etsy_keys where apiversion = 'v3' )");

	if ($result->num_rows > 0) {
		while($row = $result->fetch_assoc()) {
			$user_id = $row['user_id'];
			echo $user_id;
            addlog("Reimport process started for user_id - ".$user_id, "INFO");
			processReimport($user_id);
		}
		$conn->query("update crons set lastrun = now(), isrunning = 0 where crontype = 'cronreimport_v3'");

	}

	
	
function processReimport($user_id) {
    global $conn, $etsyConfig;
    $userResult = $conn->query("select * from users where id = '".$user_id."' and installationstatus = 1");
    if($userResult->num_rows < 1){
        return false;
    }
    $userRow = $userResult->fetch_assoc();
    $shopurl = $userRow['shopurl'];
    $shopifytoken = $userRow['token'];
    //echo $shopifytoken;
   
    $configResult = $conn->query("select * from etsy_keys where valid = 1 and user_id = '".$user_id."'");
    if($configResult->num_rows > 0){
        $configRow = $configResult->fetch_assoc();
        $shop_id = $configRow['shop_id'];
        $oauth_token = $configRow['oauth_token'];
        $oauth_token_secret = $configRow['oauth_token_secret'];
        $access_token = $configRow['access_token'];
        $refresh_token = $configRow['refresh_token'];
        $api_key = $etsyConfig['api_key'];
        //echo $api_key;
       
        $productResult = $conn->query("select * from products where status = 'reimport in progress' and user_id = ".$user_id);
        if($productResult->num_rows > 0){
            while($productRow = $productResult->fetch_assoc()){
                $etsylistingid = $productRow['etsylistingid'];
                $product_id = $productRow['product_id'];
                $shopifyproductid = $productRow['shopifyproductid'];
                
                if($shopifyproductid != ""){
                     
                    $res = deleteShopifyProduct($user_id, $shopifytoken, $shopurl, $shopifyproductid);  
					echo $res; 
                }
                $conn->query("delete from products where product_id = '".mysqli_real_escape_string($conn, $product_id)."' and user_id = ".$user_id);
                $conn->query("delete from product_images where product_id = '".mysqli_real_escape_string($conn, $product_id)."' and user_id = ".$user_id);
                $conn->query("delete from product_variants where product_id = '".mysqli_real_escape_string($conn, $product_id)."' and user_id = ".$user_id);
                  processItem($user_id, $etsylistingid, $shop_id, $oauth_token, $oauth_token_secret,$access_token,$refresh_token,$api_key);
                $conn->query("update products set status = 'Import in progress' where status = 'Ready to import' and etsylistingid = '".mysqli_real_escape_string($conn, $etsylistingid)."' and user_id = ".$user_id);
				addlog("updated etsy product - ".$etsylistingid, "sucess");	
            }
        }
    } else {
        addlog("No valid Etsy keys found. user_id - ".$user_id, "ERROR");				
    }
	return true;		
}
function processItem($user_id, $etsylistingid, $shop_id, $oauth_token, $oauth_token_secret,$access_token,$refresh_token,$api_key) {
    global $conn;
	echo "In process item";
	$header = array("Authorization: Bearer " . $access_token, "x-api-key: " . $api_key);
    //echo json_encode($header);
   
 try {
        $curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL => 'https://openapi.etsy.com/v3/application/listings/'.$etsylistingid.'?includes=Images&Section',
			CURLOPT_HTTPHEADER => $header,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_RETURNTRANSFER => true
		));
		$r_body = curl_exec($curl);
		curl_close($curl);
		$r = json_decode($r_body);
		//print_r($r);
		
    if (isset($r->error) && $r->error == 'invalid_token') {
		echo $r->error;
		$client = new Etsy\OAuth\Client($api_key);
		$refreshTokenArray = $client->refreshAccessToken($refresh_token);
		print_r($refreshTokenArray);
		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);
				processItem($user_id, $etsylistingid, $shop_id, $oauth_token, $oauth_token_secret,$access_token,$refresh_token,$api_key);
			}
	}
	else {
		echo "In process item valid token";
		print_r($r->listing_id);
		   if(!isset($r->listing_id)){
			// TODO: Listing id missing
			 return false; 
			 //continue;								
		   }
		  $listing =$r;
		  $etsy_listing_id = $listing->listing_id;
		  //echo "aa".$etsy_listing_id;
		  $title = "";
		  $description = "";
		  $tags = "";
		  $materials = "";
		  $who_made = "";
		  $is_supply = "";
		  $when_made = "";
		  $section_id = "";
		 $section_name = "";
		 $images = array();
		 $category_path = "";
		 $etsy_state = "";
		 $variations = array();

		 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->Section->shop_section_id;
		 }
		 if(isset($listing->Section)){
			$section_name = $listing->Section->title;
		 }

		 $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;
		 }
		
		 if(isset($listing->images)){

			
			
			$pictureLength = count($listing->images);
			for($i = 0; $i < $pictureLength; $i++) {
				if(isset($listing->images[$i]->url_fullxfull)){
					$images[] = $listing->images[$i]->url_fullxfull;
				} else if(isset($listing->images[$i]->url_570xN)){
					$images[] = $listing->images[$i]->url_570xN;
				} else if(isset($listing->images[$i]->url_170x135)){
					$images[] = $listing->images[$i]->url_170x135;
				} else if(isset($listing->images[$i]->url_75x75)){
					$images[] = $listing->images[$i]->url_75x75;
				} else {
					$images[] = array();
				}
			}
		 }
		// print_r("images".json_encode($images));
		 if($listing->has_variations){
			$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)){
							$variations[$i]['price'] = $variation->products[$i]->offerings[0]->price->amount / 100;
						} 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'] = "";
						}
					}
				}
				//print_r($variation);
				
				$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)or die("error in product insert");
				$product_id = $conn->insert_id;
				//print_r("with".$variations);
				foreach($variations as $productVariant) {

					$productVariantQuery= "INSERT INTO product_variants(product_id, sku, option1val, option2val, price, quantity, imageurl, 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'])."', '".mysqli_real_escape_string($conn, $images[0])."', '".$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);
					}
				}
				echo "inserted with variant  process completed";
			}
		 } else {
			echo "without variant";
			
			$price = 0.0;
			$quantity = 0;
			$sku = "";
			if(isset($listing->price)){
				if (isset($listing->price->amount)) {
					$price = $listing->price->amount / 100;
				}
			}
			if(isset($listing->quantity)){
				$quantity = $listing->quantity;
			}
			if (isset($listing->skus[0])) {
				$sku = $listing->skus[0];
			}
			//print_r($listing);
			$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, imageurl, 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)."', '".mysqli_real_escape_string($conn, $images[0])."', '".$user_id."', now(), now())";
			$productVariantResult = mysqli_query($conn, $productVariantQuery);
			echo "inserted without variant  process completed";
		 }
		
	    }
	} catch (OAuthException $e) {
		error_log($e->getMessage());
		error_log(print_r($oauth->getLastResponse(), true));
		error_log(print_r($oauth->getLastResponseInfo(), true));
	}
	return true;
}
function getSectionName($user_id, $access_token, $refresh_token, $shop_id, $section_id)
{
	global $conn, $etsyConfig;
	$section_name = "";
	$sResult = $conn->query("SELECT * FROM `etsy_section` where shop_section_id = '" . $section_id . "'");
	if ($sResult->num_rows > 0) {
		$sRow = $sResult->fetch_assoc();
		$section_name = $sRow["title"];
	} else {
		$api_key = $etsyConfig['api_key'];
		$header = array("Authorization: Bearer " . $access_token, "x-api-key: " . $api_key);
		try {
			$curl = curl_init();
			curl_setopt_array($curl, array(
				CURLOPT_URL => 'https://openapi.etsy.com/v3/application/shops/' . $shop_id . '/sections',
				CURLOPT_HTTPHEADER => $header,
				CURLOPT_SSL_VERIFYPEER => false,
				CURLOPT_RETURNTRANSFER => true
			));
			$r_body = curl_exec($curl);
			curl_close($curl);
			$r = json_decode($r_body, true);
			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, $refreshTokenArray['access_token']) . "',refresh_token = '" . mysqli_real_escape_string($conn, $refreshTokenArray['refresh_token']) . "', updated_at = now() where user_id = " . $user_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 . '/sections',
						CURLOPT_HTTPHEADER => $header,
						CURLOPT_SSL_VERIFYPEER => false,
						CURLOPT_RETURNTRANSFER => true
					));
					$r_body = curl_exec($curl);
					curl_close($curl);
					$r = json_decode($r_body, true);
					insertSections($user_id, $r);
				}
			} else {
				insertSections($user_id, $r);
			}
			$sResult = $conn->query("SELECT * FROM `etsy_section` where shop_section_id = '" . $section_id . "'");
			if ($sResult->num_rows > 0) {
				$sRow = $sResult->fetch_assoc();
				$section_name = $sRow["title"];
			}
		} catch (OAuthException $e) {
			print_r($e);
			error_log($e->getMessage());
			error_log(print_r($oauth->getLastResponse(), true));
			error_log(print_r($oauth->getLastResponseInfo(), true));
		}
	}
	return $section_name;
}
function deleteShopifyProduct($user_id, $token, $shopurl, $product_id){
	echo $token.$shopurl.$product_id;
	$productId = "gid://shopify/Product/" . $product_id;
		$query = <<<GRAPHQL
		mutation {
			productDelete(input: {id: "$productId"}) {
				deletedProductId
				userErrors {
					field
					message
				}
			}
		}
		GRAPHQL;
		$url = "https://$shopurl/admin/api/".GRAPHQL_API_VERSION."/graphql.json";

		$headers = [
			"Content-Type: application/json",
			"X-Shopify-Access-Token: $token",
		];

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['query' => $query]));

		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);

		if ($httpCode !== 200) {
			return false;
		}
		return true;

}

function addlog($message, $type)
{
	global $logfile;
	$txt = date("Y-m-d H:i:s") . " [" . $type . "]: " . $message . "\n";
	fwrite($logfile, $txt);
}
addlog("Execution Finished", "INFO");
fclose($logfile);
?>