<?php

set_time_limit(0);
ini_set('memory_limit','1024M');
require_once("includes/config.php");



	// Check connection
	
	
    $shopurl="";
    $token="";
    $user_id =2825;
    $userresult = $conn->query("select * from users where installationstatus = 1 and id = ".$user_id);
    if ($userresult->num_rows > 0) {
        while($userrow = $userresult->fetch_assoc()) {
            $shopurl = $userrow['shopurl'];
            $token = $userrow['token'];		


        }
    
    }
    $configResult = $conn->query("select * from etsy_keys where valid = 1 and user_id = ".$user_id);
	if($configResult->num_rows > 0){

        $configRow = $configResult->fetch_assoc();
        $shopId = $configRow['shop_id'];
        $apiKey = $etsyConfig['api_key'];

   $product_image  = $conn->query("select * from products  where status='imported'  and shopifyproductid !=''    and user_id = ".$user_id." limit 1");
    if ($product_image->num_rows > 0) { 

        while($imageRow =  $product_image->fetch_assoc()){

            $product_id =$imageRow['shopifyproductid'];
            $listing_id=$imageRow['etsylistingid'];


            updateShopifyProduct($token, $shopurl,  $product_id);



$variationImages = getVariationImage($shopId,$listing_id,$apiKey);
// $product_id = '10141993926987';


$images = image($listing_id,$apiKey);


// print_r($images);


foreach ($images as $i) {
    $addedImage = addProductImage($product_id, $i['url_fullxfull'],$token, $shopurl,$apiKey);
   
        foreach($variationImages as $key =>$value){
            if($value == $i['listing_image_id']){
                $variationImages[$key]=$addedImage;
            }
        }
}
print_r($variationImages);
$variations = getVariants($product_id,$token,$shopurl,$apiKey);


print_r($variations);


    foreach ($variations as $variation) {
       
        $imageId = $variationImages[$variation['option1']];
        print_r($imageId);
       updateVariant($product_id, $imageId, $variation['id'], $token, $shopurl,$apiKey,$user_id);
    }

 

        }
      }

    }



function getVariationImage($shopId,$listing_id,$apiKey){





$ch = curl_init();


curl_setopt($ch, CURLOPT_URL, "https://openapi.etsy.com/v3/application/shops/$shopId/listings/$listing_id/variation-images");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "x-api-key: $apiKey"
]);


$response = curl_exec($ch);


if(curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
    exit;
}


curl_close($ch);


$responseData = json_decode($response, true);


echo "<pre>";
print_r($responseData);
echo "</pre>";
$convertedArray = [];
foreach ($responseData['results'] as $item) {
    $convertedArray[$item['value']] = $item['image_id'];
}


echo "<pre>";
print_r($convertedArray);
echo "</pre>";
return $convertedArray;
}

function updateVariant($product_id, $image_id, $variantId, $token, $shopurl, $apiKey,  $user_id) {
    global $conn;
    $data = [
        'variant' => [
            'image_id' => $image_id
        ]
    ];

    $json_data = json_encode($data);

    $api_url = "https://$shopurl/admin/api/2023-04/variants/$variantId.json";

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $api_url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'X-Shopify-Access-Token: ' . $token,
        'Content-Type: application/json'
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);

    $response = curl_exec($curl);
    sleep(1);
    curl_close($curl);

    $data = json_decode($response, true);

    if (isset($data['errors'])) {
        echo "Error: " . print_r($data['errors'], true) . "\n";
    } else {
        echo "Updated Product Variant:\n";
        print_r($data['variant']);
        
        
        $updateQuery = "UPDATE products SET errdetails='imgdone' WHERE user_id = $user_id AND shopifyproductid = $product_id";
        if ($conn->query($updateQuery) === TRUE) {
            echo "Record updated successfully\n";
        } else {
            echo "Error updating record: " . $conn->error . "\n";
        }
    }
}


// function updateVariant($product_id, $image_id, $variantId,$token, $shopurl,$apiKey  ) {
// //     = "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";
// //    = "edadca-bd.myshopify.com";

//     $data = [
//         'variant' => [
//             'image_id' => $image_id
//         ]
//     ];

//     $json_data = json_encode($data);

//     $api_url = "https://$shopurl/admin/api/2023-04/variants/$variantId.json";

//     $curl = curl_init();
//     curl_setopt($curl, CURLOPT_URL, $api_url);
//     curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//         'X-Shopify-Access-Token: ' . $token,
//         'Content-Type: application/json'
//     ));
//     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//     curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
//     curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);

//     $response = curl_exec($curl);
//     curl_close($curl);

//     $data = json_decode($response, true);

//     if (isset($data['errors'])) {
//         echo "Error: " . print_r($data['errors'], true) . "\n";
//     } else {
//         echo "Updated Product Variant:\n";
//         print_r($data['variant']);
//     }
// }

function getVariants($product_id,$token,$shopurl,$apiKey) {
    //  = "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";
    //  = "edadca-bd.myshopify.com";
    $url = "https://$shopurl/admin/api/2024-07/products/$product_id/variants.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_CUSTOMREQUEST, "GET");
    $response = curl_exec($curl);
    curl_close($curl);

    $data = json_decode($response, true);

    return $data['variants'];
}

function image($listing_id,$apiKey) {
    
    $apiUrl = "https://openapi.etsy.com/v3/application/listings/$listing_id/images";
//    $apiKey = '9vnyhcjjd9p6q4m239g9brio';
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $apiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => array(
            "x-api-key: $apiKey",
            "Content-Type: application/json; charset=utf-8"
        )
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    $data = json_decode($response, true);
    return $data['results'];
}


function addProductImage($product_id, $image_url,$token, $shopUrl,$apiKey ) {
//      = "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";
//    = "edadca-bd.myshopify.com";
    $imageData = [
        'image' => [
            'src' => $image_url
        ]
    ];

    $url = "https://$shopUrl/admin/api/2024-07/products/$product_id/images.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'
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($imageData));

    $response = curl_exec($curl);
    if ($response === false) {
        $error = curl_error($curl);
        curl_close($curl);
        die("cURL Error: $error");
    }

    $newImage = json_decode($response, true);
    curl_close($curl);

    $id = $newImage['image'];
    return $id['id'];
}



function updateShopifyProduct($token, $shopUrl, $product_id){	

    $data = array("product" => array("id" => $product_id, "images" => array()));
    	  
     $url = "https://".$shopUrl."/admin/api/2024-07/products/".$product_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);	
     echo $response;
     curl_close ($curl);	
     $response_arr=explode("\n",$response);		

     print_r(  $response);
     $climit = -1;
     foreach($response_arr as $obj){
         if (strpos($obj, 'X-Shopify-Shop-Api-Call-Limit') !== false) {
             $tempArr = explode(":", $obj);
             $climit = substr(trim(end($tempArr)), 0, -3);
         }
     }	
     if(intval($climit) > 35){
         sleep(5);
     }
     if( (strstr(($response_arr[0]), "200")) || (strstr(($response_arr[1]), "200")) || (strstr(($response_arr[2]), "200")) ){
         
         return 1;
     } else {
         echo $product_id."<br />";
        		
         return null;
     }
 }
?>