<?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;




	
		$user_id = 561;
		echo "test  1   ";
		$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'];
			echo "test -- 2   ";
			$access_token = $configRow['access_token'];
			$refresh_token = $configRow['refresh_token'];
			$api_key = $etsyConfig['api_key'];

				
			fetchCatalog($user_id, $shop_id, $access_token, $refresh_token, $existingSKUs, $api_key);

			
		} 
		
		
	



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

//https://openapi.etsy.com/v3/application/listings/1146374733
    //https://openapi.etsy.com/v3/application/listings/{listing_id}/videos
	try {
		$curl = curl_init();
		curl_setopt_array($curl, array(
			
			CURLOPT_URL => 'https://openapi.etsy.com/v3/application/listings/1744582658/videos',
			CURLOPT_HTTPHEADER => $header,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_RETURNTRANSFER => true
		));
		$r_body = curl_exec($curl);
		curl_close($curl);
		$r = json_decode($r_body);
		

        echo "test          kjgbbbbbbbbbbbbbbbbbbbbb       1   ";
		if (isset($r->error) && $r->error == 'invalid_token') {
			print_r($api_key);
			
			$client = new Etsy\OAuth\Client($api_key);
			print_r($client );
			
			$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 {
			print_r($r);
		
			//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));
	}
}




?>


