<?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=1217;
$user =$conn->query("select * from users where id= 1217");
$row = $user->fetch_assoc();
$shop_url=$row['shopurl'];
$token=$row['token'];

$result =$conn->query("select * from etsy_keys where valid =1 and user_id=1217");
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'];

	$result = $conn->query("select * from product_variants  where user_id = 1217 and product_id in (select product_id from products where user_id = 1217 and etsy_state='active')");
	if ($result->num_rows > 0) {
		while($variantRow = $result->fetch_assoc()) {	
			//$etsyitemid  = $variantRow['etsylistingid'];
            ///fetchList($user_id, $shop_id, $access_token, $refresh_token, $api_key,$etsyitemid);
				//exit(0);
                $variant_id = $variantRow['shopifyvariantid'];
                $data = array(
                    "variant"=>array(
                        "id" => $variant_id,		
                        "weight" => $variantRow['weight'],
                         "weight_unit" =>$variantRow['weight_unit']
                    )
                );	
                updateShopifyVariant($token, $shop_url, $variant_id, $data);
                //exit;
		}
	}
}
    function fetchList($user_id, $shop_id, $access_token, $refresh_token, $api_key,$etsyitemid)
    {
        global $conn;
        $header = array("Authorization: Bearer " . $access_token, "x-api-key: " . $api_key);
        echo 'https://openapi.etsy.com/v3/application/listings/'.$etsyitemid.'';
        try {
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://openapi.etsy.com/v3/application/listings/'.$etsyitemid.'',
                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 {
                
                print_r($r);
                $weight_unit='';
                $weight ='0';
                $etsy_listing_id =$r->listing_id;
                if (isset($r->item_weight_unit)) {
                    $weight_unit =$r->item_weight_unit;
                }
                if (isset($r->item_weight)) {
                    if($weight_unit == 'oz' &&  $r->item_weight >= 16){
                        $weight  =$r->item_weight * 0.0625;
                        $weight_unit = 'lbs';
                    }
                    else{
                        $weight  =$r->item_weight;
                    }
                }
               
                $state =$r->state;
               //}

          $conn->query("update products set  etsy_state ='".mysqli_real_escape_string($conn, $state)."' where etsylistingid='".mysqli_real_escape_string($conn, $etsy_listing_id)."' and user_id = ".$user_id)or die("error in queries".$conn->error);
       
          $conn->query("update product_variants set  weight ='".mysqli_real_escape_string($conn,$weight)."',weight_unit ='".mysqli_real_escape_string($conn,$weight_unit)."' where  user_id = ".$user_id." and product_id in (select product_id from products where user_id = ".$user_id." and etsylistingid='".mysqli_real_escape_string($conn, $etsy_listing_id)."')")or die("error in qudksdfdkskjeries".$conn->error);;

             }
             
                     }
                 
         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 updateShopifyVariant($token, $shopurl, $variant_id, $data){
        global $conn;
        $url = "https://".$shopurl."/admin/api/2023-10/variants/".$variant_id.".json";
        
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        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, 1);
        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);
        curl_close ($curl);
        echo $response;
       sleep(1);
       return $response;
    }

?>
