<?php
require __DIR__.'/etsyconfig.php';
//require_once('../inventory.php');
require_once  __DIR__.'/../inventory.php';
require_once __DIR__.'/../product.php';
require_once __DIR__.'/../retail.php';
require_once __DIR__.'/../log.php';
require_once __DIR__.'/../sse.php';
require_once __DIR__.'/../helper/category-helper.php';
class Etsy
{
    public function __construct() {
        $this->dataPath = __DIR__.'/../../inventory/';
        $this->properties = [511];
        $this->log = new Log('bug');
        $this->process_log = new Log('log/download/process_download_etsy');
        $this->process_upload_log = new Log('log/upload/process_upload_etsy');
        $this->inventory = new InventoryCore();
    }
    public function saveList($file, $data) {
        $saveSuccess = file_put_contents($file . '_temp', json_encode($data, JSON_PRETTY_PRINT));
        if ($saveSuccess) {
            $moveSuccess = rename($file . '_temp', $file);
        }
    }
    function getAccessToken()
    {
    	if(isset($_SESSION['etsy_acc_token']) && $_SESSION['etsy_acc_token'] != ''){
			return $acc_token;
		}
		else {
			return false;
		}
    }
    public function getActiveListings($offset = 0) {
    	$param = array(
			'method' => "GET",
			'url' => "https://openapi.etsy.com/v3/application/shops/".SHOP_ID."/listings/active?limit=100&offset=$offset",
		);
		$json = $this->executeCURL($param, true);
		
		/*echo "<br>=====param=========";
		echo "<pre>";
		print_r($param);
		echo "<br>=====results=========";
		echo "<pre>";
		print_r($json);
		die('AAA');*/
		
		if(isset($json['results'])) {
			return $json['results'];
		}
        else {
			return false;
		}
    }
    public function getShops() {
    	$param = array(
			'method' => "GET",
			'url' => "https://openapi.etsy.com/v3/application/shops?shop_name=Bodi4Life",
		);
		$json = $this->executeCURL($param, true);
		
		echo "<br>=====param=========";
		echo "<pre>";
		print_r($param);
		echo "<br>=====results=========";
		echo "<pre>";
		print_r($json);
		die('AAA');
    }
    public function checkState($listing_id) {
    	$param = array(
			'method' => "GET",
			'url' => "https://openapi.etsy.com/v3/application/listings/{$listing_id}",
		);
		$json = $this->executeCURL($param, true);
		if (isset($json['state'])) {
            return $json['state'];
        }
        return false;        
    }
    public function getListing($listing_id) {
        $param = array(
			'method' => "GET",
			'url' => "https://openapi.etsy.com/v3/application/listings/{$listing_id}/inventory",
		);
		$json = $this->executeCURL($param, true);
		
		/*echo "<br>=====param=========";
		echo "<pre>";
		print_r($param);
		echo "<br>=====results=========";
		echo "<pre>";
		print_r($json);
		die('AAA');*/
		
		if(isset($json)) {
			return $json;
		}
        else {
			return false;
		}
    }
    public function searchProperty($arr) {
        foreach ($arr as $property) {
            if (array_search($property['property_id'], $this->properties) !== false) {
                return $property;
            }
        }
        return null;
    }
    public function setMinStock($product) {
        if (is_array($product['Retail'])) {
            foreach ($product['Retail'] as $key => $retail) {
                if (!isset($retail['Etsy'])) {
                    $product['Retail'][$key]['Etsy'] = array();
                }
                $product['Retail'][$key]['Etsy']['Stock'] = 1;
            }
        }
        return $product;

    }
    public function checkDeactiveListing($product) {
        $stock = Retail::calculateStockTotal($product);
        if ($stock > 0) {
            return false;
        }
        return true;
    }
   
    public function changeState($listing_id=null, $state = 'active') {
	    if (!$listing_id) {
	        return false;
	    }

	    $msg = '';
	    $data = ["state" => $state];

	    try {
	        $msg .= 'try ' . PHP_EOL;
	        $param = array(
	            'method' => "PUT",
	            'url' => "https://openapi.etsy.com/v3/application/shops/" . SHOP_ID . "/listings/{$listing_id}",
	            'data' => json_encode($data)
	        );

	        $json = $this->executeCURL($param, true);
			//echo "<br>Result START===== ";
			//pr($json);
			//echo "<br>Result END===== ";
	        // Optional: Check success based on $json structure
	        if (isset($json['error']) || isset($json['status']) && $json['status'] !== 'ok') {
	            $msg .= 'API Error: ' . print_r($json,true);
	            $this->process_upload_log->output($msg, __FILE__, __LINE__);
	            return false;
	        }
	        return true;
	    } catch (Exception $e) {
	        $msg .= 'catch ' . PHP_EOL;
	        $msg .= $e->getMessage();
	        $this->process_upload_log->output($msg, __FILE__, __LINE__);
	        error_log($e->getMessage());
	        return false;
	    }
	}
    public function hasQuantity($product) {
        if (is_array($product['Retail'])) {
            foreach ($product['Retail'] as $key => $listing) {
                $quantity = floor(Retail::calculateStockTotal($product, $listing['RetailUnit'])/$listing['RetailSize']);
                if ($quantity > 0) {
                    return true;
                }
            }
        }
        return false;
    }
    public function checkTrackingCode($OrderId=null) {
    	$rs = array('success' => false, 'err' => '', 'DATA' => '');
		if($OrderId=='') {
			$rs['success'] = false;
			$rs['err'] = "Invalid Request Data";
			return $rs;
		}										
        
        try {
        	$url = "https://openapi.etsy.com/v3/application/orders/$OrderId";
	        $param = array(
				'method' => "GET",
				'url' => $url
			);
			$orderData = $this->executeCURL($param, true);
			$trackingCode = '';
			if (isset($orderData['shipments'][0]['tracking_code'])) {
		        $trackingCode = $orderData['shipments'][0]['tracking_code'];
		    }
        	//echo "Request";
        	//echo "<br>url=$url";
        	//echo "<pre>";print_r($data);
			//echo "Response";
			//echo "<pre>";print_r($json);
			//die('STOP');
            $rs['success'] = true;
			$rs['err'] = "";
			$rs['DATA'] = $trackingCode;
			return $rs;
        } catch (Exception $e) {
            //echo "catch";
            //echo "<pre>";print_r($e->getMessage());
            //$msg .= 'catch '.PHP_EOL;
            //$msg .= print_r($oauth->getLastResponse(), true);
            //$msg .= $e->getMessage();
            //$this->process_upload_log->output($msg, __FILE__  , __LINE__);
            //error_log($e->getMessage());
            $rs['success'] = false;
			$rs['err'] = $e->getMessage();
			$rs['DATA'] = $e->getMessage();
			return $rs;
        }
    }
    public function createEtsyReceiptShipment($file=null, $OrderDate=null) {
    	$rs = array('success' => false, 'err' => '', 'DATA' => '');
        $receipt_id = '';
        $carrier_name = '';
        $tracking_code = '';
        $orderInfoDir = "../retail/Etsy/";
		$fileName = $file.'.json';
		$fileData = array();
		$fileData_json = file_get_contents($orderInfoDir.$fileName);
		if(!empty($fileData_json)) {
			$fileData = json_decode($fileData_json, true);
		}
		
		if(count($fileData)>0) {
			foreach($fileData as $OrderIndex => $fileDataRow){
				if (isset($fileDataRow['Order']) && is_array($fileDataRow['Order'])) {
					if(!empty($fileDataRow['Order'])) {
						foreach ($fileDataRow['Order'] as $order) {
							if($order['OrderDate'] == $OrderDate) {
								$receipt_id = $order['OrderId'];
								$carrier_name = $order['OrderCarrier'];
								
								if(isset($order['OrderTracking']) && !empty($order['OrderTracking'])) {
									foreach($order['OrderTracking'] as $OrderTracking) {
										if($OrderTracking!=''){
											$tracking_code = $OrderTracking;
										}
									}
								}						        
								break;
							}
						}
					}
				}
			}
		}
		
		if($receipt_id=='' || $carrier_name=='' || $tracking_code=='') {
			//return "Invalid Request Data";
			$rs['success'] = false;
			$rs['err'] = "Invalid Request Data";
			return $rs;
		}										
        
        try {
	    	$data = [
	            'tracking_code' => $tracking_code,
	            'carrier_name' => $carrier_name,
	            'send_bcc' => false,
	            'note_to_buyer' => ''
	        ];
        	$url = "https://openapi.etsy.com/v3/application/shops/".SHOP_ID."/receipts/{$receipt_id}/tracking";
	        $param = array(
				'method' => "POST",
				'url' => $url,
				'data' => json_encode($data)
			);
			$json = $this->executeCURL($param, true);
        	//echo "Request";
        	//echo "<br>url=$url";
        	//echo "<pre>";print_r($data);
			//echo "Response";
			//echo "<pre>";print_r($json);
			//die('STOP');
            $rs['success'] = true;
			$rs['err'] = "";
			$rs['DATA'] = $json;
			return $rs;
        } catch (Exception $e) {
            //echo "catch";
            //echo "<pre>";print_r($e->getMessage());
            //$msg .= 'catch '.PHP_EOL;
            //$msg .= print_r($oauth->getLastResponse(), true);
            //$msg .= $e->getMessage();
            //$this->process_upload_log->output($msg, __FILE__  , __LINE__);
            //error_log($e->getMessage());
            $rs['success'] = false;
			$rs['err'] = $e->getMessage();
			$rs['DATA'] = $e->getMessage();
			return $rs;
        }
    }
    private function getInventoryFilePath($inventoryName) {
        return $this->dataPath.$inventoryName.'.json';
    }
    public function loadInventory($inventoryName) {
        $filePath = $this->getInventoryFilePath($inventoryName);
        if (!is_file($filePath)) {
            return null;
        }
        return json_decode(file_get_contents($filePath), true);
    }
    public function loadAllInventories() {
        $inventoryFiles = preg_grep("/^(?!.*(Packaging|Shipping).*$)(.*\.json$)/", scandir($this->dataPath));
        $rs = array_map(function($filename){
            if (preg_match("/(.*)\.json$/", $filename, $match)) {
                $inv = array(
                    'format' => $match[1],
                    'data' => $this->loadInventory($match[1]),
                );
                return $inv;
            } else {
                return null;
            }
        }, $inventoryFiles);
        return array_values($rs);
    }
    public function getStoreListingASINId($product) {
        $itemId = '';
        if (isset($product['ListingID_etsy']) ) {
            $itemId = $product['ListingID_etsy'];
        }
        return $itemId;
    }    
    public function searchProduct($inventories, $item) {
        foreach ($inventories as $i => $inventory) {
            foreach ($inventory['data'] as $p => $product) {
                $itemId = $this->getStoreListingASINId($product);
                if ($itemId == $item['listing_id']) {
                    return array(
                        'product' => $product,
                        'format' => $inventory['format'],
                        'i_key' => $i,
                        'p_key' => $p,
                    );
                }
            }
        }
        return null;
    }
    public function writeFile($inventory, $data) {
        $saveSuccess = file_put_contents($this->getInventoryFilePath($inventory) . '_temp', json_encode($data, JSON_PRETTY_PRINT));
        if ($saveSuccess) {
            $moveSuccess = rename($this->getInventoryFilePath($inventory) . '_temp', $this->getInventoryFilePath($inventory));
        }
    }
    public function save($inventories) {
        foreach ($inventories as $inventory) {
            $this->writeFile($inventory['format'], $inventory['data']);
        }
    }
    public function checkUpload($product, $upload = 'stock') {
        if (is_array($product['Retail'])) {
            foreach ($product['Retail'] as $retail) {
                if ((($upload == 'stock' && isset($retail['UploadStock']) && $retail['UploadStock']) || ($upload == 'price' && isset($retail['UploadPrice']) && $retail['UploadPrice'])) &&
                    $this->getStoreListingASINId($product) != ''
                ) {
                    return true;
                }
            }
        }
        return false;
    }
    public function download() {
        $productTemplate = new Product();
        $this->sse = new SSE();
        $this->sse->log('start', 1000);
        $load = true;
        $offset = 0;
        $inventoryCtl = new Inventory();
        $inventories = $this->loadAllInventories();
        while ($load) {
            $activeItems = $this->getActiveListings($offset);
            foreach ($activeItems as $n => $activeItem) {
                $change = 0;
                $msg = '';
                $no = $n + $offset;
                $p = null;$rs = null;
                $rs = $this->searchProduct($inventories, $activeItem);
                if ($rs != null) {
                    $p = $rs['product'];
                    $msg .= "{$no}. ItemID: [{$activeItem['listing_id']}] {$p['Product']}".PHP_EOL;
                    $inventory = $this->getListing($activeItem['listing_id']);
                    //echo "<pre>";
                    //print_r($inventory);
                    //die('STOP');
                    $inventory = $inventory['results'];
                    if ($activeItem['has_variations']) {
                        foreach ($inventory['products'] as $product) {
                            $size = null;
                            $quantity = null;
                            if (is_array($product['property_values']) && count($product['property_values'])) {
                                $property_value = reset($product['property_values']);
                                $size = reset($property_value['values']).$property_value['scale_name'];
                                $size = preg_replace('/\s*/', '', $size);
                            }
                            if (is_array($product['offerings']) && count($product['offerings'])) {
                                $offering = reset($product['offerings']);
                                $quantity = $offering['quantity'];
                            }
                            $retail = null;
                            if (isset($p['Retail'][$size])) {
                                $retail = $p['Retail'][$size];
                            }
                            if ($retail != null) {
                                if (isset($retail['Etsy'])) {
                                    $diff = $retail['Etsy']['Stock'] - $quantity;
                                    if (isset($retail['Etsy']['Stock'])) {
                                        $retail['Etsy']['Stock'] = $quantity;
                                    }
                                    if ($diff > 0) {
                                        $retail['Etsy']['Sold'] += $diff;
                                        $p = $inventoryCtl->reduceInventoryItem($p, array(
                                            'units_select' => $retail['RetailSize'],
                                            'volume_quantity' => $diff,
                                            'unit' => $retail['RetailUnit'],
                                        ));
                                        $p = $inventoryCtl->addProductSold($p, $diff, $retail['RetailSize'], $retail['RetailUnit']);
                                        $inventoryCtl->addupCapital($p, $retail, 'Etsy', $diff);
                                        $inventoryCtl->updateSaleData($p, $retail, 'Etsy', $diff);
                                        $inventoryCtl->reducePackage($rs['format'], $retail);
                                    }
                                    // $retail['UploadStock'] = false;
                                    $p['Retail'][$size] = $retail;
                                }
                                if ($diff > 0) {
                                    $change += $diff;
                                    $msg .= "Size: $size -";
                                    $msg .= "Quantity: $quantity -";
                                    $msg .= "Quantity diff: $diff".PHP_EOL;
                                }
                            }
                        }
                    } else {
                        $msg .= '<p>'.$activeItem['title']. ' has no variations</p>'.PHP_EOL;
                    }
                    $productTemplate->data = $p;
                    $inventories[$rs['i_key']]['data'][$rs['p_key']] = $productTemplate->getData();
                } else {
                    $msg .= '<p>'.$activeItem['title']. ' not found. ItemID: '. $activeItem['listing_id']. '</p>'.PHP_EOL;
                }
                if ($change > 0) {
                    $this->process_log->output($msg);
                }
                $this->sse->log('process', $no);
            }
            if (count($activeItems) < 100) {
                $load = false;
            } else {
                $offset += 100;
            }
        }
        $this->save($inventories);
        $this->sse->log('end', 'end');
    }
    public function uploadProduct($product, $type) {
        $msg = '';
        $isDeactive = $this->checkDeactiveListing($product);
        $listing_id = $this->getStoreListingASINId($product);
        $msg .= "Item: {$product['Product']}".PHP_EOL;
        $state = $this->checkState($listing_id);
        $inventory = $this->getListing($listing_id);
        if (isset($inventory['error'])) {
            $msg .= "ERR: {$inventory['msg']}".PHP_EOL;
            $this->process_upload_log->output($msg, __FILE__  , __LINE__);
            return false;
        }
        if ($isDeactive) {
            if ($state == 'active') {
                $msg .= "Deactivate listing".PHP_EOL;
                $msg .= "Set variation quantity to 1".PHP_EOL;
                $product = $this->setMinStock($product);
                $update = $this->updateInventory($listing_id, $inventory, $product, $type, false);
                $deactive = $this->changeState($listing_id, 'inactive');
            }
            $this->process_upload_log->output($msg, __FILE__  , __LINE__);
            return $update;
        }
        if ($state == 'edit') {
            $msg .= "Activate listing".PHP_EOL;
            $deactive = $this->changeState($listing_id, 'active');
        }
        $update = $this->updateInventory($listing_id, $inventory, $product, $type, false);
        $this->process_upload_log->output($msg);
        return $update;
    }
    public function upload() {
    	$msg = '';
    	$this->process_upload_log->output($msg);
        $this->sse = new SSE();
        $this->sse->log('start', 1000);
        $total = 0;
        $products = $this->inventory->loadJson(__DIR__.'/../../setting/uploadsync.json');
        if(!empty($products)) {
			foreach($products as $product) {
				$listing_id = $product['ListingID_etsy'];
				$listing = $this->getListing($listing_id);  
				//Listing Activate/Deactivate------------
            	$changeToState = '';
            	if (CategoryHelper::isHandCraft($product['Category']) === false) {
	            	// $isDeactive = $this->checkDeactiveListing($product);
	            	$state = $this->checkState($listing_id);
			        /*if ($isDeactive) {
			            if ($state == 'active') {
			            	$changeToState = 'inactive';
			                $msg .= "Deactivate listing".PHP_EOL;
			                $msg .= "Set variation quantity to 1".PHP_EOL;
			                $product = $this->setMinStock($product);
			                $this->changeState($listing_id, $changeToState);
			            }
			        }*/
			        if ($state == 'inactive') {
			        	$changeToState = 'active';
			            $msg .= "Activate listing".PHP_EOL;
			            $this->changeState($listing_id, $changeToState);
			        }
				}
            	//-------------------------------------
				// if($changeToState=='inactive') {
				// 	$total += 1;
				// 	$msg .= '***SUCCESS***'.PHP_EOL;
	            //     $this->sse->log('process', $total);
				// }
				// else {
                $revise = $this->updateInventory($listing_id, $listing, $product);
                if ($revise) {
                    $total += 1;
                    $msg .= '***SUCCESS***'.PHP_EOL;
                    $this->sse->log('process', $total);
                }
                else {
                    $msg .= '***FAILED***'.PHP_EOL;
                }
				// }
			}
		}
		
        $this->process_upload_log->output($msg);
        $this->process_upload_log->output("Total: {$total} items updated");
        $this->sse->log('end', 'end');
    }
    public function updateInventory($listing_id, $inventories, $product, $upload = '', $checkCondition = true) {
        $shouldUpload = false;
        $msg = '1.000003 sku null'.PHP_EOL;
        $this->sse->log('msg', $msg);
        $properties = array();
        $inventories = $inventories['products'];//listing
        foreach ($inventories as &$inventory) {
            $retailName = null;
            $quantity = null;
            if (is_array($inventory['property_values']) && count($inventory['property_values'])) {
                $property_value = $inventory['property_values'][0];
                $property_id = $property_value['property_id'];
                if (!in_array($property_id, $properties)) {
                    $properties[] = $property_id;
                }
            }
            
            if (isset($inventory['sku']) && $inventory['sku']) {
                $sku = $inventory['sku'];
                $msg .= 'sku='.$inventory['sku'].PHP_EOL;
                if ($sku != $product['SKU']) {
                    continue;
                }
            }
            
            if ($upload == '' || $upload == 'stock') {
	            if (CategoryHelper::isHandCraft($product['Category']) !== false) {
	                $quantity = 50;
	            } else {
	                $quantity = $product['Qty'];
	                $quantity = $quantity > 0 ? $quantity : 0;
	                
	            }
	            $inventory['offerings'][0]['quantity'] = (int)$quantity;
	            if($quantity<=0){
					 $inventory['offerings'][0]['is_enabled'] = false;
				}
	            $shouldUpload = true;
	        }
	        if ($upload == '' || $upload == 'price') {
	            $price = $product['Price'];
	            $inventory['offerings'][0]['price'] = round((float)$price, 2);
	            $shouldUpload = true;
	        }
        }
        if (!empty($inventories)) {
		    foreach ($inventories as &$inventoryTemp) {
		        unset($inventoryTemp['product_id'], $inventoryTemp['is_deleted']);

		        // Clean up property_values
		        if (!empty($inventoryTemp['property_values'])) {
		            foreach ($inventoryTemp['property_values'] as &$property_values) {
		                unset($property_values['scale_name'], $property_values['scale_id']);
		            }
		            unset($property_values); // break reference
		        }

		        // Clean up offerings
		        if (!empty($inventoryTemp['offerings'])) {
		            foreach ($inventoryTemp['offerings'] as &$offerings) {
		                unset($offerings['offering_id'], $offerings['is_deleted']);

		                if (isset($offerings['price']) && is_array($offerings['price'])) {
		                    $price = 0;
		                    if (!empty($offerings['price']['amount'])) {
		                        $price = $offerings['price']['amount'];
		                    }
		                    if (!empty($offerings['price']['divisor'])) {
		                        $price = $price / $offerings['price']['divisor'];
		                    }
		                    $offerings['price'] = round((float)$price, 2);
		                }
		            }
		            unset($offerings); // break reference
		        }
		    }
		    unset($inventoryTemp); // break reference
		}
        $data = [
            'products' => $inventories,
            'price_on_property' => $properties,
            'quantity_on_property' => $properties,
            'sku_on_property' => $properties
        ];
        //echo "<br>shouldUpload=$shouldUpload";
        //echo "<br>JSONSTART=>".json_encode($data)."<=JSONEND<br>";
        //only for debug-------------
        //$this->process_upload_log->output($msg, __FILE__  , __LINE__);
        //return true; 
        //--------------
        
        
        if (!$shouldUpload) {
            return false;
        }
        try {
            $msg .= 'try '.PHP_EOL;
	        $param = array(
				'method' => "PUT",
				'url' => "https://openapi.etsy.com/v3/application/listings/{$listing_id}/inventory",
				'data' => json_encode($data)
			);
			$json = $this->executeCURL($param, true);
			//echo "<br>Result START===== ";
			//pr($json);
			//echo "<br>Result END===== ";
			//$msg .= 'Result START===== '.PHP_EOL;
			//$msg .= print_r($json, true);
			//$msg .= 'Result END===== '.PHP_EOL;
			//$msg .= 'DONE===== '.PHP_EOL;
            $this->process_upload_log->output($msg, __FILE__  , __LINE__);
            return true;
        } catch (Exception $e) {
            $msg .= 'catch '.PHP_EOL;
            // $msg .= print_r($oauth->getLastResponse(), true);
            $msg .= $e->getMessage();
            $this->process_upload_log->output($msg, __FILE__  , __LINE__);
            error_log($e->getMessage());
            return false;
        }
    }
	
	
    public function uploadtest() {
        $msg = '';
    	$this->process_upload_log->output($msg);
        $this->sse = new SSE();
        $this->sse->log('start', 1000);
        $total = 0;
        $products = $this->inventory->loadJson(__DIR__.'/../../setting/uploadsync.json');
        if(!empty($products)) {
			foreach($products as $product) {
        		$msg .= "Item: {$product['Product']}".PHP_EOL;
				$product['Format'] = $product['Category'];
				$listing_id = $this->getStoreListingASINId($product);
                $msg .= "listing_id: {$listing_id}".PHP_EOL;
            	$listing = $this->getListing($listing_id);   
            	
            	//Listing Activate/Deactivate------------
            	$changeToState = '';
            	if (CategoryHelper::isHandCraft($product['Format']) === false) {
	            	$isDeactive = $this->checkDeactiveListing($product);
	            	$state = $this->checkState($listing_id);
			        if ($isDeactive) {
			            if ($state == 'active') {
			            	$changeToState = 'inactive';
			                $msg .= "Deactivate listing".PHP_EOL;
			                $msg .= "Set variation quantity to 1".PHP_EOL;
			                $product = $this->setMinStock($product);
			                $this->changeState($listing_id, $changeToState);
			            }
			            //$this->process_upload_log->output($msg, __FILE__  , __LINE__);
			            //return true;
			        }
			        if ($state == 'inactive') {
			        	$changeToState = 'active';
			            $msg .= "Activate listing".PHP_EOL;
			            $this->changeState($listing_id, $changeToState);
			        }
			}
            	//-------------------------------------
            	if($changeToState=='inactive') {
					$total += 1;
					$msg .= '***SUCCESS***'.PHP_EOL;
	                $this->sse->log('process', $total);
				} 
				else {
					$revise = $this->updateInventory($listing_id, $listing, $product);
	        		if ($revise) {
	                    $total += 1;
	                    $msg .= '***SUCCESS***'.PHP_EOL;
	                    $this->sse->log('process', $total);
	                }
	                else {
						$msg .= '***FAILED***'.PHP_EOL;
					}
				}	
			}
		}
        $this->process_upload_log->output($msg);
        $this->process_upload_log->output("Total: {$total} items updated");
        $this->sse->log('end', 'end');
    }
    public function updateInventorytest($listing_id, $inventories, $product, $upload = '', $checkCondition = true) {        
        $msg = '1.000003 sku null'.PHP_EOL;
        $this->sse->log('msg', $msg);
        $properties = array();
        $retail = new Retail();
        $inventories = $inventories['products'];
        foreach ($inventories as &$inventory) {
            $retailName = null;
            $quantity = null;
            if (is_array($inventory['property_values']) && count($inventory['property_values'])) {
                $property_value = $inventory['property_values'][0];
                $property_id = $property_value['property_id'];
                if (!in_array($property_id, $properties)) {
                    $properties[] = $property_id;
                }
            }
            if (isset($inventory['sku']) && $inventory['sku']) {
                $sku = $inventory['sku'];
                $msg .= 'sku='.$inventory['sku'].PHP_EOL;
                foreach ($product['Retail'] as $key => $rt) {
                    if ($key == $sku) {
                        $retailName = $key;
                        break;
                    }
                }
            }
            if (!$retailName) {
                $msg .= 'sku not match'.PHP_EOL;
                if (is_array($inventory['property_values']) && count($inventory['property_values'])) {
                    $property_value = $inventory['property_values'][0];
                    if ($property_value != null) {
                        $retailName = reset($property_value['values']).$property_value['scale_name'];
                        $retailName = preg_replace('/\s*/', '', $retailName);
                    } else {
                        $msg .= "property not found".PHP_EOL;
                    }
                }
            }
            //$msg .= 'A'.PHP_EOL;
            if (isset($product['Retail'][$retailName])) {
            	//$msg .= 'B'.PHP_EOL;
                $listing = $product['Retail'][$retailName];                
                if ($upload == '' || $upload == 'stock') {
                	//$msg .= 'C:Format='.$product['Format'].PHP_EOL;
                    if (CategoryHelper::isHandCraft($product['Format']) !== false) {
                    	//$msg .= 'D'.PHP_EOL;
                        $quantity = 50;
                    } else {
                    	//$msg .= 'E'.PHP_EOL;
                        $quantity = floor(Retail::calculateStockTotal($product, $listing['RetailUnit'])/$listing['RetailSize']);
                        $hasQuantity = $this->hasQuantity($product);
                        if($hasQuantity) {
                            $quantity = $quantity > 0 ? $quantity : 1;
                        }
                        else {
                            $quantity = $quantity > 0 ? $quantity : 0;
                        }
                        $msg .= "{$listing['RetailSize']} {$listing['RetailUnit']} - Quantity: $quantity - ".PHP_EOL;
                        if ($listing['RetailSize'] == '8' && strtolower($listing['RetailUnit']) == 'oz') $quantity = 0;
                        if ($listing['RetailSize'] == '12' && strtolower($listing['RetailUnit']) == 'oz') $quantity = 0;
                        if ($listing['RetailSize'] == '32' && strtolower($listing['RetailUnit']) == 'oz') $quantity = 0;
                        if ($listing['RetailSize'] == '2' && strtolower($listing['RetailUnit']) == 'lb') $quantity = 0;
                    }
                    $inventory['offerings'][0]['quantity'] = (int)$quantity;
                    if($quantity<=0){
						 $inventory['offerings'][0]['is_enabled'] = false;
					}
                    $shouldUpload = true;
                }
                if ($upload == '' || $upload == 'price') {
                    $price = $retail->calculateRetailUniversal($product, $listing, 'bodiretailer');
                    $msg .= "{$listing['RetailSize']} {$listing['RetailUnit']} - Price: $price - ".PHP_EOL;
                    $inventory['offerings'][0]['price'] = round((float)$price, 2);;
                    $shouldUpload = true;
                }
            }
        }
        $msg .= 'shouldUpload '.($shouldUpload?'true':'false').PHP_EOL;
        if (!empty($inventories)) {
		    foreach ($inventories as &$inventoryTemp) {
		        unset($inventoryTemp['product_id'], $inventoryTemp['is_deleted']);

		        // Clean up property_values
		        if (!empty($inventoryTemp['property_values'])) {
		            foreach ($inventoryTemp['property_values'] as &$property_values) {
		                unset($property_values['scale_name'], $property_values['scale_id']);
		            }
		            unset($property_values); // break reference
		        }

		        // Clean up offerings
		        if (!empty($inventoryTemp['offerings'])) {
		            foreach ($inventoryTemp['offerings'] as &$offerings) {
		                unset($offerings['offering_id'], $offerings['is_deleted']);

		                if (isset($offerings['price']) && is_array($offerings['price'])) {
		                    $price = 0;
		                    if (!empty($offerings['price']['amount'])) {
		                        $price = $offerings['price']['amount'];
		                    }
		                    if (!empty($offerings['price']['divisor'])) {
		                        $price = $price / $offerings['price']['divisor'];
		                    }
		                    $offerings['price'] = round((float)$price, 2);
		                }
		            }
		            unset($offerings); // break reference
		        }
		    }
		    unset($inventoryTemp); // break reference
		}
        $data = [
            'products' => $inventories,
            'price_on_property' => $properties,
            'quantity_on_property' => $properties,
            'sku_on_property' => $properties
        ];
        //echo "<br>shouldUpload=$shouldUpload";
        //echo "<br>JSONSTART=>".json_encode($data)."<=JSONEND<br>";
        //only for debug-------------
        //$this->process_upload_log->output($msg, __FILE__  , __LINE__);
        //return true; 
        //--------------
        
        if (!$shouldUpload) {
            return false;
        }
        try {
            $msg .= 'try '.PHP_EOL;
	        $param = array(
				'method' => "PUT",
				'url' => "https://openapi.etsy.com/v3/application/listings/{$listing_id}/inventory",
				'data' => json_encode($data)
			);
			$json = $this->executeCURL($param, true);
			//echo "<br>Result START===== ";
			//pr($json);
			//echo "<br>Result END===== ";
			//$msg .= 'Result START===== '.PHP_EOL;
			//$msg .= print_r($json, true);
			//$msg .= 'Result END===== '.PHP_EOL;
			//$msg .= 'DONE===== '.PHP_EOL;
            $this->process_upload_log->output($msg, __FILE__  , __LINE__);
            return true;
        } catch (Exception $e) {
            $msg .= 'catch '.PHP_EOL;
            // $msg .= print_r($oauth->getLastResponse(), true);
            $msg .= $e->getMessage();
            $this->process_upload_log->output($msg, __FILE__  , __LINE__);
            error_log($e->getMessage());
            return false;
        }
    }
	
	public function convertDateFromTimezone($date,$timezone,$timezone_to,$format){
		$date = new DateTime($date,new DateTimeZone($timezone));
		$date->setTimezone( new DateTimeZone($timezone_to) );
		return $date->format($format);
	}
	public function getProductList() {
        $inventoryFiles = $this->inventory->getList();
        $products = array();
        foreach ($inventoryFiles as $filename) {
            $data = $this->inventory->loadInventory($filename);
            if (is_array($data)) {
                foreach ($data as $i => $product) {
                	$attributes = array('4oz');
                	if (isset($product['Retail']) && is_array($product['Retail']))
                		$attributes = array_keys($product['Retail']);
                	$products[] = array(
                		'label' => $product['Product'],
                		'value' => array(
                    		'inventory' => $this->inventory->removeExt($filename),
                    		'product' => $product['Product'],
                    		'itemData' => array(
                    			'Format' => $this->inventory->removeExt($filename),
                    			'Product' => $product['Product'],
                    			'Retail' => $product['Retail'],
                    			'Suppliers' => $product['Suppliers'],
                    			'StoreListingASIN' => $product['StoreListingASIN']
                    		),
                    		'attributes' => $attributes,
                		),
                	);
                }
            }
        }
        usort($products, function($a, $b) {
        	return strcmp($a['label'], $b['label']);
        });
        return $products;
	}
	public function getEtsyOrder(){
		$this->sse = new SSE();
        $this->sse->log('start', 1000);
        $load = true;
        $offset = 0;

		require_once '../retail/order.php';
		$this->Order = new Order();
		$retail = new Retail();
        $orderInfoDir = "../retail/Etsy/";
		$RetailerOrderLogTemplateUrl = "../retail/RetailerOrderLogTemplate.json";
		$rs = false;
        $today = date('Y-m-d');
        $dateFrom = date('Y-m-d', strtotime($today." -6 day"));
		$dateTo = date('Y-m-d');

        $date1_ts = strtotime($dateFrom);
	    $date2_ts = strtotime($dateTo);
	    $diff = $date2_ts - $date1_ts;
	    $no_of_days = round($diff / 86400);
	    //$products = $this->getProductList();
	    $products = $this->Order->getProductList();
        for($i=0;$i<=$no_of_days;$i++) {
        	$cDate1 = date('Y-m-d');
        	if($i>0){
				$date = new DateTime($cDate1);
				$date->sub(new DateInterval('P'.$i.'D')); // P1D means a period of 1 day
				$cDate = $date->format('Y-m-d');
			}
			else {
				$cDate = $cDate1;
			}
			$CreateTimeFrom = strtotime($cDate.' 00:00:01');
			$CreateTimeTo = strtotime($cDate.' 23:59:59');
			$options = array(
				'CreateTimeFrom' => $CreateTimeFrom,
				'CreateTimeTo' => $CreateTimeTo
			);
			$fileName = $cDate.'.json';
			$allOrders = $this->getOrders($options);
        	if(!empty($allOrders)) {
				$rs = true;
				$RetailerOrderLogTemplate = json_decode(file_get_contents($RetailerOrderLogTemplateUrl), true);
				$fileData = array();
				//if (file_exists(dirname(__FILE__).'/'.$orderInfoDir.$fileName) ) {
				    $fileData_json = file_get_contents($orderInfoDir.$fileName);
					if(!empty($fileData_json)) {
						$fileData = json_decode(file_get_contents($orderInfoDir.$fileName), true);
					}
				//}
				
				//$totalCnt = count($allOrders);
				$etsyTotalLog = array();
				if($fileData!= '' && count($fileData)>0) {
					$etsyTotalLog = $fileData;
				}
				$reduceArr = array();
				foreach($allOrders as $aOrderKey => $aOrder){
					$receipt_id = $aOrder['receipt_id'];
					$allTrans = $this->getOrderTransactions($receipt_id);
					$orderFound = false;
					$orderTrackingChanged = false;
					if($etsyTotalLog!= '' && count($etsyTotalLog)>0) {
						foreach($etsyTotalLog as $OrderIndex => $fileDataRow){
							if (isset($fileDataRow['Order']) && is_array($fileDataRow['Order'])) {
								foreach ($fileDataRow['Order'] as $OrderSubIndex => $order) {
									if($order['OrderId'] == $receipt_id) {
										$orderFound = true;
										break;
									}
								}
							}
						}
					}
					if($orderFound) {
						continue;
					}

					$etsyOrderLogInfo = $RetailerOrderLogTemplate;
					$orderInfo = $etsyOrderLogInfo['Order'][0];
					$BuyerUserID = $aOrder['buyer_user_id'];
					$CustomerName = isset($aOrder['name'])?$aOrder['name']:'';
					$CustomerEmail = isset($aOrder['buyer_email'])?$aOrder['buyer_email']:'';
					$CustomerPhone = '';
					if($CustomerPhone!=''){
						$firstPart = substr($CustomerPhone,0,3);
						$secondPart = substr($CustomerPhone,3,3);
						$thirdPart = substr($CustomerPhone,6,4);
						$CustomerPhone = $firstPart.'-'.$secondPart.'-'.$thirdPart;
					}

					$tempAdd = $etsyOrderLogInfo["Addresses"][0];
					$AddressStreet = '';
					$AddressUnit = '';
					if(isset($aOrder['first_line']) && $aOrder['first_line'] != ''){
						$AddressStreet .= $aOrder['first_line'];
					}
					if(isset($aOrder['second_line']) && $aOrder['second_line'] != ''){
						$AddressUnit .= ' '.$aOrder['second_line'];
					}

					$AddressZip = '';
					if(isset($aOrder['zip']) && $aOrder['zip'] != ''){
						$AddressZip = $aOrder['zip'];
					}

					$tempAdd['AddressType'] = "Residential";
					$tempAdd['AddressName'] =$CustomerName;
					$tempAdd['AddressStreet'] = $AddressStreet;
					$tempAdd['AddressUnit'] = $AddressUnit;
					$tempAdd['AddressCity'] = isset($aOrder['city'])?$aOrder['city']:'';
					$tempAdd['AddressState'] = isset($aOrder['state'])?$aOrder['state']:'';
					$tempAdd['AddressZip'] = $AddressZip;
					$AddressCountry = '';
					$country_id = '';
					if(isset($aOrder['country_iso']) && $aOrder['country_iso'] != ''){
						$AddressCountry = $aOrder['country_iso']; ////Only 3 character
					}
					else if(isset($aOrder['country_id']) && $aOrder['country_id'] != ''){
						$country_id = $aOrder['country_id'];
						$countryData = $this->getCountryById($country_id);
						if(isset($countryData[0]['world_bank_country_code']) && $countryData[0]['world_bank_country_code'] != '') {
							$AddressCountry = $countryData[0]['world_bank_country_code'];
						}
					}
					
					if($AddressCountry == 'US') {
						$AddressCountry = 'USA';
					}
					else if($AddressCountry == 'CA') {
						$AddressCountry = 'CAN';
					}
					$tempAdd['AddressCountry'] = $AddressCountry;

					$OrderLastUpDate = '';
					//if(isset($aOrder['last_modified_tsz']) && $aOrder['last_modified_tsz'] != '') {
					//	$OrderLastUpDate = date('Y-m-d H:i:s', $aOrder['last_modified_tsz']);
					//}
					if(isset($aOrder['updated_timestamp']) && $aOrder['updated_timestamp'] != '') {
						$OrderLastUpDate = date('Y-m-d H:i:s', $aOrder['updated_timestamp']);
					}
					$ShipmentTrackingNumber = isset($aOrder['shipments'][0]['tracking_code'])?$aOrder['shipments'][0]['tracking_code']:'';
					$ShippingCarrierUsed = isset($aOrder['shipments'][0]['carrier_name'])?$aOrder['shipments'][0]['carrier_name']:'';
					$ShippingService = '';
					$ShippingServiceCost = 0.00;
					if(isset($aOrder['total_shipping_cost']['amount']) && $aOrder['total_shipping_cost']['amount'] != '' ) {
						$ShippingServiceCost = $aOrder['total_shipping_cost']['amount'];
						if(isset($aOrder['total_shipping_cost']['divisor']) && $aOrder['total_shipping_cost']['divisor']>0) {
							$ShippingServiceCost = $ShippingServiceCost/$aOrder['total_shipping_cost']['divisor'];
						}
					}

					$ShippedTime = '';
					if(isset($aOrder['shipped_date']) && $aOrder['shipped_date'] != '') {
						$ShippedTime = date('Y-m-d H:i:s', $aOrder['shipped_date']);
					}
					$OrderDeliveryDate = '';
					if($ShippedTime!=''){
						$OrderDeliveryDate = $this->convertDateFromTimezone($ShippedTime,'GMT','America/New_York','Y-m-d H:i:s');
						$OrderDeliveryDateObj = new DateTime($OrderDeliveryDate);
						$OrderDeliveryDateObj->sub(new DateInterval('PT7H'));
						$OrderDeliveryDate = $OrderDeliveryDateObj->format('Y-m-d H:i:s');
					}

					$CreatedTime = '';
					if(isset($aOrder['created_timestamp']) && $aOrder['created_timestamp'] != '') {
						$CreatedTime = date('Y-m-d H:i:s', $aOrder['created_timestamp']);
					}
					$OrderDate='';
					if($CreatedTime!=''){
						$OrderDate = $this->convertDateFromTimezone($CreatedTime,'GMT','America/New_York','Y-m-d H:i:s');
						$OrderDateObj = new DateTime($OrderDate);
						$OrderDateObj->sub(new DateInterval('PT7H'));
						$OrderDate = $OrderDateObj->format('Y-m-d H:i:s');

					}

					$LastModifiedTime = '';
					if(isset($aOrder['updated_timestamp']) && $aOrder['updated_timestamp'] != '') {
						$LastModifiedTime = date('Y-m-d H:i:s', $aOrder['updated_timestamp']);
					}

					$OrderLastUpDate='';
					if($LastModifiedTime!=''){
						$OrderLastUpDate = $this->convertDateFromTimezone($LastModifiedTime,'GMT','America/New_York','Y-m-d H:i:s');
						$OrderLastUpDateObj = new DateTime($OrderLastUpDate);
						$OrderLastUpDateObj->sub(new DateInterval('PT7H'));
						$OrderLastUpDate = $OrderLastUpDateObj->format('Y-m-d H:i:s');
					}
					
					if(isset($aOrder['total_price']['divisor']) && $aOrder['total_price']['divisor']>0){
						$total_price = $aOrder['total_price']['amount']/$aOrder['total_price']['divisor'];
					}
					else {
						$total_price = $aOrder['total_price']['amount'];
					}
					
					if(isset($aOrder['grandtotal']['divisor']) && $aOrder['grandtotal']['divisor']>0){
						$AmountPaid = $Total = $aOrder['grandtotal']['amount']/$aOrder['grandtotal']['divisor'];
					}
					else {
						$AmountPaid = $Total = $aOrder['grandtotal']['amount'];
					}
					
					$OrderDiscount = 0.00;
					if($aOrder['discount_amt']['amount']>0 && $aOrder['total_price']['amount']>0) {
						if(isset($aOrder['discount_amt']['divisor']) && $aOrder['discount_amt']['divisor']>0){
							$discount_amt = $aOrder['discount_amt']['amount']/$aOrder['discount_amt']['divisor'];
						}
						else {
							$discount_amt = $aOrder['discount_amt']['amount'];
						}
						$OrderDiscount = ($discount_amt/$total_price)*100;
					}
					$OrderTracking = '';
					if(isset($ShipmentTrackingNumber) && $ShipmentTrackingNumber != '') {
						$OrderTracking = $ShipmentTrackingNumber;
					}
					$OrderCarrier = 'usps';
					$OrderCarrierService = 'ground';
					$OrderStatus = 'Ordered';
					/*if(isset($ShippingCarrierUsed) && $ShippingCarrierUsed != '') {
						$OrderCarrier = $ShippingCarrierUsed;
						if($ShippingCarrierUsed == 'USPS'){
							$OrderCarrier = 'usps';
						}
					}*/
					$OrderShipWeightTotal = 0;
					
					$OrderItems = array();
					$rOrderItems = array();
					$OrderCostTotal = 0.00;
					$shipweightTotal = 0;
					$OrderExpenseCostTotal = 0.00;
					$ShipFeeExpenseTotal = 0.00;
					$PackingFeeExpenseTotal = 0.00;
					$ShipFeeForProductCostTotal = 0.00;
					//echo "<pre>";print_r($allTrans);die('SS');
					if(!empty($allTrans)){
						foreach($allTrans as $Transaction){
							$OrderSubCategory = '';
							$OrderTaskPoint = '';
							$TitleFull = $Transaction['title'];
							$ItemID = $Transaction['listing_id'];
							$ProductSKU = isset($Transaction['sku'])?$Transaction['sku']:'';
							$TitleArr = explode(' - ', $TitleFull);
							$Title = '';
							if(isset($TitleArr[0])){
								$Title = $TitleArr[0];
								$TitleArr = explode(' | ', $Title);
								if(isset($TitleArr[0])){
									$Title = $TitleArr[0];
								}
							}
							
							$OrderAttribute = '';
							if(isset($Transaction['variations'][0]['formatted_value'])) {
								$Attribute = $Transaction['variations'][0]['formatted_value'];
								$OrderAttribute = '';
								if($Attribute!='') {
									$OrderAttribute = str_replace(' ', '', $Attribute);
								}
							}
							$QuantityPurchased = $Transaction['quantity'];
							if(isset($Transaction['price']['divisor']) && $Transaction['price']['divisor']>0){
								$TransactionPrice = $Transaction['price']['amount']/$Transaction['price']['divisor'];
							}
							else {
								$TransactionPrice = $Transaction['price']['amount'];
							}
							
							
							//---------------------
							$OrderShipWeight = 0;
							$isfoundItem = false;
							if(!empty($products)) {
								foreach($products as $productTemp1) {
									$productTemp = $productTemp1['value']['itemData'];
									if($ProductSKU != '') {
										foreach($productTemp['Retail'] as $RetailIndex => $RetailRow){
											if($RetailIndex == $ProductSKU) {
												$isfoundItem = true;
												$product = $productTemp;
												break;
											}
										}
									}
									if(!$isfoundItem) {
										//echo "<br>".$productTemp['Product']."==".$Title;
										if(isset($productTemp['Product']) && $productTemp['Product'] == $Title){
											$isfoundItem = true;
											$product = $productTemp;
										}
									}
									if(!$isfoundItem) {
										continue;
									}
									if(isset($product['Product']) && $product['Product'] != '') {
										$Title = $product['Product'];
									}
									$OrderSubCategory = $product['SubCategory'] ?? '';
									if(isset($product['Retail']) && is_array($product['Retail']) && !empty($product['Retail']) && $product['Retail'] != '') {
										foreach($product['Retail'] as $RetailIndex => $RetailRow){
	        								$RetailSize = $RetailRow['RetailSize'];
	        								$RetailUnit = $RetailRow['RetailUnit'];
	        								$retailAttribute = $RetailSize.$RetailUnit;
	        								$isAttrFound = false;
	        								if($ProductSKU != '') {
	        									if($RetailIndex == $ProductSKU) {
	        										$isAttrFound = true;
	        										$OrderShipWeight = $RetailRow['ShipWeight'];
	        									}
	        								}
	        								if(!$isAttrFound && $retailAttribute == $OrderAttribute) {
	        									$isAttrFound = true;
	        									$OrderShipWeight = $RetailRow['ShipWeight'];
	        								}
											if($isAttrFound) {
												$isfoundItem = true;
												$OrderTaskPoint = $RetailRow['TaskPoint'];
												$cost = $retail->calculateCost($product, $RetailRow);
												$feePacking = 0;
												$inventory = $retail->getFormat($product['Format']);
												if (isset($RetailRow['FeePacking']) && $RetailRow['FeePacking'] > 0) {
													$feePacking = (isset($RetailRow['FeePacking']) && $RetailRow['FeePacking']!='')?$RetailRow['FeePacking']:0;
										        } else {
										            $feePacking = $retail->getFeePacking($inventory, $RetailRow);
										        }
							        
										        $CostTotal = (($cost+$feePacking)*$QuantityPurchased);
												$OrderCostTotal += $CostTotal;
												
												$CostOnly = ($cost*$QuantityPurchased);
		        								$OrderExpenseCostTotal += $CostOnly;
		        								$PackingFeeExpenseTotal += $feePacking;
												break;
											}
										}
									}
									
									if($isfoundItem) {
										break;
									}
								}
							}
							$shipweightTotal += ($OrderShipWeight*$QuantityPurchased);
							//----------------------
							
							$tempItem = array(
								"OrderProduct" => $Title,
								"OrderProductID" => $ItemID,
								"OrderProductSKU" => $ProductSKU,
					            "OrderAttribute" => $OrderAttribute,
					            "OrderShipWeight" => $OrderShipWeight,
					            "OrderQuantity" => $QuantityPurchased,
					            "OrderPrice" => $TransactionPrice,
					            "OrderSubCategory" => $OrderSubCategory,
					            "OrderTaskPoint" => $OrderTaskPoint
							);
							array_push($OrderItems, $tempItem);
							
							$rtempItem = array(
								"OrderDate" => $OrderDate,
								"OrderProduct" => $Title,
								"OrderProductID" => $ItemID,
								"OrderProductSKU" => $ProductSKU,
					            		"OrderAttribute" => $OrderAttribute,
					            		"OrderShipWeight" => $OrderShipWeight,
					            		"OrderQuantity" => $QuantityPurchased,
					            		"OrderPrice" => $TransactionPrice
							);
							array_push($rOrderItems, $rtempItem);
							
						}
					}
					if(isset($aOrder['message_from_buyer']) && $aOrder['message_from_buyer'] != '') {
						$tempItem = array(
							"OrderProduct" => $aOrder['message_from_buyer'],
							"OrderProductID" => '',
							"OrderProductSKU" => '',
				            "OrderAttribute" => 'Instr',
				            "OrderShipWeight" => '',
				            "OrderQuantity" => '',
				            "OrderPrice" => ''
						);
						array_push($OrderItems, $tempItem);
					}
					
					//if($OrderTracking != ''){
						//$OrderStatus = 'Shipped';
						
						//-------------------------
						$RetailCost = ($Total)*0.15;
						$OrderCostTotal += $RetailCost;
						
						if(($ShippingServiceCost == '' || $ShippingServiceCost == 0) && ($shipweightTotal>0)) {
							$shipFeeTotal = 0.00;
							//$sizeData = array('ShipWeight' => $shipweightTotal);
							//$ShippingServiceCost = $shipFeeTotal = $retail->calculateShipFee($sizeData);
							//echo "<br>shipFeeTotal=".$shipFeeTotal;
							$OrderCostTotal += $shipFeeTotal;
							$ShipFeeExpenseTotal += $shipFeeTotal;
						}
						else {
							$OrderCostTotal += $ShippingServiceCost;
							$ShipFeeExpenseTotal += $ShippingServiceCost;
						}
						if($shipweightTotal>0) {
							$ShipFeeForProductCostTotal = $retail->getFeeShippingTotal($shipweightTotal);
						}
						//-------------------------
								
						$rTempArr = array('OrderTotal' => $Total, 'OrderCostTotal' => $OrderCostTotal, 'RetailCost' => $RetailCost, 'OrderExpenseCostTotal' => $OrderExpenseCostTotal, 'ShipFeeExpenseTotal' => $ShipFeeExpenseTotal, 'PackingFeeExpenseTotal' => $PackingFeeExpenseTotal, 'ShipFeeForProductCostTotal' => $ShipFeeForProductCostTotal, 'OrderItems' => $rOrderItems);
						array_push($reduceArr, $rTempArr);
						
						//$this->Order->reduceInv($OrderItems, $products, 'Etsy', false);
					//}
					$OrderTrackingArr = array($OrderTracking);
					$OrderNotes = isset($aOrder['message_from_buyer'])?$aOrder['message_from_buyer']:'';
					$orderInfo['OrderId'] = "$receipt_id";
					$orderInfo['OrderDate'] = "$OrderDate";
					$orderInfo['OrderTotal'] = "$Total";
					$orderInfo['OrderCoupon'] = "";
					$orderInfo['OrderStatus'] = "$OrderStatus";
					$orderInfo['OrderLastUpDate'] = "$OrderLastUpDate";
					$orderInfo['OrderDiscount'] = "$OrderDiscount";
					$orderInfo['OrderDeliveryDate'] = "$OrderDeliveryDate";
					$orderInfo['OrderTracking'] = $OrderTrackingArr;
					$orderInfo['OrderCarrier'] = "$OrderCarrier";
					$orderInfo['OrderCarrierService'] = "$OrderCarrierService";
					$orderInfo['OrderShipWeightTotal'] = "$shipweightTotal";
					//$orderInfo['OrderCarrierFeeRetail'] = ($ShippingServiceCost == 0)?"":"$ShippingServiceCost";
					$orderInfo['OrderCarrierFeeRetail'] = "$ShippingServiceCost";
					$orderInfo['OrderRetailer'] = "";
					$orderInfo['OrderNotes'] = "$OrderNotes";
					//$orderInfo['OrderAddressType'] = "$AddressStreet";
					$orderInfo['OrderAddressType'] = "$AddressZip";
					$orderInfo['OrderPaymentType'] = "";
					$orderInfo['OrderPaid'] = "";
					$orderInfo['OrderItems'] = $OrderItems;

					$CustomerID = $BuyerUserID;
					$etsyOrderLogInfo["BuyerUserID"] = $BuyerUserID;
					$etsyOrderLogInfo["CustomerName"] = $CustomerName;
					$etsyOrderLogInfo["Email"] = $CustomerEmail;
					$etsyOrderLogInfo["Phone"] = $CustomerPhone;
					$etsyOrderLogInfo["Addresses"][0] = $tempAdd;
			        $etsyOrderLogInfo['Order'][0] = $orderInfo;
			        array_push($etsyTotalLog, $etsyOrderLogInfo);
				}
				$saveSuccess = file_put_contents($orderInfoDir.$fileName . '_temp', json_encode($etsyTotalLog, JSON_PRETTY_PRINT));
			    if ($saveSuccess) {
			        $moveSuccess = rename($orderInfoDir.$fileName . '_temp', $orderInfoDir.$fileName);
			    }
			    
			    $options = array();
			    $options['store'] = 'Etsy';
			    $this->Order->updateLog($options);
				/*if(!empty($allOrders)){
					foreach($allOrders as $aOrderKey => $aOrder){
						$receipt_id = $aOrder['receipt_id'];
						$allTrans = $this->getOrderTransactions($receipt_id);
						echo "=======aOrder========";
						print_r($aOrder);
						echo "=======allTrans========";
						print_r($allTrans);
						echo "==================================";
					}
				}*/
				
				//Reduce Inventory----
			    /*if(!empty($reduceArr)) {
					foreach($reduceArr as $rData){
						$OrderTotal = (float)$rData['OrderTotal'];
						$OrderCostTotal = (float)$rData['OrderCostTotal'];
						$RetailCost = (float)$rData['RetailCost'];
						$OrderExpenseCostTotal = (float)$rData['OrderExpenseCostTotal'];
						$ShipFeeExpenseTotal = (float)$rData['ShipFeeExpenseTotal'];
						
						$OrderProfitTotal = $OrderTotal-$OrderCostTotal;
						$this->Order->reduceInv($rData['OrderItems'], $products, 'Etsy', true);//true for no update sale...
						$this->Order->onlyUpdateMonthlySales($OrderTotal, $OrderProfitTotal, 'Etsy');
						$dataExpense = array(
							'OrderStore' => 'Ebay',
							'RetailCost' => $RetailCost,
							'OrderCostTotal' => $OrderExpenseCostTotal,
							//'ShipFeeTotal' => $ShipFeeExpenseTotal,
							'PackingFeeTotal' => $PackingFeeExpenseTotal,
							'ShipFeeForProductCostTotal' => $ShipFeeForProductCostTotal
						);
						$this->Order->onlyUpdateMonthlyExpenses($dataExpense);
					}
				}*/
			    //Reduce Inventory----
			    
			}
        }
				
		
		
		$this->sse->log('end', 'Success');
		 return $rs;
	}
	public function getEtsyOrderTest(){
		require_once '../retail/order.php';
		$this->Order = new Order();
		$retail = new Retail();
	    //$products = $this->Order->getProductList();
	    
		$CreateTimeFrom = strtotime('2026-02-26 00:00:01');
		$CreateTimeTo = strtotime('2026-02-26 23:59:59');
		$options = array(
			'CreateTimeFrom' => $CreateTimeFrom,
			'CreateTimeTo' => $CreateTimeTo
		);

		$allOrders = $this->getOrders($options);

		echo "===allOrders=============";
		pr($allOrders);
    	if(!empty($allOrders)) {
			foreach($allOrders as $aOrderKey => $aOrder){
				$receipt_id = $aOrder['receipt_id'];
				$allTrans = $this->getOrderTransactions($receipt_id);
				echo "<br>receipt_id=$receipt_id";
				pr($allTrans);
				if(!empty($allTrans)){
					foreach($allTrans as $Transaction){

						echo "===getOrderTransactions=============";
						$OrderSubCategory = '';
						$OrderTaskPoint = '';
						$TitleFull = $Transaction['title'];
						$ItemID = $Transaction['listing_id'];
						$ProductSKU = isset($Transaction['sku'])?$Transaction['sku']:'';
						$TitleArr = explode(' - ', $TitleFull);
						$Title = '';
						if(isset($TitleArr[0])){
							$Title = $TitleArr[0];
							$TitleArr = explode(' | ', $Title);
							if(isset($TitleArr[0])){
								$Title = $TitleArr[0];
							}
						}
						echo "<br>TitleFull=$TitleFull";
						echo "<br>Title=$Title";
						echo "<br>ProductSKU=$ProductSKU";
						//pr($aOrder);
					}
				}
			}
		}
				
		die('STOP');
	}
	public function getOrders($options=null) {
		if(!$options){
			return false;
		}
		$CreateTimeFrom = $options['CreateTimeFrom'];
		$CreateTimeTo = $options['CreateTimeTo'];

		$query = http_build_query([
			'min_created' => $CreateTimeFrom,
			'max_created' => $CreateTimeTo,
			'limit' => 25,
			'offset' => 0
		]);

		$url = "https://api.etsy.com/v3/application/shops/".SHOP_ID."/receipts?" . $query;
		//$url = "https://api.etsy.com/v3/application/shops/".SHOP_ID."/receipts?shop_id=".SHOP_ID."&min_created=".$CreateTimeFrom."&max_created=".$CreateTimeTo."&limit=25&offset=0";

		$param = array(
			'method' => 'GET',
			'callFrom'=>'',			
			'url' => $url,
		);
		$json = $this->executeCURL($param, true);
		
		/*echo "<br>=====param=========";
		echo "<pre>";
		print_r($param);
		echo "<br>=====results=========";
		echo "<pre>";
		print_r($json);
		die('AAA');*/
		
		if(isset($json['results'])) {
			return $json['results'];
		}
        else {
			return false;
		}
    }
    
	public function getEtsyTestOrders() {
		$CreateTimeFrom = strtotime('2025-05-03 00:00:01');
		$CreateTimeTo = strtotime('2025-05-03 23:59:59');
		
		$param = array(
			'method' => 'GET',
			'url' => "https://openapi.etsy.com/v3/application/shops/".SHOP_ID."/receipts?shop_id=".SHOP_ID."&min_created=".$CreateTimeFrom."&max_created=".$CreateTimeTo."&limit=25&offset=0",
		);
		$json = $this->executeCURL($param, true);
		
		echo "<br>=====param=========";
		echo "<pre>";
		print_r($param);
		echo "<br>=====results=========";
		echo "<pre>";
		print_r($json);
		die('AAA');
		
    }
    
	public function getOrderTransactions($receipt_id=null) {
		if(!$receipt_id){
			return false;
		}
		
		$param = array(
			'method' => "GET",
			'url' => "https://openapi.etsy.com/v3/application/shops/".SHOP_ID."/receipts/".$receipt_id."/transactions?receipt_id=".$receipt_id."",
		);
		$json = $this->executeCURL($param, true);
		/*echo "<br>=====param=========";
		echo "<pre>";
		print_r($param);
		echo "<br>=====results=========";
		echo "<pre>";
		print_r($json);
		die('AAA');*/
		if(isset($json['results'])) {
			return $json['results'];
		}
        else {
			return false;
		}
		
		/*$access_token = $_SESSION['etsy_acc_token']['oauth_token'];
        $access_token_secret = $_SESSION['etsy_acc_token']['oauth_token_secret'];
        $oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
        $oauth->setToken($access_token, $access_token_secret);
        try {
        	$URL = 'https://openapi.etsy.com/v2/receipts/'.$receipt_id.'/transactions';
            $oauth->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION);
            $data = $oauth->fetch(
		        $URL,
		        [
		            'receipt_id' => $receipt_id,
		            'limit' => 25,
		            'offset' => 0
		        ],
		        OAUTH_HTTP_METHOD_GET,
		        ['Content-Type' => 'application/json']
		    );

            $results = json_decode($oauth->getLastResponse(), true);
            return $results['results'];
		
        } catch (OAuthException $e) {
        	//echo "=========catch=========";
        	//echo "<pre>";
        	//print_r($e);
        	//die('catch');
            $this->log->output($e->getMessage(), __FILE__  , __LINE__);
            error_log($e->getMessage());
            error_log(print_r($oauth->getLastResponse(), true));
            error_log(print_r($oauth->getLastResponseInfo(), true));
        	return false;
        }*/

    }
	public function getActiveTransactions($offset = 0) {
		$param = array(
			'method' => 'GET',
			'url' => "https://openapi.etsy.com/v3/application/shops/".SHOP_ID."/transactions?shop_id=".SHOP_ID."&limit=20&offset=$offset&type=Transaction",
		);
		$json = $this->executeCURL($param, true);
		if(isset($json['results'])) {
			return $json['results'];
		}
        else {
			return false;
		}
		
		
        /*$access_token = $_SESSION['etsy_acc_token']['oauth_token'];
        $access_token_secret = $_SESSION['etsy_acc_token']['oauth_token_secret'];
        $oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
        $oauth->setToken($access_token, $access_token_secret);
        try {
        	$URL = 'https://openapi.etsy.com/v2/shops/Bodi4Life/transactions';
            $oauth->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION);
            $data = $oauth->fetch(
		        $URL,
		        [
		            'shop_id' => 'Bodi4Life',
		            'limit' => 20,
		            'offset' => $offset,
		            'type' => 'Transaction'
		        ],
		        OAUTH_HTTP_METHOD_GET,
		        [
		        	'Content-Type' => 'application/json'
		        ]
		    );

            $results = json_decode($oauth->getLastResponse(), true);
            return $results['results'];

        } catch (OAuthException $e) {
            $this->log->output($e->getMessage(), __FILE__  , __LINE__);
            error_log($e->getMessage());
            error_log(print_r($oauth->getLastResponse(), true));
            error_log(print_r($oauth->getLastResponseInfo(), true));
        	return false;
        }*/
    }

	public function getReceiptById($receipt_id=null){
		if(!$receipt_id){
			return false;
		}
		
		$param = array(
			'method' => "GET",
			'url' => "https://openapi.etsy.com/v3/application/receipts/{$receipt_id}",
		);
		$json = $this->executeCURL($param, true);
				
		if(isset($json['results'])) {
			return $json['results'];
		}
        else {
			return false;
		}
		
		/*
		//receipts/:receipt_id
		$access_token = $_SESSION['etsy_acc_token']['oauth_token'];
        $access_token_secret = $_SESSION['etsy_acc_token']['oauth_token_secret'];
        $oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
        $oauth->setToken($access_token, $access_token_secret);
        try {
        	$URL = 'https://openapi.etsy.com/v2/receipts/'.$receipt_id;
            $oauth->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION);
            $data = $oauth->fetch(
		        $URL, '', OAUTH_HTTP_METHOD_GET, ['Content-Type' => 'application/json']
		    );

            $results = json_decode($oauth->getLastResponse(), true);
            return $results['results'];

        } catch (OAuthException $e) {
            $this->log->output($e->getMessage(), __FILE__  , __LINE__);
            error_log($e->getMessage());
            error_log(print_r($oauth->getLastResponse(), true));
            error_log(print_r($oauth->getLastResponseInfo(), true));
        	return false;
        }*/

	}
	public function getCountryById($country_id=null){
		if(!$country_id){
			return false;
		}
		$param = array(
			'method' => "GET",
			'url' => "https://openapi.etsy.com/v3/application/countries/{$country_id}",
		);
		$json = $this->executeCURL($param, true);
				
		if(isset($json['results'])) {
			return $json['results'];
		}
        else {
			return false;
		}
		
		/*$access_token = $_SESSION['etsy_acc_token']['oauth_token'];
        $access_token_secret = $_SESSION['etsy_acc_token']['oauth_token_secret'];
        $oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
        $oauth->setToken($access_token, $access_token_secret);
        try {
        	$URL = 'https://openapi.etsy.com/v2/countries/'.$country_id;
        	$data = $oauth->fetch($URL, '', OAUTH_HTTP_METHOD_GET, ['Content-Type' => 'application/json']);
            $results = json_decode($oauth->getLastResponse(), true);
            return $results['results'];

        } catch (OAuthException $e) {
            $this->log->output($e->getMessage(), __FILE__  , __LINE__);
            error_log($e->getMessage());
            error_log(print_r($oauth->getLastResponse(), true));
            error_log(print_r($oauth->getLastResponseInfo(), true));
        	return false;
        }*/

	}

	public function executeCURL( $param, $json = true )
    {
    	try {
        	$headers = array();
	        $headers[]='Authorization: Bearer '.$_SESSION['etsy_acc_token'];
	        $headers[]='x-api-key: '.OAUTH_CONSUMER_KEY.':'.OAUTH_CONSUMER_SECRET;
	        //$headers[]='x-api-secret: '.OAUTH_CONSUMER_SECRET;
	        if(isset($param['method']) && ($param['method'] == "POST" || $param['method'] == "PUT")) {
	            if($json == true)
	            {
	                $headers[]='Content-Type: application/json';
	            }
	            else {
					$headers[]='Content-Type: application/x-www-form-urlencoded; charset=utf-8';
				}
	        }
	        else if(isset($param['method']) && $param['method'] == "GET") {
	            if($json == true)
	            {
	                $headers[]='Content-Type: application/json';
	            }
	            else {
					$headers[]='Content-Type: application/x-www-form-urlencoded; charset=utf-8';
				}
	        } 
	        $curl = curl_init();
	        curl_setopt($curl, CURLOPT_URL, $param['url']);
	        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
	        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
	        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

	        if(isset($param['method']) && $param['method'] == "PUT") {
	        	curl_setopt($curl, CURLOPT_ENCODING, '');
	        	curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
	        	curl_setopt($curl, CURLOPT_TIMEOUT, 0);
	        	curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
	        	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
	        	
	            curl_setopt($curl, CURLOPT_POST, true);
	            curl_setopt($curl, CURLOPT_POSTFIELDS, $param['data']);
	        }
			if(isset($param['method']) && $param['method'] == "POST" ) {
	        	curl_setopt($curl, CURLOPT_ENCODING, '');
	        	curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
	        	curl_setopt($curl, CURLOPT_TIMEOUT, 0);
	        	curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
	        	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
	        	
	            curl_setopt($curl, CURLOPT_POST, true);
	            curl_setopt($curl, CURLOPT_POSTFIELDS, $param['data']);
	        }

	        $data = curl_exec($curl);	      
			if(isset($param['callFrom']) && $param['callFrom']=='TEST') {
				echo "<br>URL=".$param['url']; 
	        	echo "<br>=====headers============";
				pr($headers);
				echo "<br>=====Request============";
				pr($param);
				echo "<br>=====Response============";
				pr($data);
				die('STOP');
			}  
	        if(curl_errno($curl)) {
	            trigger_error('Curl error: ' . curl_error($curl), E_USER_ERROR);
	        } elseif($json) {           
	            return json_decode( $data, true);
	        } else {
	            return $data;
	        }
	        
	        curl_close($curl);
        } 
        catch (Exception $e) {
        	echo "=========catch=========";
        	echo "<pre>";
        	print_r($e);
        	die('catch');
            $this->log->output($e->getMessage(), __FILE__  , __LINE__);
            error_log($e->getMessage());
            //error_log(print_r($oauth->getLastResponse(), true));
            //error_log(print_r($oauth->getLastResponseInfo(), true));
        	return false;
        }
    	
    	
        
    }
}
if (!function_exists('pr')) {
	function pr($var) {
		$template = php_sapi_name() !== 'cli' ? '<pre>%s</pre>' : "\n%s\n";
		printf($template, print_r($var, true));
	}
}