<?php
echo "00";
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");
 echo "1";
 use OAuth\Client;


 $api_key = $etsyConfig['api_key'];
 $api_secret = $etsyConfig['api_secret'];    
 $user_id = 561;
 $etsyResult = $conn->query("SELECT * FROM `etsy_keys` where user_id = 561");
 if($etsyResult->num_rows == 0) {
	return "No valid Etsy keys found!";
 }
 $etsyRow = $etsyResult->fetch_assoc();     
  $oauth_token = $etsyRow['oauth_token'];
 $oauth_token_secret = $etsyRow['oauth_token_secret'];
    $access_token = $etsyRow['access_token'];
    $refresh_token = $etsyRow['refresh_token'];
    $shoid = $etsyRow['shop_id'];
    echo $refresh_token;
	$listing_id = 1130521901;
	$api_key = $etsyConfig['api_key'];
    $url = "https://openapi.etsy.com/v3/application/shops/{$shoid}/shipping-profiles";
    
    // Set the headers
    $headers = array(
        'Authorization: Bearer ' . $access_token,
        "x-api-key: " . $api_key,
        'Content-Type: application/json'
    );
    $result = getres($url,$json_data,$headers);
    $r = json_decode($result);
    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);
            $url = "https://openapi.etsy.com/v3/application/shops/{$shoid}/shipping-profiles";
    
            // Set the headers
            $headers = array(
                'Authorization: Bearer ' . $access_token,
                "x-api-key: " . $api_key,
                'Content-Type: application/json'
            );
            $result = getres($url,$json_data,$headers);
           $r = json_decode($result);
        }
    } 

    print_r($r);
    // Initialize cURL
    function getres($url,$json_data,$headers){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    //curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    // Execute the request
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    // Close cURL
    curl_close($ch);
    
    // Check the response
    if ($httpCode == 200) {
        echo 'Inventory updated successfully.';
    } else {
        echo 'Failed to update inventory. Response: ' . $response;
    }
  return $response;    
}


?>