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


global $conn, $etsyConfig;

$tokenExp = "";
$user_id =561;

use OAuth\Client;

$sResult = $conn->query("SELECT * FROM etsy_keys WHERE user_id = " . 
$user_id);
$etsyRow = $sResult->fetch_assoc();

$access_token = $etsyRow['access_token'];
$api_key = $etsyConfig['api_key'];
$refresh_token = $etsyRow['refresh_token'];
$shop_id = $etsyRow['shop_id']; // This seems like a typo, perhaps you meant $etsyRow['shop_id']

$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=1&offset=0',
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_RETURNTRANSFER => true
    ));
    $r_body = curl_exec($curl);
    $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    $response = json_decode($r_body);
        $tokenExp = $response->error;
       echo $response->error. "upside";
    if (isset($response->error) && $response->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;
            $header = array("Authorization: Bearer " . $access_token, "x-api-key: " . $api_key);
            // Update tokens in your database

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://openapi.etsy.com/v3/application/shops/' . $shop_id . '/listings?limit=1&offset=0',
                CURLOPT_HTTPHEADER => $header,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_RETURNTRANSFER => true
            ));
            $r_body = curl_exec($curl);
            $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            curl_close($curl);

            $response = json_decode($r_body);


            print_r($response );
            // echo $response->error. "inside";
            // die();
            $tokenExp =$response->error?$response->error:" ";










        }
    }
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}







echo ">>>>>> fianl".$tokenExp; 
if($tokenExp == 'invalid_token'){



    // sendEmail($user_id);
    
}


function sendEmail($user_id)
{
	global $conn;
	$name =" test 123";

    $to = "mewaradeepanshu@gmail.com";
				$subject = "[BigCommerce App] Etsy Importer - Setup completed";
				$body = '<p>Dear ' . $name . ',</p>
						
						<p>invalid token</p>';
				// sendGridEmail($to, $subject, $body);
			
		
}

// function sendGridEmail($to, $subject, $body)
// {
// 	require_once("includes/sendgrid/sendgrid-php.php");
// 	$email = new \SendGrid\Mail\Mail();
// 	$email->setFrom("shopifyapps@infoshore.biz", "Rohit from InfoshoreApps");
// 	$email->setSubject($subject);
// 	$email->addTo($to);
// 	// $email->addBcc("khariwal.rohit@gmail.com");
// 	$email->addContent(
// 		"text/html",
// 		$body
// 	);
// 	$sendgrid = new \SendGrid('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');


// 	try {
// 		$sendgrid->send($email);
// 		return true;
// 	} catch (Exception $e) {		
// 		return false;
// 	}
// }

?>

?>