<?php
require_once __DIR__.'/amazonconfig.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';
class Amazon
{
    public function __construct() {
        $this->dataPath = __DIR__.'/../../inventory/';
        $this->properties = [511];
        $this->log = new Log('bug');
        $this->process_log = new Log('log/download/process_download_amazon');
        $this->process_upload_log = new Log('log/upload/process_upload_amazon');
        $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['amazon_acc_token']) && $_SESSION['amazon_acc_token'] != ''){
			return $acc_token;
		}
		else {
			return false;
		}
    }
    public function getActiveListings($offset = 0) {
    	$param = array(
			'method' => "GET",
			'url' => "https://openapi.amazon.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.amazon.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.amazon.com/v3/application/listings/{$listing_id}?limit=100&offset=$offset",
			'url' => "https://openapi.amazon.com/v3/application/listings/{$listing_id}",
		);
		$json = $this->executeCURL($param, true);
		if (isset($json['state'])) {
            return $json['state'];
        }
        return false;
        
    	
        /*$access_token = $_SESSION['amazon_acc_token']['oauth_token'];
        $access_token_secret = $_SESSION['amazon_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 {
            $data = $oauth->fetch("https://openapi.amazon.com/v2/listings/{$listing_id}", null, OAUTH_HTTP_METHOD_GET);
            $json = json_decode($oauth->getLastResponse(), true);
            if ($json['count']) {
                return reset($json['results'])['state'];
            }
            return array();

        } catch (OAuthException $e) {
            $msg = $oauth->getLastResponse();
            $rs = $oauth->getLastResponseInfo();
            return array(
                'error' => true,
                'msg' => $msg,
                'http_code' => $rs['http_code'],
            );
        }*/
    }
    public function getListing($listing_id) {
        $param = array(
			'method' => "GET",
			'url' => "https://openapi.amazon.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;
		}
		
        /*$access_token = $_SESSION['amazon_acc_token']['oauth_token'];
        $access_token_secret = $_SESSION['amazon_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 {
            $data = $oauth->fetch("https://openapi.amazon.com/v2/listings/{$listing_id}/inventory", null, OAUTH_HTTP_METHOD_GET);
            $json = json_decode($oauth->getLastResponse(), true);
            return $json;

        } catch (OAuthException $e) {
            $msg = $oauth->getLastResponse();
            $rs = $oauth->getLastResponseInfo();
            return array(
                'error' => true,
                'msg' => $msg,
                'http_code' => $rs['http_code'],
            );
        }*/
    }
    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['Amazon'])) {
                    $product['Retail'][$key]['Amazon'] = array();
                }
                $product['Retail'][$key]['Amazon']['Stock'] = 1;
            }
        }
        return $product;

    }
    public function checkDeactiveListing($product) {
        $stock = Retail::calculateStockTotal($product);
        if ($stock > 0) {
            return false;
        }
        return true;
    }
    public function changeState($listing_id, $state) {
        $access_token = $_SESSION['amazon_acc_token']['oauth_token'];
        $access_token_secret = $_SESSION['amazon_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 {
            $oauth->setAuthType(OAUTH_AUTH_TYPE_FORM);
            $data = $oauth->fetch(
                "https://openapi.amazon.com/v2/listings/{$listing_id}",
                [
                    'state' => $state?'active':'inactive',
                ],
                OAUTH_HTTP_METHOD_PUT
            );
            $json = json_decode($oauth->getLastResponse(), true);
            return $json;

        } catch (OAuthException $e) {
            error_log($e->getMessage());
            error_log(print_r($oauth->getLastResponse(), true));
            error_log(print_r($oauth->getLastResponseInfo(), true));
            return array();
        }
    }
    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 createAmazonReceiptShipment($file=null, $OrderDate=null) {
    	$rs = array('success' => false, 'err' => '', 'DATA' => '');
        $receipt_id = '';
        $carrier_name = '';
        $tracking_code = '';
        $orderInfoDir = "../retail/Amazon/";
		$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.amazon.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['StoreListingASIN']) && isset($product['StoreListingASIN']['amazon']) && $product['StoreListingASIN']['amazon']) {
            if (is_array($product['StoreListingASIN']['amazon']) && isset($product['StoreListingASIN']['amazon'][0])) {
                $itemId = $product['StoreListingASIN']['amazon'][0];
            } else {
                $itemId = $product['StoreListingASIN']['amazon'];
            }
        }
        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['Amazon'])) {
                                    $diff = $retail['Amazon']['Stock'] - $quantity;
                                    if (isset($retail['Amazon']['Stock'])) {
                                        $retail['Amazon']['Stock'] = $quantity;
                                    }
                                    if ($diff > 0) {
                                        $retail['Amazon']['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, 'Amazon', $diff);
                                        $inventoryCtl->updateSaleData($p, $retail, 'Amazon', $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, false);
            }
            $this->process_upload_log->output($msg, __FILE__  , __LINE__);
            return $update;
        }
        if ($state == 'edit') {
            $msg .= "Activate listing".PHP_EOL;
            $deactive = $this->changeState($listing_id, true);
        }
        $update = $this->updateInventory($listing_id, $inventory, $product, $type, false);
        $this->process_upload_log->output($msg);
        return $update;
    }
    public function upload() {
    	$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);        		
        		$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) {        
        $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;
                    }
                }
            }
            if (isset($product['Retail'][$retailName])) {
                $listing = $product['Retail'][$retailName];                
                if ($upload == '' || $upload == 'stock') {
                    $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']} - Quantiy: $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'] = $quantity;
                    $shouldUpload = true;
                }
                if ($upload == '' || $upload == 'price') {
                    $price = $retail->calculateRetail($product, $listing, true, $this->process_upload_log);
                    $msg .= "{$listing['RetailSize']} {$listing['RetailUnit']} - Price: $price - ".PHP_EOL;
                    $inventory['offerings'][0]['price'] = $price;
                    $shouldUpload = true;
                }
            }
        }
        $msg .= 'shouldUpload '.($shouldUpload?'true':'false').PHP_EOL;
        if(!empty($inventories)){
			foreach($inventories as &$inventoryTemp){
				if(isset($inventoryTemp['product_id'])) {
					unset($inventoryTemp['product_id']);
				}
				if(isset($inventoryTemp['is_deleted'])) {
					unset($inventoryTemp['is_deleted']);
				}
				if(isset($inventoryTemp['property_values']) && !empty($inventoryTemp['property_values'])) {
					foreach($inventoryTemp['property_values'] as &$property_values){
						if(isset($property_values['scale_name'])){
							unset($property_values['scale_name']);
						}
							
					}
				}
				if(isset($inventoryTemp['offerings']) && !empty($inventoryTemp['offerings'])) {
					foreach($inventoryTemp['offerings'] as &$offerings){
						if(isset($offerings['offering_id'])){
							unset($offerings['offering_id']);
						}
						if(isset($offerings['is_deleted'])){
							unset($offerings['is_deleted']);
						}
						if(isset($offerings['price']) && is_array($offerings['price'])){
							$priceArr = $offerings['price'];
							$price=0;
							if(isset($offerings['price']['amount'])  && $offerings['price']['amount'] > 0){
								$price=$offerings['price']['amount'];
							}
							if(isset($offerings['price']['divisor']) && $offerings['price']['divisor'] > 0){
								$price = $price/$offerings['price']['divisor'];
							}
							unset($offerings['price']);
							$offerings['price'] = number_format($price,'2');
							
						}
					}
				}
				
			}
		}
        $data = [
            'products' => $inventories,
            'price_on_property' => $properties,
            'quantity_on_property' => $properties,
            'sku_on_property' => $properties
        ];
        
        //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.amazon.com/v3/application/listings/{$listing_id}/inventory",
				'data' => json_encode($data)
			);
			$json = $this->executeCURL($param, true);
			//$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 getAmazonOrder(){
		$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/Amazon/";
		$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;
			}
			//$cDate = "2024-11-10";
			$CreateTimeFrom = $cDate.'T00:00:00Z';
			$CreateTimeTo = $cDate.'T23:59:59Z';
			
			if($cDate==date('Y-m-d')) {
				$CreateTimeTo = '';
			}
			$options = array(
				'CreateTimeFrom' => $CreateTimeFrom,
				'CreateTimeTo' => $CreateTimeTo
			);
			$fileName = $cDate.'.json';
			$allOrders = $this->getOrders($options);
        	if(isset($allOrders['Orders']) && !empty($allOrders['Orders'])) {
				$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);
				$amazonTotalLog = array();
				if($fileData!= '' && count($fileData)>0) {
					$amazonTotalLog = $fileData;
				}
				$reduceArr = array();
				foreach($allOrders['Orders'] as $aOrderKey => $aOrder){
					$AmazonOrderId = $aOrder['AmazonOrderId'];
					$allTrans = $this->getOrderTransactions($AmazonOrderId);
					$orderFound = false;
					$orderTrackingChanged = false;
					if($amazonTotalLog!= '' && count($amazonTotalLog)>0) {
						foreach($amazonTotalLog as $OrderIndex => $fileDataRow){
							if (isset($fileDataRow['Order']) && is_array($fileDataRow['Order'])) {
								foreach ($fileDataRow['Order'] as $OrderSubIndex => $order) {
									if($order['OrderId'] == $AmazonOrderId) {
										$orderFound = true;
										break;
									}
								}
							}
						}
					}
					if($orderFound) {
						continue;
					}

					$amazonOrderLogInfo = $RetailerOrderLogTemplate;
					$orderInfo = $amazonOrderLogInfo['Order'][0];
					$CustomerEmail = isset($aOrder['BuyerInfo']['BuyerEmail'])?$aOrder['BuyerInfo']['BuyerEmail']:'';
					$CustomerName = isset($aOrder['BuyerInfo']['BuyerName'])?$aOrder['BuyerInfo']['BuyerName']:'';
					$CustomerPhone = isset($aOrder['BuyerInfo']['BuyerPhoneNumber'])?$aOrder['BuyerInfo']['BuyerPhoneNumber']:'';


					$AddressName =isset($aOrder['ShippingAddress']['Name'])?$aOrder['ShippingAddress']['Name']:'';
					$AddressStreet = isset($aOrder['ShippingAddress']['AddressLine1'])?$aOrder['ShippingAddress']['AddressLine1']:'';
					$AddressUnit = isset($aOrder['ShippingAddress']['AddressLine2'])?$aOrder['ShippingAddress']['AddressLine2']:'';					
					$AddressCity = isset($aOrder['ShippingAddress']['City'])?$aOrder['ShippingAddress']['City']:'';
					$AddressState = isset($aOrder['ShippingAddress']['StateOrRegion'])?$aOrder['ShippingAddress']['StateOrRegion']:'';
					$AddressZip = isset($aOrder['ShippingAddress']['PostalCode'])?$aOrder['ShippingAddress']['PostalCode']:'';					
					$AddressCountry = isset($aOrder['ShippingAddress']['CountryCode'])?$aOrder['ShippingAddress']['CountryCode']:'';
					
					if($AddressCountry == 'US') {
						$AddressCountry = 'USA';
					}
					else if($AddressCountry == 'CA') {
						$AddressCountry = 'CAN';
					}

					$tempAdd = $amazonOrderLogInfo["Addresses"][0];
					$tempAdd['AddressType'] = "Residential";
					$tempAdd['AddressName'] = $AddressName;
					$tempAdd['AddressStreet'] = $AddressStreet;
					$tempAdd['AddressUnit'] = $AddressUnit;
					$tempAdd['AddressCity'] = $AddressCity;
					$tempAdd['AddressState'] = $AddressState;
					$tempAdd['AddressZip'] = $AddressZip;
					$tempAdd['AddressCountry'] = $AddressCountry;

					$OrderLastUpDate = '';
					if(isset($aOrder['LastUpdateDate']) && $aOrder['LastUpdateDate'] != '') {
						$OrderLastUpDate = date('Y-m-d H:i:s', strtotime($aOrder['LastUpdateDate']));
					}
					$ShipmentTrackingNumber = '';
					$ShippingCarrierUsed = isset($aOrder['AutomatedShippingSettings']['AutomatedCarrier'])?$aOrder['AutomatedShippingSettings']['AutomatedCarrier']:'';
					$ShippingService = '';
					$ShippingServiceCost = 0.00;

					$ShippedTime = '';
					if(isset($aOrder['LatestShipDate']) && $aOrder['LatestShipDate'] != '') {
						$ShippedTime = date('Y-m-d H:i:s', strtotime($aOrder['LatestShipDate']));
					}
					$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['PurchaseDate']) && $aOrder['PurchaseDate'] != '') {
						$CreatedTime = date('Y-m-d H:i:s', strtotime($aOrder['PurchaseDate']));
					}
					$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['LastUpdateDate']) && $aOrder['LastUpdateDate'] != '') {
						$LastModifiedTime = date('Y-m-d H:i:s', strtotime($aOrder['LastUpdateDate']));
					}

					$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');
					}
					$total_price = 0;
					if(isset($aOrder['OrderTotal']['Amount']) && $aOrder['OrderTotal']['Amount']>0){
						$total_price = $aOrder['OrderTotal']['Amount'];
					}
					
					
					$OrderDiscount = 0.00;
					$OrderTracking = '';
					$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(isset($allTrans['OrderItems']) && !empty($allTrans['OrderItems'])){
						foreach($allTrans['OrderItems'] as $Transaction){
							$TitleFull = $Transaction['Title'];
							$ItemID = $Transaction['ASIN'];
							$ProductSKU = isset($Transaction['SellerSKU'])?$Transaction['SellerSKU']:'';
							$TitleArr = explode(' - ', $TitleFull);
							$Title = '';
							if(isset($TitleArr[0])){
								$Title = str_replace('bodi : ', '', $TitleArr[0]);
							}
							$OrderAttribute = '';
							$QuantityPurchased = $Transaction['QuantityOrdered'];
							$TransactionPrice = 0;
							if(isset($Transaction['ItemPrice']['Amount']) && $Transaction['ItemPrice']['Amount']>0){
								$TransactionPrice = (float)$Transaction['ItemPrice']['Amount'];
							}
							if(isset($Transaction['ItemTax']['Amount']) && $Transaction['ItemTax']['Amount']>0){
								$TransactionPrice += (float)$Transaction['ItemTax']['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'];
									}
									
									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'];
	        								$OrderAttribute = $RetailSize.$RetailUnit;
	        								$isAttrFound = false;
	        								if($ProductSKU != '') {
	        									if($RetailIndex == $ProductSKU) {
	        										$isAttrFound = true;
	        										$OrderShipWeight = $RetailRow['ShipWeight'];
	        									}
	        								}
											if($isAttrFound) {
												$isfoundItem = true;
												$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
							);
							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($OrderTracking != ''){
						//$OrderStatus = 'Shipped';
						
						//-------------------------
						$RetailCost = ($OrderCostTotal)*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, 'Amazon', false);
					//}
					$OrderTrackingArr = array($OrderTracking);
					$OrderNotes = '';
					$orderInfo['OrderId'] = "$AmazonOrderId";
					$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['OrderCarrierCost'] = ($ShippingServiceCost == 0)?"":"$ShippingServiceCost";
					$orderInfo['OrderRetailer'] = "";
					$orderInfo['OrderNotes'] = "$OrderNotes";
					//$orderInfo['OrderAddressType'] = "$AddressStreet";
					$orderInfo['OrderAddressType'] = "$AddressZip";
					$orderInfo['OrderPaymentType'] = "";
					$orderInfo['OrderPaid'] = "";
					$orderInfo['OrderItems'] = $OrderItems;

					$amazonOrderLogInfo["BuyerUserID"] = "$AmazonOrderId";
					$amazonOrderLogInfo["CustomerName"] = $CustomerName;
					$amazonOrderLogInfo["Email"] = $CustomerEmail;
					$amazonOrderLogInfo["Phone"] = $CustomerPhone;
					$amazonOrderLogInfo["Addresses"][0] = $tempAdd;
			        $amazonOrderLogInfo['Order'][0] = $orderInfo;
			        array_push($amazonTotalLog, $amazonOrderLogInfo);
				}
				$saveSuccess = file_put_contents($orderInfoDir.$fileName . '_temp', json_encode($amazonTotalLog, JSON_PRETTY_PRINT));
			    if ($saveSuccess) {
			        $moveSuccess = rename($orderInfoDir.$fileName . '_temp', $orderInfoDir.$fileName);
			    }
			    
			    $options = array();
			    $options['store'] = 'Amazon';
			    $this->Order->updateLog($options);			    
			}
        }
				
		
		
		$this->sse->log('end', 'end');
		 return $rs;
	}
	public function getOrders($options=null) {
		if(!$options){
			return false;
		}
		$CreateTimeFrom = $options['CreateTimeFrom'];
		$CreateTimeTo = $options['CreateTimeTo'];
		$url = "https://sellingpartnerapi-na.amazon.com/orders/v0/orders?MarketplaceIds=".MARKETPLACEID."&CreatedAfter=".$CreateTimeFrom;
		if($CreateTimeTo!='') {
			$url .= "&CreatedBefore=".$CreateTimeTo;
		}
		
		
		$param = array(
			'method' => 'GET',
			'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['payload'])) {
			return $json['payload'];
		}
        else {
			return false;
		}
    }
    
	public function getAmazonTestOrders() {
		$param = array(
			'method' => 'GET',
			'url' => "https://sellingpartnerapi-na.amazon.com/orders/v0/orders?MarketplaceIds=".MARKETPLACEID."&CreatedAfter=2024-11-22T00:00:00Z&OrderStatuses=Unshipped",
		);
		$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 getAmazonTestOrderDetails() {
		$orderId = '112-9396262-5939403';
		$param = array(
			'method' => 'GET',
			'url' => "https://sellingpartnerapi-na.amazon.com/orders/v0/orders/".$orderId."/orderItems",
		);
		$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($AmazonOrderId=null) {
		if(!$AmazonOrderId){
			return false;
		}
		
		$param = array(
			'method' => "GET",
			'url' => "https://sellingpartnerapi-na.amazon.com/orders/v0/orders/".$AmazonOrderId."/orderItems",
		);
		$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['payload'])) {
			return $json['payload'];
		}
        else {
			return false;
		}
    }
	public function getActiveTransactions($offset = 0) {
		$param = array(
			'method' => 'GET',
			'url' => "https://openapi.amazon.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['amazon_acc_token']['oauth_token'];
        $access_token_secret = $_SESSION['amazon_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.amazon.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.amazon.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['amazon_acc_token']['oauth_token'];
        $access_token_secret = $_SESSION['amazon_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.amazon.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.amazon.com/v3/application/countries/{$country_id}",
		);
		$json = $this->executeCURL($param, true);
				
		if(isset($json['results'])) {
			return $json['results'];
		}
        else {
			return false;
		}
		
		/*$access_token = $_SESSION['amazon_acc_token']['oauth_token'];
        $access_token_secret = $_SESSION['amazon_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.amazon.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[0]='Authorization: Bearer '.$_SESSION['amazon_acc_token'];
	        $headers[1]='x-amz-access-token: '.$_SESSION['amazon_acc_token'];
	        $headers[2]='x-amz-date: '.gmdate('Ymd\THis\Z');
	        if(isset($param['method']) && ($param['method'] == "POST" || $param['method'] == "PUT")) {
	            if($json == true)
	            {
	                $headers[3]='Content-Type: application/json';
	            }
	            else {
					$headers[3]='Content-Type: application/x-www-form-urlencoded; charset=utf-8';
				}
	        }
	        else if(isset($param['method']) && $param['method'] == "GET") {
	            if($json == true)
	            {
	                $headers[3]='Content-Type: application/json';
	            }
	            else {
					$headers[3]='Content-Type: application/x-www-form-urlencoded; charset=utf-8';
				}
	        } 
	        echo "<pre>";
        	print_r($headers);
	        $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(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));
	}
}