<?php
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");

use OAuth\Client;

    $user_id = 561;
    $missingStr = "";
    $userResult = $conn->query("select * from users where id = '".$user_id."' and installationstatus = 1");
		if($userResult->num_rows < 1){
			return false;
		}
		$userRow = $userResult->fetch_assoc();
		echo $userRow;
        $shopurl = $userRow['shopurl'];
		$shopifytoken = $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();
        $shop_id = $configRow['shop_id'];
        $access_token = $configRow['access_token'];
        $refresh_token = $configRow['refresh_token'];
        $api_key = $etsyConfig['api_key'];
	
	$existingSKUs = array();
	$result = $conn->query("SELECT *  FROM `products` where user_id = 561 and status='imported'  and product_id not in (select product_id from product_images where user_id = 561)");
	if ($result->num_rows > 0) {
		while($row = $result->fetch_assoc()) {	
			$etsy_listing_id  = $row['etsylistingid'];
            $product_id = $row['product_id'];
            $shopifyproductid = $row['shopifyproductid'];
            $updateimage = processitem($user_id, $shop_id, $access_token, $refresh_token,$api_key,$etsy_listing_id,$shopifyproductid,$shopurl,$shopifytoken,$product_id);  
            print_r($updateimage);
            
		}
        echo "done";
	}
}
function  processitem($user_id, $shop_id, $access_token, $refresh_token,$api_key,$etsy_listing_id,$shopifyproductid,$shopurl,$shopifytoken,$product_id){
    global $conn;
  
	$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/' . $etsy_listing_id . '/images',
							CURLOPT_HTTPHEADER => $header,
							CURLOPT_SSL_VERIFYPEER => false,
							CURLOPT_RETURNTRANSFER => true
						));
						$image_body = curl_exec($curl);
						curl_close($curl);
						$r = json_decode($image_body);
                        
                     
                        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);
                                processitem($user_id, $shop_id, $access_token, $refresh_token,$api_key,$etsy_listing_id,$shopifyproductid,$shopurl,$shopifytoken,$product_id);
                            }
                        } else {
                           
                            if(isset($r->results)){
                                $images =array();
                                $pictureLength = count($imgResponse->results);
								for ($i = 0; $i < $pictureLength; $i++) {
									if (isset($imgResponse->results[$i]->url_fullxfull)) {
										$images[] = $imgResponse->results[$i]->url_fullxfull;
									} else if (isset($imgResponse->results[$i]->url_570xN)) {
										$images[] = $imgResponse->results[$i]->url_570xN;
									} else if (isset($imgResponse->results[$i]->url_170x135)) {
										$images[] = $imgResponse->results[$i]->url_170x135;
									} else if (isset($imgResponse->results[$i]->url_75x75)) {
										$images[] = $imgResponse->results[$i]->url_75x75;
									} else {
										$images[] = array();
									}
								}
                                
                                $tempArr = array();
                                foreach ($images as $imgurl) {
                                    $productImageQuery =$conn->query("INSERT INTO product_images(product_id, imgurl, user_id, created_at, updated_at) VALUES('" . mysqli_real_escape_string($conn, $product_id) . "', '" . mysqli_real_escape_string($conn, $imgurl) . "', '" . $user_id . "', now(), now())");
                                    
                                    echo "inserted";
                                    $tempArr[] = trim($imgurl);
                                }	
                                $tempArr = array_unique($tempArr);
                                $position = 1;
                                foreach($tempArr as $imgurl){
                                    $imageArr[] = array("src" => trim($imgurl), "position" => $position++);
                                }
                              
                                foreach($imgdata as $temp){
                                    $data = array("image" => $temp);				
                                    addShopifyProductImage($shopifytoken, $shopurl, $shopifyproductid, $data);
                                    echo "update"
                                }
                            }   
                        }
                        return null;
}
function addShopifyProductImage($token, $shopurl, $product_id, $data){
    $url = "https://".$shopurl."/admin/api/2023-04/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; 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, "POST");
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec ($curl);
    curl_close ($curl);
    $response_arr = explode("\n",$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]), "201")) || (strstr(($response_arr[1]), "201")) || (strstr(($response_arr[2]), "201")) ){
        $product_json = end($response_arr);
        $product_arr = json_decode($product_json, true);
        $product_arr = $product_arr["product"];
        return $product_arr;
    } else {
        print_r($data);
        print_r($response_arr);
        //addlog("Error adding product with SKU - ".$product["product"]["variants"]["sku"].", Err Details: ".serialize($response_arr), "ERROR");
    }
    return null;
}
// function updateShopifyProduct($token, $shopurl, $product_id, $data){	
//     $url = "https://".$shopurl."/admin/api/".SHOPIFY_API_VERSION."/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);		
//     $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")) ){
//         addlog("Product updated with ID - ".$product_id, "SUCCESS");
//         return 1;
//     } else {
//         echo $product_id."<br />";
//         addlog("Error updating product with ID - ".$product_id.", Err Details: ".serialize($response_arr), "ERROR");			
//         return null;
//     }
// }