<?php
// echo "ddd";

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

$user_id = 1217;

$configResult = $conn->query("select * from etsy_keys where valid = 1 and user_id = 2241");
// echo $configResult;
echo "ddd";
if ($configResult->num_rows > 0) {
    $configRow = $configResult->fetch_assoc();
    $shop_id = $configRow['shop_id'];
    echo $shop_id;
    $access_token = $configRow['access_token'];
    $refresh_token = $configRow['refresh_token'];
    $api_key = $etsyConfig['api_key'];
    //  echo "changedeep14" ;
    //  echo $api_key ;
    //  echo $refresh_token ;
    //  echo  $access_token ;
    //  echo "changedeep17" ;
    $existingSKUs = array();
    $result = $conn->query("select distinct etsylistingid from products where user_id = " . $user_id);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $existingSKUs[] = $row['etsylistingid'];
        }
    }


    // fetchCatalog($user_id, $shop_id, $access_token, $refresh_token, $existingSKUs, $api_key);
//}
}
// print_r($configResult);
// echo "changedeep" ;
// echo $configResult ;



// function fetchCatalog($user_id, $shop_id, $access_token, $refresh_token, $existingSKUs, $api_key)
// {
// 	global $conn;

//     echo"hello";
// 	$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);
//         echo"ssss";
//         print_r($r->error);
// 		//echo $r ;
// 		if(isset($r->error) && $r->error == 'invalid_token') {
//             echo "gffgfggfgh";
// 			$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;
				
// 				fetchCatalog($user_id, $shop_id, $access_token, $refresh_token, $existingSKUs, $api_key);
// 			}
// 		} else {
// 			print_r($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));
// 	}
// }


//







$oauth_url = 'https://api.etsy.com/v3/public/oauth/token';


$post_data = array(
    'grant_type' => 'refresh_token',
    'refresh_token' =>  $refresh_token,
    'client_id' => $api_key,
    'client_secret' => $api_secret,
);

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $oauth_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));

// Execute cURL session and get the response
$response = curl_exec($ch);

// Check for cURL errors
if (curl_errno($ch)) {
    echo 'cURL Error: ' . curl_error($ch);
    // Handle error if needed
}

// Close cURL session
curl_close($ch);

// Process the response
if ($response) {
    $data = json_decode($response, true);

    // Now you can access the new Access Token and other data
    $access_token = $data['access_token'];
     echo "ffffff";
     echo  $access_token;
    echo "kkkk";
    // Save the new Access Token in your database or session for future API requests
    // ...
} else {
    echo 'Error refreshing Access Token';
    // Handle error if needed
}

$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 . '/listings?state=active&limit=100&offset=100',
			CURLOPT_HTTPHEADER => $header,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_RETURNTRANSFER => true
		));
		$r_body = curl_exec($curl);
		curl_close($curl);
		$r = json_decode($r_body);
        echo"ssss";
        print_r($r);

        $c = $r->count;
			$c = $c / 100;
			$c = intval($c);
			$c = $c + 1;
        for ($q = 0; $q <= $c; $q++) {
            $offset = $q * 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&language=de&limit=100&offset=' . $offset,
                CURLOPT_HTTPHEADER => $header,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_RETURNTRANSFER => true
            ));
            $response_body = curl_exec($curl);
            curl_close($curl);
           

           $response = json_decode($response_body);
           foreach ($response->results as $listing) {
            if (!isset($listing->listing_id)) {
                // TODO: Listing id missing
                continue;
            }
            $etsy_listing_id = $listing->listing_id;
            if (in_array($etsy_listing_id, $existingSKUs)) {
                // TODO: Listing id already exists
                continue;
            }
            $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;
            }

            


            echo $title;
$product = array( 
    "product" => array (
    "title" => $title,
    "html_body" => "Excellent!!",
    "vendor" => "ssss",
    "product_type" => "accessories",
    "price" => "2700.00",
    "status" => "draft",
    "tags" => "Emotive, Flash Memory, MP3, Music"
    )
);


$token ="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";
$request ="https://shop10054.myshopify.com/admin/products.json";

$curl =curl_init();
curl_setopt($curl, CURLOPT_URL, $request); 
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, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($product));

$response  = curl_exec($curl);

$res = json_decode($response, true);
print_r($res); 

        }
    }
        
?>