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

require_once("includes/etsyv3/vendor/autoload.php");
use OAuth\Client;

global $etsyConfig;
$user_id=563;
$user =$conn->query("select * from users where id= 563");
$row = $user->fetch_assoc();
$shop_url=$row['shopurl'];
$token=$row['token'];

$result =$conn->query("select * from etsy_keys where valid =1 and user_id=563");
if ($result ->num_rows > 0) {
    $Row = $result->fetch_assoc();
    $shop_id =   $Row['shop_id'];
	
    $access_token =   $Row['access_token'];
    $refresh_token =  $Row['refresh_token'];
    $api_key =  $etsyConfig['api_key'];

	
	fetchList(1217, $shop_id, $access_token, $refresh_token,$api_key);
	// updateshopify($user_id,$shop_url,$token,$data, $shopifyvariantid,$shopifyproductid );

	}
   // }

   function fetchList($user_id, $shop_id, $access_token, $refresh_token, $api_key)
   {
	   global $conn;
	   $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 . '/listings?state=active&limit=100&offset=0',
			   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') {
			   $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 );
				   fetchList($user_id, $shop_id, $access_token, $refresh_token,  $api_key);
			   }
		   } else {
			insertlist($user_id, $shop_id, $access_token, $refresh_token,  $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 insertlist($user_id, $shop_id, $access_token, $refresh_token, $api_key, $r){
	global $conn;
	$header = array("Authorization: Bearer " . $access_token, "x-api-key: " . $api_key);
   if ($r->count > 0){
	$c = $r->count/100 ;
	$c= intval($c);
	$c= $c+1;
	for ($i=0; $i<=$c; $i++){
     $offset = $i * 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;
				$res= json_decode($response_body);
				foreach( $res->results  as $listing){
 
				    $id = $listing->listing_id;

					if ($listing->has_variations == 1) {

						//echo $id;
						$curl = curl_init();
							curl_setopt_array($curl, array(
								CURLOPT_URL => 'https://openapi.etsy.com/v3/application/listings/' .  $id  . '/inventory',
								CURLOPT_HTTPHEADER => $header,
								CURLOPT_SSL_VERIFYPEER => false,
								CURLOPT_RETURNTRANSFER => true
							));
							$result = curl_exec($curl);
							curl_close($curl);
							$variation = json_decode($result );
							
							if ($variation != "") {
								$varLength = count($variation->products);
								for ($i = 0; $i < $varLength; $i++) {
								$price=	$variation->products[$i]->offerings[0]->price->amount/100;
							//	print_r( $price);
								$quantity= $variation->products[$i]->offerings[0]->quantity;

								$data=array(
									"price"=>$price,
									"quantity"=>$quantity

								);
								$result12 =$conn->query("select * from products where etsylistingid = '".$id."' and user_id=563");

								while($row = $result12->fetch_assoc()){
									$product_id= $row['product_id'];
							$result=$conn->query("update product_variants set price= '".$price."' and quantity= '".$quantity."' where  user_id=1217 and product_id= '".$product_id."'");
								echo $result;	
								}

								}
							}
							
					}
					
					else{

						$res = $r;

						//print_r( $res);
					$price= $listing->price->amount/100;
					$quantity=$listing->quantity;
					$data=array(
						"price"=>$price,
						"quantity"=>$quantity

					);
					
			  $result12 =$conn->query("select * from products where etsylistingid = '".$id."' and user_id=563 ");
			  while($row = $result12->fetch_assoc()){
				$product_id= $row['product_id'];
				//$conn->query("update product_variants set price= '".$price."' and quantity= '".$quantity."' where  user_id=1217 and product_id= '".$product_id."'");
				
			}
			
					}

						}

 			 				 }				

   									}			

											}


//     function updateshopify($user_id,$shop_url,$token,$data, $shopifyvariantid,$shopifyproductid ){
// 	$requestURL="https://$shop_url/admin/products/ $shopifyproductid.json";
// 	$curl = curl_init();
//     	curl_setopt($curl, CURLOPT_URL,$requestURL);
//     	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, false);
//     	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);

//    }
?>