<?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;

$queueArr = array();
$existingSKUs = array();


$user_id =563;
$configResult = $conn->query("select * from etsy_keys where valid = 1 and  user_id = " . $user_id);



if ($configResult->num_rows > 0) {

    // echo "test valid";
    $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();


    fetchCatalog($user_id, $shop_id, $access_token, $refresh_token, $existingSKUs, $api_key,$shopurl,$token);
}

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

    // echo $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=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);
        // print_r($r);
        // die();
        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);
                fetchCatalog($user_id, $shop_id, $access_token, $refresh_token, $existingSKUs, $api_key);
            }
        } else {


            getallProducts($user_id, $shop_id, $access_token, $refresh_token, $existingSKUs, $api_key, $r,$shopurl,$token);
        }
    } catch (OAuthException $e) {
        print_r($e);
        // error_log($e->getMessage());
        // error_log(print_r($oauth->getLastResponse(), true));
        // error_log(print_r($oauth->getLastResponseInfo(), true));
    }
}

// print_r($existingSKUs);
// die();

function  getallProducts($user_id, $shop_id, $access_token, $refresh_token, $existingSKUs, $api_key, $r,$shopurl,$token)
{
    $existingItems = array();
    $etsy_listing_array = array();

    global $conn;
    $header = array("Authorization: Bearer " . $access_token, "x-api-key: " . $api_key);
    try {
        if ($r->count > 0) {
            $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&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);

                if ($response->results != '') {
                    foreach ($response->results as $listing) {
                        if (!isset($listing->listing_id)) {
                            // TODO: Listing id missing
                            continue;
                        }

                        $etsy_listing_id = $listing->listing_id;
                        $has_variations = $listing->has_variations;
                        // echo " ";
                        // echo $has_variations;
                        // echo " ";
                        $etsy_listing_array[] = array("etsylistingid" => $etsy_listing_id, "has_variations" => $has_variations);


                        $variations = array();


                        //todo --make call to etsy and fetch all varaints and add them in an array

                        // $etsy_listing_id = array();
                        // $queueResult = $conn->query("select *  from products where etsylistingid = $etsy_listing_id");
                    }
                }
            }
        }
    } catch (OAuthException $e) {
        // print_r($e);
        // error_log($e->getMessage());
        // error_log(print_r($oauth->getLastResponse(), true));
        // error_log(print_r($oauth->getLastResponseInfo(), true));
    }

    missMatchData($etsy_listing_array, $user_id, $access_token, $api_key, $refresh_token,$shopurl,$token);
}


function  missMatchData($etsy_listing_array, $user_id, $access_token, $api_key, $refresh_token,$shopurl,$token)
{

    global $conn;

    $existingItems = array();
    $result = $conn->query("select * from product_variants where user_id = " . $user_id);


    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $product_id = $row['product_id'];
            $variant_id = $row['id'];
            $option1val = $row['option1val'];
            $option2val = $row['option2val'];
            $option3val = $row['option3val'];


            $price = $row['price'];
            $quantity = $row['quantity'];

            $productResult = $conn->query("select * from products where product_id = " . $product_id . " and user_id = " . $user_id);
            if ($productResult->num_rows < 1) {
                continue;
            }
            $productRow = $productResult->fetch_assoc();
            $etsylistingid = $productRow['etsylistingid'];
            $option1name = $productRow['option1name'];
            $option2name = $productRow['option2name'];
            $option3name = $productRow['option3name'];

            $temp = array("etsylistingid" => $etsylistingid, "price" => $price, "quantity" => $quantity, "variant_id" => $variant_id);
            if (strlen($option1name) > 0) {
                $temp[$option1name] = $option1val;
            }
            if (strlen($option2name) > 0) {
                $temp[$option2name] = $option2val;
            }
            if (strlen($option3name) > 0) {
                $temp[$option3name] = $option3val;
            }
            $existingItems[$etsylistingid][] = $temp;
        }
    }

    //  print_r($existingItems);

    //  die(0);
    $missmatchproduct = array();

    // ------------------------------------- inventry data 
    foreach ($etsy_listing_array as $etsylistingidw) {


        $etsylistingid = $etsylistingidw['etsylistingid'];
        $has_variations = $etsylistingidw['has_variations'];
         $existingItemData12 = $existingItems[$etsylistingid];

         if($existingItemData12){
           
          // $existingItemData = $existingItems[$etsylistingid];
      
        try {
            $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/listings/' . $etsylistingid . '/inventory',
                CURLOPT_HTTPHEADER => $header,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_RETURNTRANSFER => true
            ));
            $response_body1 = curl_exec($curl);
            curl_close($curl);
            $inventoryData = json_decode($response_body1);

            if (isset($inventoryData->error) && $inventoryData->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);
                    $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/listings/' . $etsylistingid . '/inventory',
                        CURLOPT_HTTPHEADER => $header,
                        CURLOPT_SSL_VERIFYPEER => false,
                        CURLOPT_RETURNTRANSFER => true
                    ));
                    $response_body1 = curl_exec($curl);
                    curl_close($curl);
                    $inventoryData = json_decode($response_body1);


                }
            }

            // echo " dfghjk ";
            // print_r($inventoryData);
            // die();

        } catch (OAuthException $e) {
            print_r($e);
            error_log($e->getMessage());
            error_log(print_r($oauth->getLastResponse(), true));
            error_log(print_r($oauth->getLastResponseInfo(), true));
        }

        
   
        

        if ($has_variations != 1) {
           
            $price = 0.0;
            $quantity = 0;
            $variant_id = $existingItemData12[0]['variant_id'];
            $quantityDB  =    $existingItemData12[0]['quantity'] ;
            // print_r($existingItemData12);
            // print_r($existingItemData12[0]['price']);
            // die();

            if (isset($inventoryData->products[0]->offerings[0]->price->amount)) {
                $price = $inventoryData->products[0]->offerings[0]->price->amount / 100;
                $price = str_replace(",", "", $price);
                // echo "sdeep" ;
                // echo $price ;
            }


            if (isset($inventoryData->products[0]->offerings[0]->quantity)) {
                $quantity = $inventoryData->products[0]->offerings[0]->quantity;
            }

            if ( $price != $existingItemData12[0]['price']) {
                echo " price mismatch ";
                 echo " price1 " . $price . " etsy-- " . $existingItemData12[0]['price'] . " /n ";
                $priceflag = 1;
            }
            if ($quantity != $existingItemData12[0]['quantity']) {
                echo " quantity mismatch ";

                echo " quantity " . $quantity . " etsy-- " . $existingItemData12[0]['quantity'] . " /n ";

                $quantityflag = 1;
            }
            $missmatchproduct[$etsylistingid ][] = array("quantityflag" => $quantityflag,  "priceflag" => $priceflag);

            // if($priceflag == 1 && $quantityflag == 1){
            //     $conn->query("update product_variants set price = '".mysqli_real_escape_string($conn, $price)."', quantity = '".mysqli_real_escape_string($conn, $quantity)."', priceflag = 1, quantityflag = 1 where id = ".$existingItemData12[0]['variant_id']." and user_id = ".$user_id);
            // } else if($priceflag == 1){
            //     $conn->query("update product_variants set price = '".mysqli_real_escape_string($conn, $price)."', priceflag = 1 where id = ".$existingItemData12[0]['variant_id']." and user_id = ".$user_id);
            // } else if($quantityflag == 1){
            //     $conn->query("update product_variants set quantity = '".mysqli_real_escape_string($conn, $quantity)."', quantityflag = 1 where id = ".$existingItemData12[0]['variant_id']." and user_id = ".$user_id);
            // }
            // if($priceflag == 1 || $quantityflag == 1){
            // updateInventoryAndPrice($priceflag ,$quantityflag , $quantity, $variant_id , $user_id ,$quantity ,$price , $shopurl,$token );
            // }
        } else {

          

            if (isset($inventoryData->products)) {
                $varLength = count($inventoryData->products);
                for ($i = 0; $i < $varLength; $i++) {
                    $variations[$i] = array();

                    if (isset($inventoryData->products[$i]->property_values[0]->property_name) && isset($inventoryData->products[$i]->property_values[0]->values[0])) {
                        $variations[$i][$inventoryData->products[$i]->property_values[0]->property_name] = $inventoryData->products[$i]->property_values[0]->values[0];
                    }

                    if (isset($inventoryData->products[$i]->property_values[1]->property_name) && isset($inventoryData->products[$i]->property_values[1]->values[0])) {
                        $variations[$i][$inventoryData->products[$i]->property_values[1]->property_name] = $inventoryData->products[$i]->property_values[1]->values[0];
                    }

                    if (isset($inventoryData->products[$i]->offerings[0]->price->amount)) {
                        $variations[$i]['price'] = $inventoryData->products[$i]->offerings[0]->price->amount / 100;
                        $variations[$i]['price'] = str_replace(",", "", $variations[$i]['price']);
                    } else {
                        $variations[$i]['price'] = 0;
                    }

                    if (isset($inventoryData->products[$i]->offerings[0]->quantity)) {
                        $variations[$i]['quantity'] = $inventoryData->products[$i]->offerings[0]->quantity;
                    } else {
                        $variations[$i]['quantity'] = 0;
                    }
                }
            }
            // print_r($variations);
            // die();
            
               

            
        


           

          
            //  print_r($variations);
// echo "mult variant";
            foreach($variations as $variation){
               
                foreach($existingItemData12 as $pk => $existingVariation){

                   
                
                    $ismatched = true;
                    foreach($existingVariation as $k => $v){
                        if( $k == 'price' || $k == 'etsylistingid' || $k == 'quantity' || $k == 'variant_id'){
                            continue;
                        }
                    //	echo $variation[$k].'--'.$v.'--'.($variation[$k] != $v)."<br /><br />";
                        if($variation[$k] != $v){
                            $ismatched = false;
                            break;
                        }
                    }
                    if(!$ismatched){
                        continue;
                    }
                   
                    $priceflag = 0;
                    $quantityflag = 0;

                    
//          echo " variation['price'] ";
// echo $variation['price'];

//          echo "<<<<<";
//          echo ">>>>>";
//          echo $existingVariation['price'];
         

// print_r($variation['price'] ) ;

// echo " tdrfghj ";

// print_r($existingVariation['price']);

// die();
                

                    if( $variation['price'] != $existingVariation['price']){

                    //     echo " price mismatch ";
                        echo " price1 " . $price . " etsy-- " . $existingVariation['price'] . " /n ";
                        $priceflag = 1;      

                    }
                    if($variation['quantity'] != $existingVariation['quantity']){ 
                        $quantityflag = 1;
                        echo " quantity " . $variation['quantity'] . " quantityetsy-- " . $existingVariation['quantity'] . " /n ";
                    }	
                    
                    // if($priceflag == 1 && $quantityflag == 1){
                    //     $conn->query("update product_variants set price = '".mysqli_real_escape_string($conn, $variation['price'])."', quantity = '".mysqli_real_escape_string($conn, $variation['quantity'])."', priceflag = 1, quantityflag = 1 where id = '".$existingVariation['variant_id']."' and user_id = ".$user_id);
                    // } else if($priceflag == 1){
                    //     $conn->query("update product_variants set price = '".mysqli_real_escape_string($conn, $variation['price'])."', priceflag = 1 where id = '".$existingVariation['variant_id']."' and user_id = ".$user_id);
                    // } else if($quantityflag == 1){
                    //     $conn->query("update product_variants set quantity = '".mysqli_real_escape_string($conn, $variation['quantity'])."', quantityflag = 1 where id = '".$existingVariation['variant_id']."' and user_id = ".$user_id);
                    // }

                    // if($priceflag == 1 || $quantityflag == 1){
                    //     updateInventoryAndPrice($priceflag ,$quantityflag ,  $variant_id , $user_id ,$quantity ,$price ,$shopurl,$token  );
                    //     }


                    break;							
                }
            }
        }
    }else{
    // data not listing

        }
    }
}

print_r($missmatchproduct);



outputCSV($missmatchproduct);

function outputCSV($missmatchproduct) {

    $output = fopen("missmatchproduct.csv", "w");

    foreach ($missmatchproduct as $row) {
        fputcsv($output, $row);
    }

    fclose($output);
}
// function getshopifyproduct($user_id, $token, $shopurl, $shopifyproductid)
// {

//     $apiurl = "https://" . $shopurl . "/admin/api/2023-10/products/" . $shopifyproductid . ".json";
//     $session = curl_init();
//     curl_setopt($session, CURLOPT_URL, $apiurl);
//     curl_setopt($session, CURLOPT_HTTPGET, 1);
//     curl_setopt($session, CURLOPT_HEADER, false);
//     curl_setopt($session, CURLOPT_HTTPHEADER, array('X-Shopify-Access-Token:' . $token));
//     curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
//     curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
//     $response = curl_exec($session);
//     // echo $response;
//     if ($response) {
//         $resObj = json_decode($response, true);
//         // print_r($resObj);

//     }

//     return "";
// }

// function updateInventoryAndPrice($priceflag ,$quantityflag ,  $variant_id , $user_id ,$quantity ,$price ,$shopurl,$token  ){

//     $data = array();
//     if ($priceflag == 1 && $quantityflag == 1) {
	// 	$data = array(
	// 		"variant" => array(
	// 			"id" => $variantid,
	// 			"price" => number_format($price, 2, '.', ''),
	// 			"inventory_quantity" => $qty
	// 		)
	// 	);
	// } elseif ($quantityflag == 1 && $priceflag != 1) {
	// 	$data = array(
	// 		"variant" => array(
	// 			"id" => $variantid,
	// 			"inventory_quantity" => $qty
	// 		)
	// 	);
	// } elseif ($quantityflag != 1 && $priceflag == 1) {
	// 	$data = array(
	// 		"variant" => array(
	// 			"id" => $variantid,
	// 			"price" => number_format($price, 2, '.', ''),
	// 		)
	// 	);
	// } else {
	// 	// Set a default value for $data if none of the conditions are met
	// 	$data = array();
	// }
//                 global $conn;
//                 $url = "https://".$shopurl."/admin/api/2023-04/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;
//                 $response_arr = explode("\n",$response);	
                
          
//                 return true;
    


// }
function addlog($message, $type)
{
    global $logfile;
    $txt = date("Y-m-d H:i:s") . " [" . $type . "]: " . $message . "\n";
    fwrite($logfile, $txt);
}
addlog("Execution Finished", "INFO");
fclose($logfile);
