<?php
ini_set('serialize_precision', 14);
ini_set('precision', 14);
require_once(__DIR__.'/../../php/template/BodiTemplate.php');
require_once(__DIR__.'/../../php/template/InventoryTemplate.php');
require_once(__DIR__.'/../../php/inventory.php');
require_once(__DIR__.'/../../php/conversion.php');
require_once(__DIR__.'/../../Accounting/monthly-capital.php');
require_once(__DIR__.'/../../php/retail.php');
require_once(__DIR__.'/../../php/product.php');
require_once(__DIR__.'/../../php/shop-product.php');
//require_once(__DIR__.'/../../bodiforbusiness/retail/stamps.php');
require_once(__DIR__.'/../../php/ShipLabel/stamps.php');
require_once(__DIR__.'/../../php/ShipLabel/ups.php');
require_once(__DIR__.'/../../php/accounting.php');
require_once(__DIR__.'/../../php/helper/category-helper.php');
require_once(__DIR__.'/classes/Order.php');
use PHPMailer\PHPMailer\PHPMailer;
class Order {
	private $logDataPath;
	private $folderPath;
	private $InvDataForCache;
	private $StampsModel;
	private $UpsModel;
	private $countryCode;
	private $franchiseInventoryPath;
	public function __construct() {
        date_default_timezone_set("America/New_York");
        $this->settingPath = __DIR__.'/../../setting/admin.json';
        $this->supplierLogPath = __DIR__.'/../../Supplier/supplier-log.json';
        $this->franchiseInventoryPath = __DIR__.'/../../Bodi/12428+NY_Ellenville/inventory/';
        $this->InvDataForCache=array();

        $this->inventoryTemplate = new InventoryTemplate();
        $this->inventory = new InventoryCore();
        $this->shopInventory = new InventoryCore();
        $this->shopInventory->setPath($this->franchiseInventoryPath);
        $this->StampsModel = new Stamps();
	$this->UpsModel = new Ups();
        $this->countryCode = array('USA' => 'US', 'CAN' => 'CA', 'AUS' => 'AU', 'AUT' => 'AT', 'BEL' => 'BE', 'BRA' => 'BR', 'BGR' => 'BG', 'CAM' => 'Cambogia', 'CHL' => 'CL', 'CHN' => 'CN', 'COL' => 'CO', 'CRI' => 'CR', 'CZE' => 'CZ', 'DNK' => 'DK', 'ECU' => 'EC', 'EGY' => 'EG', 'DEU' => 'DE', 'GRC' => 'GR', 'HKG' => 'HK', 'HUN' => 'HU', 'ISL' => 'IS', 'IND' => 'IN', 'ISR' => 'IL', 'ITA' => 'IT', 'JPN' => 'JP', 'KOR' => 'KR', 'KWT' => 'KW', 'LIE' => 'LI', 'LUX' => 'LU', 'MEX' => 'MX', 'MCO' => 'MC', 'NLD' => 'NL', 'NOR' => 'NO', 'PER' => 'PE', 'POL' => 'PO', 'PRT' => 'PT', 'PRI' => 'PR', 'ROU' => 'RO', 'RUS' => 'RU', 'SAU' => 'SA', 'ESP' => 'ES', 'SWE' => 'SE', 'CHE' => 'CH', 'TUR' => 'TR', 'UKR' => 'UA', 'GBR' => 'GB');
	}
	public function loadInfoByStore($storeName, $fileName) {
		if (!is_file($storeName. '/'. $fileName . '.json')) {
			return null;
		}

		return json_decode(file_get_contents($storeName. '/'. $fileName . '.json'), true);
	}
	public function loadFile($filename) {
		if (!is_file($filename)) {
			return null;
		}
		return json_decode(file_get_contents($filename), true);
	}
	public function load($options) {
		$OrderStatus = $options['OrderStatus'];
		$OrderStore = $options['OrderStore'];
		$OrderDate = $options['OrderDateSearch'];
		$monthName = array("January" => "01", "February" => "02", "March" => "03", "April" => "04", "May" => "05", "June" => "06", "July" => "07", "August" => "08", "September" => "09", "October" => "10", "November" => "11", "December" => "12");
		$searchRangeArr = array();
		$OrderDeliveryDateFrom = '';
		$OrderDeliveryDateTo = '';

		if($OrderDate !=''){
			$cDate = date("Y-m-d");
			$OrderDateRangeArr = explode('@@', $OrderDate);
			if(!empty($OrderDateRangeArr)) {
				foreach($OrderDateRangeArr as $Rval) {
					$Rval = trim($Rval);
					if($Rval!='') {
						$MonthArr = explode(' ', $Rval);
						if(isset($MonthArr[1]) && $MonthArr[1] != '') {
							$date = $MonthArr[1].'-'.$monthName[$MonthArr[0]].'-01';
							$OrderDeliveryDateFrom = date('Y-m-01 00:00:01', strtotime($date));
							$OrderDeliveryDateTo = date("Y-m-t 23:59:59", strtotime($date));
							$dt = array('From' => $OrderDeliveryDateFrom, 'To' => $OrderDeliveryDateTo);
							array_push($searchRangeArr, $dt);
						}
						else if(isset($MonthArr[0]) && $MonthArr[0] != '') {
							$date1 = $MonthArr[0].'-01-01 00:00:01';
							$date2 = $MonthArr[0].'-12-31 23:59:59';
							$OrderDeliveryDateFrom = date('Y-m-01 00:00:01', strtotime($date1));
							$OrderDeliveryDateTo = date("Y-m-t 23:59:59", strtotime($date2));
							$dt = array('From' => $OrderDeliveryDateFrom, 'To' => $OrderDeliveryDateTo);
							array_push($searchRangeArr, $dt);
						}
					}
				}
			}
		}

		if($OrderStore!=''){
			$stores = array($OrderStore);
		} else {
			$stores = array('Temp', 'Equine', 'Amazon', 'Bodi4life', 'Bodi2business', 'Ebay', 'BodiShop', 'Etsy');
		}
		$orders = array();

		foreach ($stores as $store) {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerTemplateDir = "../../bodiforbusiness/retail/";
			$Customertemplate = $this->loadFile($customerTemplateDir."template.json");

			if($OrderStatus == 'Cart' || $OrderStatus == '' || $store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop' || $store=='Temp' )
			{
				$fileNameArr = array();
				$filePath = $store.'Cart';
				if (file_exists($filePath.'/')) {
					$fileNameArr = preg_grep("/.*\.json$/", scandir($filePath.'/')); //Read Orders folder
				}
				if(!empty($fileNameArr)) {
					foreach($fileNameArr as $fileNameTemp) {
						$fileName = str_replace('.json','',$fileNameTemp);
						$fileData = $this->loadInfoByStore($store, $fileName);
						if($store == 'Ebay' || $store == 'Etsy' || $store == 'Amazon' || $store == 'BodiShop') {
							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(isset($order['OrderStatus']) && ($order['OrderStatus']== $OrderStatus || $OrderStatus == '')) {
						        					if($order['OrderStatus'] == 'Cart'){
														$lastModifiedOn = filemtime('../'.$store.'/'.$fileName.'.json');
														$order['OrderDateShow'] = date('Y-m-d h:i A', $lastModifiedOn);
														$order['OrderDate'] = date('Y-m-d H:i:s', $lastModifiedOn);
													}
													else {
														if($order['OrderDeliveryDate']!=''){
															$order['OrderDeliveryDate'] = date('Y-m-d', strtotime($order['OrderDeliveryDate']));
														}

														$order['OrderDateShow'] = $order['OrderDate'];
							        					if(isset($order['OrderDate']) && $order['OrderDate'] != ''){
															$order['OrderDateShow'] = date('Y-m-d h:i A', strtotime($order['OrderDate']));
														}
													}

													if($order['OrderDate'] != '' && !empty($searchRangeArr)) {
														$dateFound = false;
														foreach($searchRangeArr as $searchRange) {
															$From =  $searchRange['From'];
															$To =  $searchRange['To'];
															if($order['OrderDate'] >= $From && $order['OrderDate'] <= $To){
																$dateFound = true;
																break;
															}
														}
														if(!$dateFound) {
															continue;
														}
													}
													$order['OrderStore'] = $store;
													$order['filePath'] = $filePath;
													$order['fileName'] = $fileName;
							        				$orders[] = $order;
												}
						        			}
										}
									}
								}
							}
						}
						else if($store == 'Temp') {
							if(isset($fileData['Order']) && is_array($fileData['Order'])) {
			        			foreach ($fileData['Order'] as $order) {
			        				if($order['OrderStatus']== $OrderStatus || $OrderStatus == '') {
										$order['OrderDateShow'] = $order['OrderDate'];
			        					if(isset($order['OrderDate']) && $order['OrderDate'] != ''){
											$order['OrderDateShow'] = date('Y-m-d h:i A', strtotime($order['OrderDate']));
											if($order['OrderDate'] != '' && !empty($searchRangeArr)) {
												$dateFound = false;
												foreach($searchRangeArr as $searchRange) {
													$From =  $searchRange['From'];
													$To =  $searchRange['To'];
													if($order['OrderDate'] >= $From && $order['OrderDate'] <= $To){
														$dateFound = true;
														break;
													}
												}
												if(!$dateFound) {
													continue;
												}
											}
										}
										$order['OrderStore'] = $store;
										$order['filePath'] = $filePath;
										$order['fileName'] = $fileName;
				        				$orders[] = $order;
									}
			        			}
							}
						}
						else {
							if(isset($fileData['Order']) && is_array($fileData['Order'])) {
			        			foreach ($fileData['Order'] as $order) {
			        				if($order['OrderStatus']== $OrderStatus || $OrderStatus == '') {
			        					if($order['OrderStatus'] == 'Cart'){
											$lastModifiedOn = filemtime('../'.$store.'/'.$fileName.'.json');
											$order['OrderDateShow'] = date('Y-m-d h:i A', $lastModifiedOn);
											$order['OrderDate'] = date('Y-m-d H:i:s', $lastModifiedOn);
										}
										else {
											$order['OrderDateShow'] = $order['OrderDate'];
				        					if(isset($order['OrderDate']) && $order['OrderDate'] != ''){
												$order['OrderDateShow'] = date('Y-m-d h:i A', strtotime($order['OrderDate']));
											}
										}
										if($order['OrderDate'] != '' && !empty($searchRangeArr)) {
											$dateFound = false;
											foreach($searchRangeArr as $searchRange) {
												$From =  $searchRange['From'];
												$To =  $searchRange['To'];
												if($order['OrderDate'] >= $From && $order['OrderDate'] <= $To){
													$dateFound = true;
													break;
												}
											}
											if(!$dateFound) {
												continue;
											}
										}
										$order['OrderStore'] = $store;
										$order['filePath'] = $filePath;
										$order['fileName'] = $fileName;
				        				$orders[] = $order;
									}
			        			}
							}

						}

					}
				}
			}
			if($OrderStatus != 'Cart' || $OrderStatus == ''){
				//Read Log---
				$customerLogData = $this->loadFile($customerInfoDir.'_log.json');
				if(!empty($customerLogData)){
					foreach($customerLogData as $customerLogRow) {
						if (!is_array($customerLogRow['OrderActive'])) {
							$customerLogRow['OrderActive'] = array();
						}
						if($OrderStatus !='' && !in_array($OrderStatus, $customerLogRow['OrderActive'])){
							continue;
						}
						//Read from customer file---
						$filePath = $store;
						$fileName = $customerLogRow['CustomerID'];
						$customerInfo = $this->loadFile($customerInfoDir.$fileName.'.json');
						if(isset($customerInfo['Order']) && is_array($customerInfo['Order'])) {
		        			foreach ($customerInfo['Order'] as $orderKey => $order) {
		        				if($order['OrderStatus'] == $OrderStatus || $OrderStatus == '') {
									$order['OrderDateShow'] = $order['OrderDate'];
		        					if(isset($order['OrderDate']) && $order['OrderDate'] != ''){
										$order['OrderDateShow'] = date('Y-m-d h:i A', strtotime($order['OrderDate']));
									}

									if($order['OrderDate'] != '' && !empty($searchRangeArr)) {
										$dateFound = false;
										foreach($searchRangeArr as $searchRange) {
											$From =  $searchRange['From'];
											$To =  $searchRange['To'];
											if($order['OrderDate'] >= $From && $order['OrderDate'] <= $To){
												$dateFound = true;
												break;
											}
										}
										if(!$dateFound) {
											continue;
										}
									}

									$order['OrderStore'] = $store;
									$order['filePath'] = $filePath;
									$order['fileName'] = $fileName;
			        				$orders[] = $order;
								}
		        			}
						}
					}
				}
			}
		}
		$orders = $this->msort($orders, 'OrderDateShow');
		$setting = '';
		return array(
			'orders' => $orders,
			'setting' => $this->inventory->loadJson($this->settingPath),
			'supplierLog' => $this->inventory->loadJson($this->supplierLogPath),
		);
	}

	public function getInventoryListData(){
		$inventoryFiles = $this->inventory->getList();
		$inventories = array();
		foreach ($inventoryFiles as $filename) {
			array_push($inventories,$this->inventory->removeExt($filename));
		}
		return array(
			'InventoryList' => $inventories
		);
	}
	public function sendPHPmailerMail($emailSendArray) {
		include_once('../../php/PHPMailer/src/Exception.php');
		include_once('../../php/PHPMailer/src/PHPMailer.php');
		include_once('../../php/PHPMailer/src/SMTP.php');

		$emailSendArray['FromEmail'] = 'sales@bodiforlife.com';
		$emailSendArray['FromName'] = 'Bodi For Life';

		$emailSendArray['Subject'] = $emailSendArray['Subject']!=''?$emailSendArray['Subject']:'Bodi4life::N/A';
		$emailSendArray['Body'] = $emailSendArray['Body']!=''?$emailSendArray['Body']:'';

		$mail = new PHPMailer;
		$mail->isSendmail();
		$mail->IsHTML(true);
		$mail->CharSet = 'UTF-8';
		$mail->WordWrap = 50;

		if(isset($emailSendArray['ToAddress']) && !empty($emailSendArray['ToAddress'])){
			foreach($emailSendArray['ToAddress'] as $To){
				if($To != ''){
					$mail->AddAddress($To);
				}
			}
		}

		if(isset($emailSendArray['AddAttachment']) && !empty($emailSendArray['AddAttachment'])) {
			foreach($emailSendArray['AddAttachment'] as  $AttachmentData) {
				if($AttachmentData['fileName'] != ''){
					$mail->AddAttachment($AttachmentData['fileUrl'], $AttachmentData['fileName']);
				} else {
					$mail->AddAttachment($AttachmentData['fileUrl']);
				}
			}
		}

		$mail->Subject = $emailSendArray['Subject'];
		$mail->Body    = $emailSendArray['Body'];
		$mail->AltBody = '';
		if($emailSendArray['FromName']!= '') {
			$mail->setFrom($emailSendArray['FromEmail'], $emailSendArray['FromName']);
		}
		else {
			$mail->setFrom($emailSendArray['FromEmail']);
		}
		if(isset($emailSendArray['ReplyTo']) && $emailSendArray['ReplyTo'] != '') {
			$mail->addReplyTo($emailSendArray['ReplyTo']);
		}

		if($mail->Send()) {
			return true;
		} else {
			return false;
		}
	}
	public function SendShippingMail($requestData){
		$result = array('SUCCESS' => false, 'DATA' => '', 'ERROR' => '');
		$shippingResdata = array();
		$file = $requestData['file'];
		$OrderDate = $requestData['OrderDate'];
		$store = $requestData['OrderRetailStore'];

		if($store == 'BodiStaff') {
			$customerInfoDir = "../Staff/Contact/";
			$customerTemplateDir = "../Staff/Contact/";
			$Customertemplate = $this->loadFile($customerTemplateDir."contact-template.json");
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerTemplateDir = "../../bodiforbusiness/retail/";
			$Customertemplate = $this->loadFile($customerTemplateDir."template.json");
		}

		$html = file_get_contents('../../bodiforbusiness/retail/Order-Email-Custom.html');
		if($store=='Bodi4life' || $store == 'Bodi2business' || $store=='Equine'){
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			$CustomerName = $customerInfo['CustomerName'];
			$CustomerEmail = $customerInfo['Email'];
			if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
				foreach ($customerInfo['Order'] as $key => $order) {
					$dateToChk = $order['OrderDate'];
					if ($dateToChk == $OrderDate) {
						$OrderAddressType = $order['OrderAddressType'];

						$PaymentMode = 'Card Payment';
						if($order['OrderPaymentType'] == 'Paypal') {
							$PaymentMode = 'Paypal';
						}
						$OrderCarrier = $order['OrderCarrier'];
						$OrderCarrierService = $order['OrderCarrierService'];
						if($OrderCarrier==''){
							$CareerType = $OrderCarrierService;
						}
						else {
							$CareerType = $OrderCarrier.' '.$OrderCarrierService;
						}

						$OrderAddressType = $order['OrderAddressType'];

						$Addresses = $customerInfo['Addresses'];
						$AddressName = $customerInfo['CustomerName'];
						$FullAddress = '';

						if(!empty($Addresses)){
							foreach($Addresses as $addressesData){
								if($addressesData['AddressZip'] == $OrderAddressType){
									$AddressName = $addressesData['AddressName'];
									if(isset($addressesData['AddressDetail']) && $addressesData['AddressDetail'] != '') {
										$FullAddress .= $addressesData['AddressDetail']. '<br />';
									}
									if(isset($addressesData['AddressStreet']) && $addressesData['AddressStreet'] != '') {
										$FullAddress .= $addressesData['AddressStreet']. ', ';
									}
									if(isset($addressesData['AddressUnit']) && $addressesData['AddressUnit'] != '') {
										$FullAddress .= $addressesData['AddressUnit']. ', ';
									}
									if(isset($addressesData['AddressBuilding']) && $addressesData['AddressBuilding'] != '') {
										$FullAddress .= $addressesData['AddressBuilding'];
									}
									$FullAddress .= '<br />';
									if(isset($addressesData['AddressCity']) && $addressesData['AddressCity'] != '') {
										$FullAddress .= $addressesData['AddressCity']. ', ';
									}
									if(isset($addressesData['AddressState']) && $addressesData['AddressState'] != '') {
										$AddressState = $this->getStateValueByCode($addressesData['AddressState']);
										if($AddressState){
											$FullAddress .= $AddressState. ', ';
										} else {
											$FullAddress .= $addressesData['AddressState']. ', ';
										}

									}
									if(isset($addressesData['AddressZip']) && $addressesData['AddressZip'] != '') {
										$FullAddress .= $addressesData['AddressZip'];
									}
									$FullAddress .= '<br />';
									if(isset($addressesData['AddressCountry']) && $addressesData['AddressCountry'] != '') {
										$AddressCountry = $this->getCountryValueByCode($addressesData['AddressCountry']);
										if($AddressCountry){
											$FullAddress .= $AddressCountry;
										}
										else {
											$FullAddress .= $addressesData['AddressCountry'];
										}
									}
									break;
								}
							}
						}

						$product_details = '';
						$product_details .= '<table cellpadding="5" cellspacing="0" width="100%"  border="1px" BORDERCOLOR="#d2d2d2" BORDERCOLORLIGHT="#d2d2d2" BORDERCOLORDARK="#d2d2d2" style="border: 1px solid #d2d2d2;">
		                    <tr>
		                        <th align="left" style="width: 66%">Product</th>
		                        <th style="width: 12px">Qty</th>
		                    </tr>';
						$OrderItems = $order['OrderItems'];
		                foreach($OrderItems as $ItemKey=>$Item) {
							$OrderProduct = $Item['OrderProduct'];
							$OrderAttribute = $Item['OrderAttribute'];
							$OrderQuantity = $Item['OrderQuantity'];
							$product_details .= '<tr bgcolor="#f8f8f8">
		                        <td style="width: 66%">'.$OrderProduct.' ('.$OrderAttribute.')</td>
		                        <td align="center" style="width: 12px">'.$OrderQuantity.'</td>
		                    </tr>';
						}
						$product_details .= '</table>';

						$OrderTracking = '';
						if(isset($order['OrderTracking']) && is_array($order['OrderTracking']) && !empty($order['OrderTracking'])) {
							foreach($order['OrderTracking'] as $OrderTrackingT){
								if($OrderTrackingT != '') {
									$OrderTracking = $OrderTrackingT;
									break;
								}
							}
						}
						$OrderCarrier = $order['OrderCarrier'];
						$setting = $this->inventory->loadJson($this->settingPath);
						$trackingUrl =$setting[$OrderCarrier]?$setting[$OrderCarrier].$OrderTracking:'#';
						$OrderTrackingHtml = '<a href="'.$trackingUrl.'" target="_blank">'.$OrderTracking.'</a>';
						$html = str_replace('[TRACKING_URL]', $OrderTrackingHtml, $html);
						$html = str_replace('[ORDER_DATE]', $OrderDate, $html);
						$html = str_replace('[PAYMENT_TYPE]', $PaymentMode, $html);
						$html = str_replace('[CAREER_TYPE]', $CareerType, $html);
						$html = str_replace('[ADDRESS_NAME]', $AddressName, $html);
						$html = str_replace('[ORDER_ADDRESS]', $FullAddress, $html);
						$html = str_replace('[PRODUCT_DETAILS]', $product_details, $html);
						$html = str_replace('[CUSTOMER_MSG]', 'No message', $html);
						//echo $html;//die('STOP');
						if($CustomerEmail!=''){
							$emailSendArray = array();
							$emailSendArray['Subject'] = 'Shipping Confirmation Bodi For Life';
							$emailSendArray['Body'] = $html;
							$emailSendArray['ToAddress'] = array($CustomerEmail);
							//pr($emailSendArray);
							$returnData = $this->sendPHPmailerMail($emailSendArray);
							return $returnData;
						}
						break;
					}
				}
			}

		}
		else if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop') {
			$filename = $store. '/' . $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(count($orderInfo)>0){
				foreach($orderInfo as $OrderIndex => $orderInfoRow){
					foreach($orderInfoRow['Order'] as $key => $order) {
						if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
							$OrderAddressType = $order['OrderAddressType'];

							$PaymentMode = 'Card Payment';
							if($order['OrderPaymentType'] == 'Paypal') {
								$PaymentMode = 'Paypal';
							}
							$OrderCarrier = $order['OrderCarrier'];
							$OrderCarrierService = $order['OrderCarrierService'];
							if($OrderCarrier==''){
								$CareerType = $OrderCarrierService;
							}
							else {
								$CareerType = $OrderCarrier.' '.$OrderCarrierService;
							}

							$OrderAddressType = $order['OrderAddressType'];

							$CustomerEmail = $orderInfoRow['Email'];
							$Addresses = $orderInfoRow['Addresses'];
							$AddressName = $orderInfoRow['CustomerName'];
							$FullAddress = '';

							if(!empty($Addresses)){
								foreach($Addresses as $addressesData){
									if($addressesData['AddressStreet'] == $OrderAddressType){
										$AddressName = $addressesData['AddressName'];
										if(isset($addressesData['AddressDetail']) && $addressesData['AddressDetail'] != '') {
											$FullAddress .= $addressesData['AddressDetail']. '<br />';
										}
										if(isset($addressesData['AddressStreet']) && $addressesData['AddressStreet'] != '') {
											$FullAddress .= $addressesData['AddressStreet']. ', ';
										}
										if(isset($addressesData['AddressUnit']) && $addressesData['AddressUnit'] != '') {
											$FullAddress .= $addressesData['AddressUnit']. ', ';
										}
										if(isset($addressesData['AddressBuilding']) && $addressesData['AddressBuilding'] != '') {
											$FullAddress .= $addressesData['AddressBuilding'];
										}
										$FullAddress .= '<br />';
										if(isset($addressesData['AddressCity']) && $addressesData['AddressCity'] != '') {
											$FullAddress .= $addressesData['AddressCity']. ', ';
										}
										if(isset($addressesData['AddressState']) && $addressesData['AddressState'] != '') {
											$AddressState = $this->getStateValueByCode($addressesData['AddressState']);
											if($AddressState){
												$FullAddress .= $AddressState. ', ';
											} else {
												$FullAddress .= $addressesData['AddressState']. ', ';
											}

										}
										if(isset($addressesData['AddressZip']) && $addressesData['AddressZip'] != '') {
											$FullAddress .= $addressesData['AddressZip'];
										}
										$FullAddress .= '<br />';
										if(isset($addressesData['AddressCountry']) && $addressesData['AddressCountry'] != '') {
											$AddressCountry = $this->getCountryValueByCode($addressesData['AddressCountry']);
											if($AddressCountry){
												$FullAddress .= $AddressCountry;
											}
											else {
												$FullAddress .= $addressesData['AddressCountry'];
											}
										}
										break;
									}
								}
							}

							$product_details = '';
							$product_details .= '<table cellpadding="5" cellspacing="0" width="100%"  border="1px" BORDERCOLOR="#d2d2d2" BORDERCOLORLIGHT="#d2d2d2" BORDERCOLORDARK="#d2d2d2" style="border: 1px solid #d2d2d2;">
			                    <tr>
			                        <th align="left" style="width: 66%">Product</th>
			                        <th style="width: 12px">Qty</th>
			                    </tr>';
							$OrderItems = $order['OrderItems'];
			                foreach($OrderItems as $ItemKey=>$Item) {
								$OrderProduct = $Item['OrderProduct'];
								$OrderAttribute = $Item['OrderAttribute'];
								$OrderQuantity = $Item['OrderQuantity'];
								$product_details .= '<tr bgcolor="#f8f8f8">
			                        <td style="width: 66%">'.$OrderProduct.' ('.$OrderAttribute.')</td>
			                        <td align="center" style="width: 12px">'.$OrderQuantity.'</td>
			                    </tr>';
							}
							$product_details .= '</table>';

							$OrderTracking = '';
							if(isset($order['OrderTracking']) && is_array($order['OrderTracking']) && !empty($order['OrderTracking'])) {
								foreach($order['OrderTracking'] as $OrderTrackingT){
									if($OrderTrackingT != '') {
										$OrderTracking = $OrderTrackingT;
										break;
									}
								}
							}
							$OrderCarrier = $order['OrderCarrier'];
							$setting = $this->inventory->loadJson($this->settingPath);
							$trackingUrl =$setting[$OrderCarrier]?$setting[$OrderCarrier].$OrderTracking:'#';
							$OrderTrackingHtml = '<a href="'.$trackingUrl.'" target="_blank">'.$OrderTracking.'</a>';
							$html = str_replace('[TRACKING_URL]', $OrderTrackingHtml, $html);
							$html = str_replace('[ORDER_DATE]', $OrderDate, $html);
							$html = str_replace('[PAYMENT_TYPE]', $PaymentMode, $html);
							$html = str_replace('[CAREER_TYPE]', $CareerType, $html);
							$html = str_replace('[ADDRESS_NAME]', $AddressName, $html);
							$html = str_replace('[ORDER_ADDRESS]', $FullAddress, $html);
							$html = str_replace('[PRODUCT_DETAILS]', $product_details, $html);
							$html = str_replace('[CUSTOMER_MSG]', 'No message', $html);
							//echo $html;//die('STOP');
							if($CustomerEmail!=''){
								$emailSendArray = array();
								$emailSendArray['Subject'] = 'Shipping Confirmation Bodi For Life';
								$emailSendArray['Body'] = $html;
								$emailSendArray['ToAddress'] = array($CustomerEmail);
								//pr($emailSendArray);
								$returnData = $this->sendPHPmailerMail($emailSendArray);
								return $returnData;
							}

							break;
						}
					}
				}
			}
		}
		return $result;
	}
	private function getStateValueByCode($Code=null){
		if(!$Code) {
			return false;
		}
		$stateArr = array('AL'=>'Alabama', 'AK'=>'Alaska', 'AZ'=>'Arizona', 'AR'=>'Arkansas', 'CA'=>'California', 'CO'=>'Colorado', 'CT'=>'Connecticut', 'DE'=>'Delaware', 'DC'=>'District Of Columbia', 'FL'=>'Florida', 'GA'=>'Georgia', 'HI'=>'Hawaii', 'ID'=>'Idaho', 'IL'=>'Illinois', 'IN'=>'Indiana', 'IA'=>'Iowa', 'KS'=>'Kansas', 'KY'=>'Kentucky', 'LA'=>'Louisiana', 'ME'=>'Maine', 'MD'=>'Maryland', 'MA'=>'Massachusetts', 'MI'=>'Michigan', 'MN'=>'Minnesota', 'MS'=>'Mississippi', 'MO'=>'Missouri', 'MT'=>'Montana', 'NE'=>'Nebraska', 'NV'=>'Nevada', 'NH'=>'New Hampshire', 'NJ'=>'New Jersey', 'NM'=>'New Mexico', 'NY'=>'New York', 'NC'=>'North Carolina', 'ND'=>'North Dakota', 'OH'=>'Ohio', 'OK'=>'Oklahoma', 'OR'=>'Oregon', 'PA'=>'Pennsylvania', 'RI'=>'Rhode Island', 'SC'=>'South Carolina', 'SD'=>'South Dakota', 'TN'=>'Tennessee', 'TX'=>'Texas', 'UT'=>'Utah', 'VT'=>'Vermont', 'VA'=>'Virginia', 'WA'=>'Washington', 'WV'=>'West Virginia', 'WI'=>'Wisconsin', 'WY'=>'Wyoming', 'AB'=>'Alberta', 'BC'=>'British Columbia', 'MB'=>'Manitoba', 'NB'=>'New Brunswick', 'NL'=>'Newfoundland and Labrador', 'NS'=>'Nova Scotia', 'ON'=>'Ontario', 'PE'=>'Prince Edward Island', 'QC'=>'Quebec', 'SK'=>'Saskatchewan', 'NT'=>'Northwest Territories', 'NU'=>'Nunavut', 'YT'=>'Yukon');
		if(isset($stateArr[$Code])){
			return $stateArr[$Code];
		}
		return false;
	}
	private function getCountryValueByCode($Code=null){
		if(!$Code) {
			return false;
		}
		$countryArr = array('USA' => 'United States', 'CAN' => 'Canada', 'AUS' => 'Australia', 'AUT' => 'Austria', 'BEL' => 'Belgium', 'BRA' => 'Brazil', 'BGR' => 'Bulgaria', 'CHL' => 'Chile', 'CHN' => 'China', 'COL' => 'Colombia', 'CRI' => 'Costa Rica', 'CZE' => 'Czech Republic', 'DNK' => 'Denmark', 'ECU' => 'Ecuador', 'EGY' => 'Egypt', 'DEU' => 'Germany', 'GRC' => 'Greece', 'HKG' => 'Hong Kong', 'HUN' => 'Hungary', 'ISL' => 'Iceland', 'IND' => 'India', 'ISR' => 'Israel', 'ITA' => 'Italy', 'JPN' => 'Japan', 'KOR' => 'Korea, Republic of', 'KWT' => 'Kuwait', 'LIE' => 'Liechtenstein', 'LUX' => 'Luxembourg', 'MEX' => 'Mexico', 'MCO' => 'Monaco', 'NLD' => 'Netherlands', 'NOR' => 'Norway', 'PER' => 'Peru', 'POL' => 'Poland', 'PRT' => 'Portugal', 'PRI' => 'Puerto Rico', 'ROU' => 'Romania', 'RUS' => 'Russian Federation', 'SAU' => 'Saudi Arabia', 'ESP' => 'Spain', 'SWE' => 'Sweden', 'CHE' => 'Switzerland', 'TUR' => 'Turkey', 'UKR' => 'Ukraine', 'GBR' => 'United Kingdom');
		if(isset($countryArr[$Code])){
			return $countryArr[$Code];
		}
		return false;
	}
	public function getShippingRates($requestData){
		$result = array('SUCCESS' => false, 'DATA' => '', 'ERROR' => '');
		
		if(!isset($_SESSION['stamps_access_token'])) {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Login Session.';
			return $result;
		}
		$shippingResdata = array();
		$file = $requestData['file'];
		$OrderDate = $requestData['OrderDate'];
		$store = $requestData['OrderRetailStore'];
		$OrderBoxsize = $requestData['OrderBoxsize'];
		$OrderCarrier = $requestData['OrderCarrier'];
		$OrderCarrierService = $requestData['OrderCarrierService'];
		$shipweightTotal = $requestData['shipweightTotal'];
		if($OrderCarrierService != 'ground' && $OrderCarrierService != 'priority' && $OrderCarrierService != 'express' && $OrderCarrierService != 'usps-international') {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Service.';
			return $result;
		}
		
		if($store == 'BodiStaff') {
			$customerInfoDir = "../Staff/Contact/";
			$customerTemplateDir = "../Staff/Contact/";
			$Customertemplate = $this->loadFile($customerTemplateDir."contact-template.json");
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerTemplateDir = "../../bodiforbusiness/retail/";
			$Customertemplate = $this->loadFile($customerTemplateDir."template.json");
		}
		$to_address = array();
		$package = array();
		if($store=='Bodi4life' || $store == 'Bodi2business' || $store=='Equine'){
			//For customer file----
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
				foreach ($customerInfo['Order'] as $key => $order) {
					$dateToChk = $order['OrderDate'];
					if ($dateToChk == $OrderDate) {
						$OrderAddressType = $order['OrderAddressType'];
						
						if(isset($customerInfo['Addresses']) && !empty($customerInfo['Addresses'])) {
							foreach ($customerInfo['Addresses'] as $Addkey => $addressArr) {
								if($addressArr['AddressZip'] == $OrderAddressType) {
									$to_address = array(
										"company_name" => "",
										"name" => $addressArr['AddressName'],
										"address_line1" => $addressArr['AddressStreet'],
										"address_line2" => $addressArr['AddressUnit'],
										"address_line3" => "",
										"city" => $addressArr['AddressCity'],
										"state_province" => $addressArr['AddressState'],
										"postal_code" => $addressArr['AddressZip'],
										"country_code" => isset($this->countryCode[$addressArr['AddressCountry']])?$this->countryCode[$addressArr['AddressCountry']]:$addressArr['AddressCountry'], //Only 2 character
										"phone" => $customerInfo['Phone'],
										"email" => $customerInfo['Email'],
										"residential_indicator" => "Yes"
									);
									break;
								}
							}
						}
						if(isset($shipweightTotal) && $shipweightTotal>0) {
							$OrderShipWeightTotal = $shipweightTotal;
						}
						else {
							$OrderShipWeightTotal = $order['OrderShipWeightTotal'];
						}
						$OrderBoxsizeArr = explode(',',$OrderBoxsize);
						$length = isset($OrderBoxsizeArr[0])?$OrderBoxsizeArr[0]:0;
						$width = isset($OrderBoxsizeArr[1])?$OrderBoxsizeArr[1]:0;
						$height = isset($OrderBoxsizeArr[2])?$OrderBoxsizeArr[2]:0;
						$boxSize = isset($OrderBoxsizeArr[3])?$OrderBoxsizeArr[3]:0;

						$WeightOZ = (int)$OrderShipWeightTotal;
						if($boxSize > 0) {
							$WeightOZ += (int)$boxSize;
						}


						$package = array(
							"packaging_type" => "package",
							"weight" => $WeightOZ,
							"weight_unit" => "ounce",
							"length" => $length,
							"width" => $width,
							"height" => $height,
							"dimension_unit" => "inch",
							"OrderShipWeightTotal" => $OrderShipWeightTotal
						);
						
						break;
					}
				}
			}
		}
		else if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop') {
			$filename = $store. '/' . $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(count($orderInfo)>0){
				foreach($orderInfo as $OrderIndex => $orderInfoRow){
					if(isset($orderInfoRow['Order']) && !empty($orderInfoRow['Order'])) {
						foreach($orderInfoRow['Order'] as $key => $order) {
							if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
								$OrderAddressType = $order['OrderAddressType'];						
								if(isset($orderInfoRow['Addresses']) && !empty($orderInfoRow['Addresses'])) {
									foreach ($orderInfoRow['Addresses'] as $Addkey => $addressArr) {
										if($addressArr['AddressStreet'] == $OrderAddressType || $addressArr['AddressZip'] == $OrderAddressType) {
											$to_address = array(
												"company_name" => "",
												"name" => $addressArr['AddressName'],
												"address_line1" => $addressArr['AddressStreet'],
												"address_line2" => $addressArr['AddressUnit'],
												"address_line3" => "",
												"city" => $addressArr['AddressCity'],
												"state_province" => $addressArr['AddressState'],
												"postal_code" => $addressArr['AddressZip'],
												"country_code" => isset($this->countryCode[$addressArr['AddressCountry']])?$this->countryCode[$addressArr['AddressCountry']]:$addressArr['AddressCountry'],
												"phone" => $orderInfoRow['Phone'],
												"email" => $orderInfoRow['Email'],
												"residential_indicator" => "Yes"
											);
											break;
										}
									}
										
								}
								if(isset($shipweightTotal) && $shipweightTotal>0) {
									$OrderShipWeightTotal = $shipweightTotal;
								}
								else {
									$OrderShipWeightTotal = $order['OrderShipWeightTotal'];
								}
								$OrderBoxsizeArr = explode(',',$OrderBoxsize);
								$length = isset($OrderBoxsizeArr[0])?$OrderBoxsizeArr[0]:0;
								$width = isset($OrderBoxsizeArr[1])?$OrderBoxsizeArr[1]:0;
								$height = isset($OrderBoxsizeArr[2])?$OrderBoxsizeArr[2]:0;
								$boxSize = isset($OrderBoxsizeArr[3])?$OrderBoxsizeArr[3]:0;

								$WeightOZ = (int)$OrderShipWeightTotal;
								if($boxSize > 0) {
									$WeightOZ += (int)$boxSize;
								}
								$package = array(
									"packaging_type" => "package",
									"weight" => $WeightOZ,
									"weight_unit" => "ounce",
									"length" => $length,
									"width" => $width,
									"height" => $height,
									"dimension_unit" => "inch",
									"OrderShipWeightTotal" => $OrderShipWeightTotal
								);
								
								break;
								
							}
						}
					}
				}
			}
		}

		
		if($OrderCarrierService == 'usps-international'){
			$service_typeArr = array("globalpost_standard_international", "globalpost_plus");
		}
		else {
			$service_typeArr = array("usps_ground_advantage", "usps_priority_mail", "usps_priority_mail_express", "ups_ground_saver", "ups_ground","ups_next_day_air_saver");
		}

		$packaging_type = 'package';
		foreach($service_typeArr as $service_type){
			$packageTemp = $package;
			
			unset($packageTemp['OrderShipWeightTotal']);
			$packageTemp['packaging_type'] = $packaging_type;
			$options = array();
			$options['to_address'] = $to_address;
			$options['package'] = $packageTemp;
			$options['service_type'] = $service_type;
			$options['delivery_confirmation_type'] = "tracking";
			$options['insurance'] = array(
				"insurance_provider" => "stamps_com",
				"insured_value" => array(
					"amount" => 0,
					"currency" => "usd"
				)
			);
			$StampsData = $this->StampsModel->getShippingRates($options);
			/* pr($options);
			echo "====Result=====";
			pr($StampsData);
			die('SS'); */
			if(!$StampsData) {
				$result['SUCCESS'] = false;
				$result['ERROR'] = 'Invalid Session.';
				return $result;
			}
			else if(!empty($StampsData)) {
				if(isset($StampsData['errors'])){
					$errorMsg = '';
					if(!empty($StampsData['errors'])) {
						foreach($StampsData['errors'] as $error) {
							$temp = array(
								'status' => 'error',
								'service_type' => $service_type,
								'packaging_type' => $packaging_type,
								'shipment_cost' => 0.00,
								'error_code' => $error['error_code'],
								'error_message' => $error['error_message']
							);
							array_push($shippingResdata, $temp);
							//$errorMsg .= $error['error_code'].' - '.$error['error_message'].'. ';
						}
					}
					else {
						$errorMsg = 'Invalid Session.';
						$temp = array(
							'status' => 'error',
							'service_type' => $service_type,
							'packaging_type' => $packaging_type,
							'shipment_cost' => 0.00,
							'error_code' => '',
							'error_message' => $errorMsg
						);
						array_push($shippingResdata, $temp);
					}
				}
				else {
					foreach($StampsData as $StampsRow) {
						$shipment_cost = isset($StampsRow['shipment_cost']['total_amount'])?$StampsRow['shipment_cost']['total_amount']:0.00;
						$currency = isset($StampsRow['shipment_cost']['currency'])?$StampsRow['shipment_cost']['currency']:'usd';
						
						$service_type = $StampsRow['service_type'];
						$packaging_type = $StampsRow['packaging_type'];
						
						$service_type_show = '';
						if($service_type == 'usps_ground_advantage') {
							$service_type_show = 'usps_ground';
						}
						else if($service_type == 'usps_priority_mail' && $packaging_type == 'package') {
							$service_type_show = 'usps_priority';
						}
						else if($service_type == 'usps_priority_mail_express' && $packaging_type == 'package') {
							$service_type_show = 'usps_express';
						}
						else if($service_type == 'usps_priority_mail_international' && $packaging_type == 'package') {
							$service_type_show = 'Int-Priority';
						}
						else if($service_type == 'globalpost_standard_international' && $packaging_type == 'package') {
							$service_type_show = 'Global Standard';
						}
						else if($service_type == 'globalpost_plus' && $packaging_type == 'package') {
							$service_type_show = 'Global Plus';
						}

						else if($service_type == 'ups_ground_saver' && $packaging_type == 'package') {
							$service_type_show = 'ups_ground_saver';
						}
						else if($service_type == 'ups_ground' && $packaging_type == 'package') {
							$service_type_show = 'ups_priority';
						}
						else if($service_type == 'ups_next_day_air_saver' && $packaging_type == 'package') {
							$service_type_show = 'ups_express';
						}			
						
						$temp = array(
							'carrier' => $StampsRow['carrier'],
							'service_type' => $service_type,
							'packaging_type' => $packaging_type,
							'service_type_show' => $service_type_show,
							'shipment_cost' => number_format($shipment_cost,2),
							'currency' => $currency
						);
						array_push($shippingResdata, $temp);
					}
				}
			}
		}




		if(!empty($shippingResdata)){
			$shippingResdata = $this->msortASC($shippingResdata, 'shipment_cost');
			$result['SUCCESS'] = true;
			$result['DATA'] = $shippingResdata;
		}
		else {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Something went wrong!';
		}
		return $result;
	}
	public function getUpsShippingRates($requestData){
		$result = array('SUCCESS' => false, 'DATA' => '', 'ERROR' => '');

		if(!isset($_SESSION['ups_access_token'])) {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Login Session.';
			return $result;
		}
		$shippingResdata = array();
		$file = $requestData['file'];
		$OrderDate = $requestData['OrderDate'];
		$store = $requestData['OrderRetailStore'];
		$OrderBoxsize = $requestData['OrderBoxsize'];
		$OrderCarrier = $requestData['OrderCarrier'];
		$OrderCarrierService = $requestData['OrderCarrierService'];
		$shipweightTotal = $requestData['shipweightTotal'];
		if($OrderCarrierService != 'ground' && $OrderCarrierService != 'priority' && $OrderCarrierService != 'express' && $OrderCarrierService != 'usps-international') {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Service.';
			return $result;
		}

		if($store == 'BodiStaff') {
			$customerInfoDir = "../Staff/Contact/";
			$customerTemplateDir = "../Staff/Contact/";
			$Customertemplate = $this->loadFile($customerTemplateDir."contact-template.json");
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerTemplateDir = "../../bodiforbusiness/retail/";
			$Customertemplate = $this->loadFile($customerTemplateDir."template.json");
		}
		$to_address = array();
		$package = array();
		$WeightOZ = 0;
		$WeightLB = 0;
		if($store=='Bodi4life' || $store == 'Bodi2business' || $store=='Equine'){
			//For customer file----
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
				foreach ($customerInfo['Order'] as $key => $order) {
					$dateToChk = $order['OrderDate'];
					if ($dateToChk == $OrderDate) {
						$OrderAddressType = $order['OrderAddressType'];

						if(isset($customerInfo['Addresses']) && !empty($customerInfo['Addresses'])) {
							foreach ($customerInfo['Addresses'] as $Addkey => $addressArr) {
								if($addressArr['AddressZip'] == $OrderAddressType) {
									$AddressLine = array();
									if(isset($addressArr['AddressStreet']) && $addressArr['AddressStreet']!='') {
										$AddressLine[] = $addressArr['AddressStreet'];
									}
									if(isset($addressArr['AddressUnit']) && $addressArr['AddressUnit']!='') {
										$AddressLine[] = $addressArr['AddressUnit'];
									}
									$to_address = array(
										"Name" => $addressArr['AddressName'],
										"Address" => array(
											"AddressLine" => $AddressLine,
											"City" => $addressArr['AddressCity'],
											"StateProvinceCode" => $addressArr['AddressState'],
											"PostalCode" =>  $addressArr['AddressZip'],
											"CountryCode" => isset($this->countryCode[$addressArr['AddressCountry']])?$this->countryCode[$addressArr['AddressCountry']]:$addressArr['AddressCountry'], //Only 2 character
										)
									);
									break;
								}
							}
						}
						if(isset($shipweightTotal) && $shipweightTotal>0) {
							$OrderShipWeightTotal = $shipweightTotal;
						}
						else {
							$OrderShipWeightTotal = $order['OrderShipWeightTotal'];
						}
						$OrderBoxsizeArr = explode(',',$OrderBoxsize);
						$length = isset($OrderBoxsizeArr[0])?$OrderBoxsizeArr[0]:0;
						$width = isset($OrderBoxsizeArr[1])?$OrderBoxsizeArr[1]:0;
						$height = isset($OrderBoxsizeArr[2])?$OrderBoxsizeArr[2]:0;
						$boxSize = isset($OrderBoxsizeArr[3])?$OrderBoxsizeArr[3]:0;

						$WeightOZ = (int)$OrderShipWeightTotal;
						if($boxSize > 0) {
							$WeightOZ += (int)$boxSize;
						}
						$WeightLB = (float)Conversion::convertStockValue($WeightOZ, "oz", "lb");
						break;
					}
				}
			}
		}
		else if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop') {
			$filename = $store. '/' . $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(count($orderInfo)>0){
				foreach($orderInfo as $OrderIndex => $orderInfoRow){
					if(isset($orderInfoRow['Order']) && !empty($orderInfoRow['Order'])) {
						foreach($orderInfoRow['Order'] as $key => $order) {
							if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
								$OrderAddressType = $order['OrderAddressType'];
								if(isset($orderInfoRow['Addresses']) && !empty($orderInfoRow['Addresses'])) {
									foreach ($orderInfoRow['Addresses'] as $Addkey => $addressArr) {
										if($addressArr['AddressStreet'] == $OrderAddressType || $addressArr['AddressZip'] == $OrderAddressType) {
											$AddressLine = array();
											if(isset($addressArr['AddressStreet']) && $addressArr['AddressStreet']!='') {
												$AddressLine[] = $addressArr['AddressStreet'];
											}
											if(isset($addressArr['AddressUnit']) && $addressArr['AddressUnit']!='') {
												$AddressLine[] = $addressArr['AddressUnit'];
											}
											$to_address = array(
												"Name" => $addressArr['AddressName'],
												"Address" => array(
													"AddressLine" => $AddressLine,
													"City" => $addressArr['AddressCity'],
													"StateProvinceCode" => $addressArr['AddressState'],
													"PostalCode" =>  $addressArr['AddressZip'],
													"CountryCode" => isset($this->countryCode[$addressArr['AddressCountry']])?$this->countryCode[$addressArr['AddressCountry']]:$addressArr['AddressCountry'], //Only 2 character
												)
											);
											break;
										}
									}

								}
								if(isset($shipweightTotal) && $shipweightTotal>0) {
									$OrderShipWeightTotal = $shipweightTotal;
								}
								else {
									$OrderShipWeightTotal = $order['OrderShipWeightTotal'];
								}
								$OrderBoxsizeArr = explode(',',$OrderBoxsize);
								$length = isset($OrderBoxsizeArr[0])?$OrderBoxsizeArr[0]:0;
								$width = isset($OrderBoxsizeArr[1])?$OrderBoxsizeArr[1]:0;
								$height = isset($OrderBoxsizeArr[2])?$OrderBoxsizeArr[2]:0;
								$boxSize = isset($OrderBoxsizeArr[3])?$OrderBoxsizeArr[3]:0;

								$WeightOZ = (int)$OrderShipWeightTotal;
								if($boxSize > 0) {
									$WeightOZ += (int)$boxSize;
								}
								$WeightLB = (float)Conversion::convertStockValue($WeightOZ, "oz", "lb");
								break;
							}
						}
					}
				}
			}
		}

		//For All service
		/* $service_typeArr = array(
			"92" => "UPS SurePost - Less than 1lb",
			"93" => "UPS SurePost - 1lb or Greater",
			"03" => "UPS Ground",
			"02" => "2nd Day Air",
			"13" => "Next Day Air Saver"
		); */
		$service_typeArr = array(
			"92" => "UPS SurePost - Less than 1lb",
			"93" => "UPS SurePost - 1lb or Greater",
			"03" => "UPS Ground",
			"02" => "2nd Day Air",
			"13" => "Next Day Air Saver"
		);
		$ShipperNumberArr = array("C311A9", "286A26");

		$options = array();
		$options['to_address'] = $to_address;
		$options['length'] = $length;
		$options['width'] = $width;
		$options['height'] = $height;
		$options['Weight'] = '';
		$options['WeightUnitCode'] = '';
		$options['WeightUnitDesc'] = '';
		$options['ShipperNumber'] = '';


		$shippingResdata = array();
		foreach($service_typeArr as $ServiceCode => $ServiceDescription) {
			foreach($ShipperNumberArr as $ShipperNumber) {
				$options['ShipperNumber'] = $ShipperNumber;
					if($ServiceCode == '92' && $WeightLB >= 1) {
					continue;
				}
				if($ServiceCode == '93' && $WeightLB < 1) {
					continue;
				}
				$options['service_code'] = $ServiceCode;
				$options['service_description'] = $ServiceDescription;

				if($ServiceCode == '93' || $ServiceCode == '03' || $ServiceCode == '02' || $ServiceCode == '13') {
					$options['Weight'] = $WeightLB;
					$options['WeightUnitCode'] = 'LBS';
					$options['WeightUnitDesc'] = "Pounds";
				}
				else {
					$options['Weight'] = $WeightOZ;
					$options['WeightUnitCode'] = 'OZS';
					$options['WeightUnitDesc'] = "Ounces";
				}
				$UpsData = $this->UpsModel->getShippingRates($options);
				/* echo "------------------<br/>";
				echo "Service Code: ".$ServiceCode." - ".$ServiceDescription."<br/>";
				pr($options);
				pr($UpsData);
				//die('STOP'); */
				if(isset($UpsData['RateResponse']['Response']['ResponseStatus']['Code']) && $UpsData['RateResponse']['Response']['ResponseStatus']['Code'] == '1') {
					$UpsRow = $UpsData['RateResponse']['RatedShipment'];

					//pr($UpsData['RateResponse']['RatedShipment']['Service']);
					//pr($UpsData['RateResponse']);
					//$shipment_cost = isset($UpsRow['TotalCharges']['MonetaryValue'])?$UpsRow['TotalCharges']['MonetaryValue']:0.00;
					$shipment_cost = isset($UpsRow['NegotiatedRateCharges']['TotalCharge']['MonetaryValue'])?$UpsRow['NegotiatedRateCharges']['TotalCharge']['MonetaryValue']:0.00;
					if($shipment_cost == 0.00) {
						$shipment_cost = isset($UpsRow['TotalCharges']['MonetaryValue'])?$UpsRow['TotalCharges']['MonetaryValue']:0.00;
					}
					$currency = isset($UpsRow['TotalCharges']['CurrencyCode'])?$UpsRow['TotalCharges']['CurrencyCode']:'USD';
					$service_type_show = $ServiceDescription;

					$temp = array(
						'carrier' => "",
						'service_type' => $ServiceCode,
						'packaging_type' => "Packaging",
						'service_type_show' => $service_type_show,
						'shipment_cost' => number_format($shipment_cost,2),
						'currency' => $currency,
						'account_id' => $ShipperNumber
					);
					array_push($shippingResdata, $temp);
				}


			}

		}


		if(!empty($shippingResdata)){
			$shippingResdata = $this->msortASC($shippingResdata, 'shipment_cost');
			$result['SUCCESS'] = true;
			$result['DATA'] = $shippingResdata;
		} 
		else {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Something went wrong!';
		}
		return $result;
	}
	public function getAccountInfo(){
		$result = array('SUCCESS' => false, 'DATA' => '', 'ERROR' => '');

		if(!isset($_SESSION['stamps_access_token'])) {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Login Session.';
			//return $result;
		}
		$StampsData = $this->StampsModel->getAccountInfo();
		//pr($StampsData);die('STOP');
		if(isset($StampsData['account']['customer_id']) && $StampsData['account']['customer_id'] != ''){
			$result['SUCCESS'] = true;
			$result['ERROR'] = '';
		}
		else {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Session.';
		}
		return $result;
	}
	public function getShippingStatus($requestData){
		$result = array('SUCCESS' => false, 'DATA' => '', 'ERROR' => '');

		if(!isset($_SESSION['stamps_access_token'])) {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Login Session.';
			return $result;
		}
		$shippingResdata = array();
		$file = $requestData['file'];
		$OrderDate = $requestData['OrderDate'];
		$store = $requestData['OrderRetailStore'];
		$OrderCarrier = $requestData['OrderCarrier'];
		$OrderTracking = $requestData['OrderTracking'];
		if($OrderCarrier == '' || $OrderTracking == '') {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid carrier or tracking';
			return $result;
		}

		$options = array();
		$options['carrier'] = $OrderCarrier;
		$options['tracking_number'] = $OrderTracking;
		//pr($options);die('SS');
		$StampsData = $this->StampsModel->getShippingStatus($options);
		//pr($StampsData);die('STOP');

		$status_code='';
		if(!$StampsData) {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Session.';
			return $result;
		}
		else if(!empty($StampsData)) {
			if(isset($StampsData['errors'])){
				$errorMsg = '';
				if(!empty($StampsData['errors'])) {
					foreach($StampsData['errors'] as $error) {
						$errorMsg .= $error['error_code'].' - '.$error['error_message'].'. ';
					}
				}
				else {
					$errorMsg = 'Invalid Session.';
				}
				$result['SUCCESS'] = false;
				$result['ERROR'] = $errorMsg;
				return $result;
			}
			else {

				//"accepted" "delivered" "exception" "awaiting_shipment" "in_transit"
				$status_code = isset($StampsData['status_code'])?$StampsData['status_code']:'';
				if($status_code == 'delivered'){

					if($store == 'BodiStaff') {
						$customerInfoDir = "../Staff/Contact/";
						$customerTemplateDir = "../Staff/Contact/";
						$Customertemplate = $this->loadFile($customerTemplateDir."contact-template.json");
					}
					else {
						$customerInfoDir = "../../bodiforbusiness/{$store}/";
						$customerTemplateDir = "../../bodiforbusiness/retail/";
						$Customertemplate = $this->loadFile($customerTemplateDir."template.json");
					}


					$customerIndex = '-1';
					$orderIndex = '-1';
					if($store=='Bodi4life' || $store == 'Bodi2business' || $store=='Equine'){
						//For customer file----
						$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
						if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
							foreach ($customerInfo['Order'] as $orderkey => $order) {
								$dateToChk = $order['OrderDate'];
								if ($dateToChk == $OrderDate) {
									$orderIndex = $orderkey;
									$customerInfo['Order'][$orderIndex]['OrderStatus']='Delivered';
									$this->saveFile($customerInfoDir.$file.'.json', $customerInfo);
									$this->updateLog(array('store'=>$store));
									break;
								}
							}
						}
					}

					else if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop') {
						$filename = $store. '/' . $file . '.json';
						$orderInfo = $this->loadFile($filename);
						if(count($orderInfo)>0){
							foreach($orderInfo as $customerkey => $orderInfoRow){
								foreach($orderInfoRow['Order'] as $orderkey => $order) {
									if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
										$customerIndex = $customerkey;
										$orderIndex = $orderkey;
										$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderStatus']='Delivered';
										$this->saveFile($customerInfoDir.$file.'.json', $orderInfo);
										$this->updateLog(array('store'=>$store));
										break;
									}
								}
							}
						}
					}
				}
			}
		}
		if($status_code!=''){
			$shippingStatusResdata = array('status_code' => $status_code);
			$result['SUCCESS'] = true;
			$result['DATA'] = $shippingStatusResdata;
		}
		else {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Something went wrong!';
		}
		return $result;
	}
	public function getAllShippingStatus(){
		$result = array('SUCCESS' => false, 'DATA' => '', 'ERROR' => '');

		/*if(!isset($_SESSION['stamps_access_token'])) {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Login Session.';
			return $result;
		}*/
		$stores = array('Ebay','Etsy','Bodi4life','Bodi2business','Equine');
		//$stores = array('Bodi4life');
		$needUpdateLogStores = array();
		$updateLists = array();
		foreach ($stores as $store) {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$logInfo = json_decode(file_get_contents($customerInfoDir.'_log.json'), true);
			if(!empty($logInfo)) {
				foreach($logInfo as $logInfoKey => $logInfoRow) {
					if(isset($logInfoRow['OrderStatus']) && !empty($logInfoRow['OrderStatus'])) {
						foreach($logInfoRow['OrderStatus'] as $OrderDate => $OrderStatus){
							if($OrderStatus=='Shipped' || $OrderStatus=='Missingmail') {
								$file = $logInfoRow['CustomerID'];
								$customerInfo = json_decode(file_get_contents($customerInfoDir.$file.'.json'), true);
								if($store == 'Bodi4life' || $store == 'Bodi2business' || $store == 'Equine') {
									if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
										foreach ($customerInfo['Order'] as $orderIndex => $order) {
											if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate ) {

												if($order['OrderStatus'] == 'Delivered') {
													array_push($needUpdateLogStores,$store);
													array_push($updateLists,array('store' => $store, 'filename' => $file, 'OrderDate' => $OrderDate));
													break;
												}
												else if($order['OrderStatus'] != 'Shipped' && $order['OrderStatus'] != 'Missingmail') {
													//Do not change status---
													break;
												}
												$OrderCarrier = $order['OrderCarrier'];
												$OrderTracking = '';
												if(is_array($order['OrderTracking']) && isset($order['OrderTracking'][0])) {
													$OrderTracking = $order['OrderTracking'][0];
												}
												else if(!is_array($order['OrderTracking']) && $order['OrderTracking'] !='') {
													$OrderTracking = $order['OrderTracking'];
												}
												if($OrderCarrier != '' && $OrderTracking != '') {
													$options = array();
													$options['carrier'] = $OrderCarrier;
													$options['tracking_number'] = $OrderTracking;
													//pr($options);die('SS');
													$StampsData = $this->StampsModel->getShippingStatus($options);
													$status_code = isset($StampsData['status_code'])?$StampsData['status_code']:'';
													//$status_code='delivered';
													if($status_code == 'delivered'){
														$customerInfo['Order'][$orderIndex]['OrderStatus']='Delivered';
														$this->saveFile($customerInfoDir.$file.'.json', $customerInfo);
														array_push($needUpdateLogStores,$store);
														array_push($updateLists,array('store' => $store, 'filename' => $file, 'OrderDate' => $OrderDate));
													}
													else {
														$now = time();
														$OrderDateTime = strtotime($order['OrderLastUpDate']);
														if($OrderDateTime<=0){
															$OrderDateTime = strtotime($order['OrderDate']);
														}
														$datediff = $now - $OrderDateTime;
														$days = round($datediff / (60 * 60 * 24));
														if($days>=7){
															array_push($needUpdateLogStores,$store);
															$customerInfo['Order'][$orderIndex]['OrderStatus'] = 'Pending';
															$this->saveFile($customerInfoDir.$file.'.json', $customerInfo);
														}
													}
												}

												break;
											}
										}
									}
								}
								else if($store == 'Ebay' || $store == 'Etsy' || $store == 'Amazon') {
									if(count($customerInfo)>0) {
										foreach($customerInfo as $customerIndex => $fileDataRow){
											if (isset($fileDataRow['Order']) && is_array($fileDataRow['Order'])) {
												if(!empty($fileDataRow['Order'])) {
													foreach ($fileDataRow['Order'] as $orderIndex => $order) {
								        				if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate ) {
								        					if($order['OrderStatus'] == 'Delivered') {
																array_push($needUpdateLogStores,$store);
																array_push($updateLists,array('store' => $store, 'filename' => $file, 'OrderDate' => $OrderDate));
																break;
															}
															else if($order['OrderStatus'] != 'Shipped' && $order['OrderStatus'] != 'Missingmail') {
																//Do not change status---
																break;
															}
															$OrderCarrier = $order['OrderCarrier'];
															$OrderTracking = '';
															if(is_array($order['OrderTracking']) && isset($order['OrderTracking'][0])) {
																$OrderTracking = $order['OrderTracking'][0];
															}
															else if(!is_array($order['OrderTracking']) && $order['OrderTracking'] !='') {
																$OrderTracking = $order['OrderTracking'];
															}
															if($OrderCarrier != '' && $OrderTracking != '') {
																$options = array();
																$options['carrier'] = $OrderCarrier;
																$options['tracking_number'] = $OrderTracking;
																//pr($options);
																$StampsData = $this->StampsModel->getShippingStatus($options);
																$status_code = isset($StampsData['status_code'])?$StampsData['status_code']:'';
																if($status_code == 'delivered'){
																	$customerInfo[$customerIndex]['Order'][$orderIndex]['OrderStatus']='Delivered';
																	$this->saveFile($customerInfoDir.$file.'.json', $customerInfo);
																	array_push($needUpdateLogStores,$store);
																	array_push($updateLists,array('store' => $store, 'filename' => $file, 'OrderDate' => $OrderDate));
																}
																else {
																	$now = time();
																	$OrderDateTime = strtotime($order['OrderLastUpDate']);
																	if($OrderDateTime<=0){
																		$OrderDateTime = strtotime($order['OrderDate']);
																	}
																	$datediff = $now - $OrderDateTime;
																	$days = round($datediff / (60 * 60 * 24));
																	if($days>=7){
																		array_push($needUpdateLogStores,$store);
																		$customerInfo[$customerIndex]['Order'][$orderIndex]['OrderStatus'] = 'Pending';
																		$this->saveFile($customerInfoDir.$file.'.json', $customerInfo);
																	}
																}
															}
															break;
														}
								        			}
								        		}
								        	}
								        }
								    }
								}
							}
						}
					}
				}
			}
		}
		if(!empty($needUpdateLogStores)) {
			$needUpdateLogStores = array_unique($needUpdateLogStores);
			foreach($needUpdateLogStores as $store) {
				$this->updateLog(array('store'=>$store));
			}
		}
		//echo "<br>========Updated Lists==========<br>";
		//pr($updateLists);
		//die('<br>All Done');
		$result['SUCCESS'] = true;
		return $result;
	}
	public function chkOrderTracking($requestData){
		$result = array('SUCCESS' => false, 'DATA' => '', 'ERROR' => '');
		$file = $requestData['filename'];
		$OrderDate = $requestData['OrderDate'];
		$store = $requestData['OrderRetailStore'];

		if($store == 'BodiStaff') {
			$customerInfoDir = "../Staff/Contact/";
			$customerTemplateDir = "../Staff/Contact/";
			$Customertemplate = $this->loadFile($customerTemplateDir."contact-template.json");
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerTemplateDir = "../../bodiforbusiness/retail/";
			$Customertemplate = $this->loadFile($customerTemplateDir."template.json");
		}
		$OrderTracking = '';
		$OrderLabelPrint = '';
		$OrderLabelId = '';
		if($store=='Bodi4life' || $store == 'Bodi2business' || $store=='Equine'){
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
				foreach ($customerInfo['Order'] as $orderkey => $order) {
					if ($order['OrderDate'] == $OrderDate) {
						if(isset($order['OrderTracking']) && is_array($order['OrderTracking']) && !empty($order['OrderTracking'])) {
							foreach($order['OrderTracking'] as $OrderTrackingT){
								if($OrderTrackingT != '') {
									$OrderTracking = $OrderTrackingT;
									break;
								}
							}
						}
						$OrderLabelId = $order['OrderLabelId'] ?? '';
						$OrderLabelPrint = $order['OrderLabelPrint'] ?? '';
						break;
					}
				}
			}
		}
		else if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop') {
			$filename = $store. '/' . $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(count($orderInfo)>0){
				foreach($orderInfo as $customerkey => $orderInfoRow){
					foreach($orderInfoRow['Order'] as $orderkey => $order) {
						if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
							if(isset($order['OrderTracking']) && is_array($order['OrderTracking']) && !empty($order['OrderTracking'])) {
								foreach($order['OrderTracking'] as $OrderTrackingT){
									if($OrderTrackingT != '') {
										$OrderTracking = $OrderTrackingT;
										break;
									}
								}
							}
							$OrderLabelId = $order['OrderLabelId'] ?? '';
							$OrderLabelPrint = $order['OrderLabelPrint'] ?? '';
							break;
						}
					}
				}
			}
		}

		if($OrderTracking!=''){
			$resdata = array(
				'OrderTracking' => $OrderTracking,
				'OrderLabelId' => $OrderLabelId,
				'OrderLabelPrint' => $OrderLabelPrint
			);
			$result['SUCCESS'] = true;
			$result['DATA'] = $resdata;
		}
		else {
			$result['SUCCESS'] = false;
		}
		return $result;
	}
	public function testLog(){
		//$this->UpsModel->testLog();
		$to_address = array(
			"Name" => 'Masha Seker',
			"Address" => array(
				"AddressLine" => array(
					'9825 Haylet Rd Nw'
				),
				"City" => 'Rice',
				"StateProvinceCode" => 'MN',
				"PostalCode" =>  '56367',
				"CountryCode" => 'US' //Only 2 character
			)
		);
		$length = 7;
		$width = 5;
		$height = 1;
		$boxSize = 1;
		$ShipperNumber = '';
		$ServiceCode = '92';
		$ServiceDescription = 'UPS SurePost - Less than 1lb';

		$WeightOZ = 4;
		if($boxSize > 0) {
			$WeightOZ += (int)$boxSize;
		}
		$WeightLB = (float)Conversion::convertStockValue($WeightOZ, "oz", "lb");


		$options = array();
		$options['to_address'] = $to_address;
		$options['length'] = $length;
		$options['width'] = $width;
		$options['height'] = $height;
		$options['Weight'] = '';
		$options['WeightUnitCode'] = '';
		$options['WeightUnitDesc'] = "";

		$options['ShipperNumber'] = $ShipperNumber;
		$options['service_code'] = $ServiceCode;
		$options['service_description'] = $ServiceDescription;

		if($ServiceCode == '93' || $ServiceCode == '03' || $ServiceCode == '02' || $ServiceCode == '13') {
			$options['Weight'] = $WeightLB;
			$options['WeightUnitCode'] = 'LBS';
			$options['WeightUnitDesc'] = "Pounds";
		}
		else {
			$options['Weight'] = $WeightOZ;
			$options['WeightUnitCode'] = 'OZS';
			$options['WeightUnitDesc'] = "Ounces";
		}
		echo "==options===<br/>";
		pr($options);
		$UpsData = $this->UpsModel->getShippingLabel($options);


		die('END');
	}
	public function getShippingLabel($requestData){
		$result = array('SUCCESS' => false, 'DATA' => '', 'ERROR' => '');
		
		//Only for test------------
		/*$shippingResdata = array(
			'LabelId' => 'Test',
			'tracking_number' => 'Test',
			'LabelPrint' => 'Test',
			'carrier' => 'Test',
			'service_type' => 'Test'
		);
		if(!empty($shippingResdata)){
			$result['SUCCESS'] = true;
			$result['DATA'] = $shippingResdata;
		} 
		return $result;*/
		//------------
		
		
		$shippingResdata = array();
		$file = $requestData['file'];
		$OrderDate = $requestData['OrderDate']??'';
		$store = $requestData['OrderRetailStore']??'';
		$OrderBoxsize = $requestData['OrderBoxsize'];
		$service_type = $requestData['service_type']??'';
		$packaging_type = $requestData['packaging_type']??'package';
		$packaging_price = $requestData['packaging_price']??0.00;
		$shipweightTotal = $requestData['shipweightTotal']??0.00;
		$OrderCarrierServiceAccount = $requestData['OrderCarrierServiceAccount']??'';
		if($service_type=='') {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Service Type.';
			return $result;
		}
		
		if($store == 'BodiStaff') {
			$customerInfoDir = "../Staff/Contact/";
			$customerTemplateDir = "../Staff/Contact/";
			$Customertemplate = $this->loadFile($customerTemplateDir."contact-template.json");
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerTemplateDir = "../../bodiforbusiness/retail/";
			$Customertemplate = $this->loadFile($customerTemplateDir."template.json");
		}

		$OrderShipLabel = '';
		$to_address = array();
		$items_ordered = array();
		$package = array();
		$customs_items = array();
		$customs = array();
		$customerIndex = '-1';
		$orderIndex = '-1';
		if($store=='Bodi4life' || $store == 'Bodi2business' || $store=='Equine'){
			//For customer file----
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
				foreach ($customerInfo['Order'] as $orderkey => $order) {
					$dateToChk = $order['OrderDate'];
					if ($dateToChk == $OrderDate) {
						$orderIndex = $orderkey;
						/*if(isset($order['OrderLabelId']) && $order['OrderLabelId'] != ''){
							$result['SUCCESS'] = false;
							$result['ERROR'] = 'Label ID already generated.';
							return $result;
						}*/
						
						if(isset($customerInfo['Addresses']) && !empty($customerInfo['Addresses'])) {
							foreach ($customerInfo['Addresses'] as $addressArr) {
								if($addressArr['AddressZip'] == $order['OrderAddressType']) {
									$to_address = array(
										"company_name" => "",
										"name" => $addressArr['AddressName'],
										"address_line1" => $addressArr['AddressStreet'],
										"address_line2" => $addressArr['AddressUnit'],
										"address_line3" => "",
										"city" => $addressArr['AddressCity'],
										"state_province" => $addressArr['AddressState'],
										"postal_code" => $addressArr['AddressZip'],
										"country_code" => isset($this->countryCode[$addressArr['AddressCountry']])?$this->countryCode[$addressArr['AddressCountry']]:$addressArr['AddressCountry'],
										"phone" => $customerInfo['Phone'],
										"email" => $customerInfo['Email'],
										"residential_indicator" => "Yes"
									);
									break;
								}
							}
						}
						
						if(isset($order['OrderItems']) && !empty($order['OrderItems'])) {
							foreach ($order['OrderItems'] as $OrderItem) {
								if($OrderItem['OrderProduct'] != '' && $OrderItem['OrderAttribute'] != 'Instr') {
									$OrderAttribute = $OrderItem['OrderAttribute'];
									$OrderAttributeType = preg_replace('/[0-9]+/', '', $OrderAttribute);
									$OrderAttributeValue = (int)filter_var($OrderAttribute, FILTER_SANITIZE_NUMBER_INT); 
									if($OrderAttributeType!='' && $OrderAttributeValue!='') {
										$item_options = array(
											array(
												"attribute" => "$OrderAttributeType",
												"value" => "$OrderAttributeValue"
											)
										);
									}
									else {
										$item_options = array(
											array(
												"attribute" => "oz",
												"value" => "4"
											)
										);
									}
									
									$item_ordered = array(
										"item_name" => $OrderItem['OrderProduct'],
										"quantity" => $OrderItem['OrderQuantity'],
										"image_url" => "",
										"item_options" => $item_options
									);
									array_push($items_ordered, $item_ordered);
									
									$TotOrderPrice = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
									$customs_itemsTemp = array(
										'item_description' => substr($OrderItem['OrderProduct'], 0, 50),
										'quantity' => $OrderItem['OrderQuantity'],
										'unit_value' => array(
											'amount' => $OrderItem['OrderPrice'],
											'currency' => "usd",
										),
										'item_weight' => $OrderItem['OrderShipWeight'],
										'weight_unit' => 'ounce',
										'harmonized_tariff_code' => '293690',
										'country_of_origin' => 'US',
									);
									array_push($customs_items, $customs_itemsTemp);
										
										
								}
							}
						}
						
						if(isset($shipweightTotal) && $shipweightTotal>0) {
							$OrderShipWeightTotal = $shipweightTotal;
						}
						else {
							$OrderShipWeightTotal = $order['OrderShipWeightTotal'];
						}
						
						$OrderBoxsizeArr = explode(',',$OrderBoxsize);
						$length = isset($OrderBoxsizeArr[0])?$OrderBoxsizeArr[0]:0;
						$width = isset($OrderBoxsizeArr[1])?$OrderBoxsizeArr[1]:0;
						$height = isset($OrderBoxsizeArr[2])?$OrderBoxsizeArr[2]:0;
						$boxSize = isset($OrderBoxsizeArr[3])?$OrderBoxsizeArr[3]:0;
						$package = array(
							"packaging_type" => $packaging_type,
							"weight" => (int)($OrderShipWeightTotal+$boxSize),
							"weight_unit" => "ounce",
							"length" => $length,
							"width" => $width,
							"height" => $height,
							"dimension_unit" => "inch"
						);
						break;
					}
				}
			}
		}
		
		else if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop') {
			$filename = $store. '/' . $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(count($orderInfo)>0){
				foreach($orderInfo as $customerkey => $orderInfoRow){
					foreach($orderInfoRow['Order'] as $orderkey => $order) {
						if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
							$customerIndex = $customerkey;
							$orderIndex = $orderkey;
							/*if(isset($order['OrderLabelId']) && $order['OrderLabelId'] != ''){
								$result['SUCCESS'] = false;
								$result['ERROR'] = 'Label ID already generated.';
								return $result;
							}*/
							$OrderAddressType = $order['OrderAddressType'];	
							$CustomerName = $orderInfoRow['CustomerName'];
							if(isset($orderInfoRow['Addresses']) && !empty($orderInfoRow['Addresses'])) {
								foreach ($orderInfoRow['Addresses'] as $addressArr) {
									if($addressArr['AddressStreet'] == $OrderAddressType || $addressArr['AddressZip'] == $OrderAddressType) {
										$AddressName = $addressArr['AddressName'];
										if($addressArr['AddressName'] =='' && $orderInfoRow['CustomerName']!='') {
											$AddressName = $orderInfoRow['CustomerName'];
										}
										$to_address = array(
											"company_name" => "",
											"name" => $AddressName,
											"address_line1" => $addressArr['AddressStreet'],
											"address_line2" => $addressArr['AddressUnit'],
											"address_line3" => "",
											"city" => $addressArr['AddressCity'],
											"state_province" => $addressArr['AddressState'],
											"postal_code" => $addressArr['AddressZip'],
											"country_code" => isset($this->countryCode[$addressArr['AddressCountry']])?$this->countryCode[$addressArr['AddressCountry']]:$addressArr['AddressCountry'],
											"phone" => $orderInfoRow['Phone'],
											"email" => $orderInfoRow['Email'],
											"residential_indicator" => "Yes"
										);
										break;
									}
								}
							}
							
							if(isset($order['OrderItems']) && !empty($order['OrderItems'])) {
								foreach ($order['OrderItems'] as $OrderItem) {
									if($OrderItem['OrderProduct'] != '' && $OrderItem['OrderAttribute'] != 'Instr') {
										$OrderAttribute = $OrderItem['OrderAttribute'];
										$OrderAttributeType = preg_replace("/[^0-9]/", '', $OrderAttribute);
										$OrderAttributeValue = (int)filter_var($OrderAttribute, FILTER_SANITIZE_NUMBER_INT); 
										if($OrderAttributeType!='' && $OrderAttributeValue!='') {
											$item_options = array(
												array(
													"attribute" => "$OrderAttributeType",
													"value" => "$OrderAttributeValue"
												)
											);
										}
										else {
											$item_options = array(
												array(
													"attribute" => "oz",
													"value" => "4"
												)
											);
										}
										
										$item_ordered = array(
											"item_name" => substr($OrderItem['OrderProduct'], 0, 50),
											"quantity" => $OrderItem['OrderQuantity'],
											"image_url" => "",
											"item_options" => $item_options
										);
										array_push($items_ordered, $item_ordered);
										
										$TotOrderPrice = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
										$customs_itemsTemp = array(
											'item_description' => substr($OrderItem['OrderProduct'], 0, 50),
											'quantity' => $OrderItem['OrderQuantity'],
											'unit_value' => array(
												'amount' => $OrderItem['OrderPrice'],
												'currency' => "usd",
											),
											'item_weight' => $OrderItem['OrderShipWeight'],
											'weight_unit' => 'ounce',
											'harmonized_tariff_code' => '293690',
											'country_of_origin' => 'US',
										);
										array_push($customs_items, $customs_itemsTemp);
										
									}
								}
							}
							
							if(isset($shipweightTotal) && $shipweightTotal>0) {
								$OrderShipWeightTotal = $shipweightTotal;
							}
							else {
								$OrderShipWeightTotal = $order['OrderShipWeightTotal'];
							}
							
							$OrderBoxsizeArr = explode(',',$OrderBoxsize);
							$length = isset($OrderBoxsizeArr[0])?$OrderBoxsizeArr[0]:0;
							$width = isset($OrderBoxsizeArr[1])?$OrderBoxsizeArr[1]:0;
							$height = isset($OrderBoxsizeArr[2])?$OrderBoxsizeArr[2]:0;
							$boxSize = isset($OrderBoxsizeArr[3])?$OrderBoxsizeArr[3]:0;
							$package = array(
								"packaging_type" => $packaging_type,
								"weight" => (int)($OrderShipWeightTotal+$boxSize),
								"weight_unit" => "ounce",
								"length" => $length,
								"width" => $width,
								"height" => $height,
								"dimension_unit" => "inch"
							);
							break;
							
						}
					}
				}
			}
		}
		$customs = array(
			'contents_type' => 'merchandise',
			'contents_description' => '',
			'non_delivery_option' => 'return_to_sender',
			'customs_items' => $customs_items
		);
		
		$options = array();
		$options['to_address'] = $to_address;
		$options['service_type'] = $service_type;
		$options['package'] = $package;
		$options['customs'] = $customs;
		$options['delivery_confirmation_type'] = "tracking";
		$options['insurance'] = array(
			"insurance_provider" => "stamps_com",
			"insured_value" => array(
				"amount" => 0,
				"currency" => "usd"
			)
		);
		$options['is_return_label'] = false;
		$options['label_options'] = array(
			"label_size" => "4x6",
			"label_format" => "png",
			"label_logo_image_id" => 0,
			"label_output_type" => "url"
		);
			/*$options['email_label'] = array(
				"email" => "",
				"email_notes" => "",
				"bcc_email" => ""
			);*/
		$options["references"] = array(
			"printed_message1" => "",
			"printed_message2" => "",
			"printed_message3" => "",
			"cost_code_id" => 0,
			"reference1" => "",
			"reference2" => "",
			"reference3" => "",
			"reference4" => ""
		);
		$options["order_details"] = array(
			"order_source" => "Bodi4life",
			"order_number" => (string)(strtotime($OrderDate)),
			"order_date" => date('m/d/Y',strtotime($OrderDate)),
			"items_ordered" => $items_ordered
		);
		$options["is_test_label"] = false;
		$options["is_store_label"] = true;	
			
		//echo "AA";
		//pr($options);
		//die('SSS');
		$StampsData = $this->StampsModel->getShippingLabel($options);
		//echo "****StampsData******";
		//pr($StampsData);
		//die('ABCD');
		if(!$StampsData) {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Session.';
			return $result;
		}
		else if(!empty($StampsData)) {
			if(isset($StampsData['errors'])){
				$errorMsg = '';
				if(!empty($StampsData['errors'])) {
					foreach($StampsData['errors'] as $error) {
						$errorMsg .= $error['error_code'].' - '.$error['error_message'].'. ';
					}
				}
				else {
					$errorMsg = 'Invalid Session.';
				}
				$result['SUCCESS'] = false;
				$result['ERROR'] = $errorMsg;
				return $result;
			}
			else {
				$LabelId = isset($StampsData['label_id'])?$StampsData['label_id']:0.00;
				$tracking_number = isset($StampsData['tracking_number'])?$StampsData['tracking_number']:'';
				$LabelPrint = isset($StampsData['labels'][0]['href'])?$StampsData['labels'][0]['href']:'';
				$shippingResdata = array(
					'LabelId' => $LabelId,
					'tracking_number' => $tracking_number,
					'LabelPrint' => $LabelPrint,
					'carrier' => $StampsData['carrier'],
					'service_type' => $StampsData['service_type']
				);
				
				if($orderIndex>=0){
					if($store=='Bodi4life' || $store == 'Bodi2business' || $store=='Equine'){
						$customerInfo['Order'][$orderIndex]['OrderStatus']='Shipped';
						$customerInfo['Order'][$orderIndex]['OrderLabelId']=$LabelId;
						$customerInfo['Order'][$orderIndex]['OrderLabelPrint']=$LabelPrint;
						//$customerInfo['Order'][$orderIndex]['OrderCarrierFeeRetail']=$packaging_price;
						$customerInfo['Order'][$orderIndex]['OrderCarrierFeeCost']=$packaging_price;
						$customerInfo['Order'][$orderIndex]['OrderLastUpDate']=date('Y-m-d');
						$customerInfo['Order'][$orderIndex]['OrderCarrierServiceAccount']=$OrderCarrierServiceAccount;
						
						if(strpos($service_type, 'ups_') !== false) {
						   $customerInfo['Order'][$orderIndex]['OrderCarrier']='ups';
						}
						else if(strpos($service_type, 'usps_') !== false) {
						    $customerInfo['Order'][$orderIndex]['OrderCarrier']='usps';
						}
						
						//OrderTracking------------
						$OrderTracking = array();
						array_push($OrderTracking,$tracking_number);
						if(isset($customerInfo['Order'][$orderIndex]['OrderTracking']) && is_array($customerInfo['Order'][$orderIndex]['OrderTracking']) && !empty($customerInfo['Order'][$orderIndex]['OrderTracking'])) {
							foreach($customerInfo['Order'][$orderIndex]['OrderTracking'] as $prevTrack) {
								if($prevTrack != '') {
									array_push($OrderTracking,$prevTrack);
								}
							}
						}
						else if(isset($customerInfo['Order'][$orderIndex]['OrderTracking']) && !is_array($customerInfo['Order'][$orderIndex]['OrderTracking']) && $customerInfo['Order'][$orderIndex]['OrderTracking']!='') {
							array_push($OrderTracking,$customerInfo['Order'][$orderIndex]['OrderTracking']);
						}
						$customerInfo['Order'][$orderIndex]['OrderTracking']=$OrderTracking;
						//OrderTracking------------						
						
						$customerInfo = $this->arrangeCustomer($customerInfo);
						$this->saveFile($customerInfoDir.$file.'.json', $customerInfo);
					}
					else if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop') {
						if($customerIndex>=0){	
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderStatus']='Shipped';	
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderLabelId']=$LabelId;
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderLabelPrint']=$LabelPrint;
							//$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderCarrierFeeRetail']=$packaging_price;
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderCarrierFeeCost']=$packaging_price;
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderLastUpDate']=date('Y-m-d');
							
							if(strpos($service_type, 'ups_') !== false) {
							    $orderInfo[$customerIndex]['Order'][$orderIndex]['OrderCarrier']='ups';
							}
							else if(strpos($service_type, 'usps_') !== false) {
							    $orderInfo[$customerIndex]['Order'][$orderIndex]['OrderCarrier']='usps';
							}
							
							//OrderTracking------------
							$OrderTracking = array();
							array_push($OrderTracking,$tracking_number);
							if(isset($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']) && is_array($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']) && !empty($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking'])) {
								foreach($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking'] as $prevTrack) {
									if($prevTrack != '') {
										array_push($OrderTracking,$prevTrack);
									}
								}
							}
							else if(isset($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']) && !is_array($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']) && $orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']!='') {
								array_push($OrderTracking,$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']);
							}
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']=$OrderTracking;
							//OrderTracking------------
							
							$this->saveFile($customerInfoDir.$file.'.json', $orderInfo);
						}
					}
					$this->updateLog(array('store'=>$store));
				}
			}
		}
			
		
			
			
		if(!empty($shippingResdata)){
			$result['SUCCESS'] = true;
			$result['DATA'] = $shippingResdata;
		} 
		else {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Something went wrong!';
		}
		return $result;
	}
	public function getUpsShippingLabel($requestData){
		$result = array('SUCCESS' => false, 'DATA' => '', 'ERROR' => '');

		$shippingResdata = array();
		$file = $requestData['file']??'';
		$OrderDate = $requestData['OrderDate']??'';
		$store = $requestData['OrderRetailStore']??'';
		$OrderBoxsize = $requestData['OrderBoxsize']??'';
		$service_type = $requestData['service_type']??'';
		$packaging_type = $requestData['packaging_type']??'package';
		$packaging_price = $requestData['packaging_price']??'';
		$shipweightTotal = $requestData['shipweightTotal']??0.00;
		$ServiceCode = $requestData['service_code']??'';
		$ServiceDescription = $requestData['service_description']??'';
		$accountNo = $requestData['account_no']??'';
		$OrderCarrierServiceAccount = $requestData['OrderCarrierServiceAccount']??'';
		if($service_type=='') {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Service Type.';
			return $result;
		}

		if($store == 'BodiStaff') {
			$customerInfoDir = "../Staff/Contact/";
			$customerTemplateDir = "../Staff/Contact/";
			$Customertemplate = $this->loadFile($customerTemplateDir."contact-template.json");
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerTemplateDir = "../../bodiforbusiness/retail/";
			$Customertemplate = $this->loadFile($customerTemplateDir."template.json");
		}
		$OrderShipLabel = '';
		$to_address = array();
		$items_ordered = array();
		$package = array();
		$customs_items = array();
		$customs = array();
		$customerIndex = '-1';
		$orderIndex = '-1';
		if($store=='Bodi4life' || $store == 'Bodi2business' || $store=='Equine'){
			//For customer file----
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
				foreach ($customerInfo['Order'] as $orderkey => $order) {
					$dateToChk = $order['OrderDate'];
					if ($dateToChk == $OrderDate) {
						$orderIndex = $orderkey;

						if(isset($customerInfo['Addresses']) && !empty($customerInfo['Addresses'])) {
							foreach ($customerInfo['Addresses'] as $addressArr) {
								if($addressArr['AddressZip'] == $order['OrderAddressType']) {

									$AddressLine = array();
									if(isset($addressArr['AddressStreet']) && $addressArr['AddressStreet']!='') {
										$AddressLine[] = $addressArr['AddressStreet'];
									}
									if(isset($addressArr['AddressUnit']) && $addressArr['AddressUnit']!='') {
										$AddressLine[] = $addressArr['AddressUnit'];
									}
									if($addressArr['AddressName'] =='' && $orderInfoRow['CustomerName']!='') {
										$addressArr['AddressName'] = $orderInfoRow['CustomerName'];
									}
									$to_address = array(
										"Name" => $addressArr['AddressName'],
										"Address" => array(
											"AddressLine" => $AddressLine,
											"City" => $addressArr['AddressCity'],
											"StateProvinceCode" => $addressArr['AddressState'],
											"PostalCode" =>  $addressArr['AddressZip'],
											"CountryCode" => isset($this->countryCode[$addressArr['AddressCountry']])?$this->countryCode[$addressArr['AddressCountry']]:$addressArr['AddressCountry'], //Only 2 character
										)
									);
									/* $to_address = array(
										"Name" => 'Masha Seker',
										"Address" => array(
											"AddressLine" => array(
												'9825 Haylet Rd Nw'
											),
											"City" => 'Rice',
											"StateProvinceCode" => 'MN',
											"PostalCode" =>  '56367',
											"CountryCode" => 'US' //Only 2 character
										)
									); */

									break;
								}
							}
						}

						if(isset($shipweightTotal) && $shipweightTotal>0) {
							$OrderShipWeightTotal = $shipweightTotal;
						}
						else {
							$OrderShipWeightTotal = $order['OrderShipWeightTotal'];
						}
						$OrderBoxsizeArr = explode(',',$OrderBoxsize);
						$length = isset($OrderBoxsizeArr[0])?$OrderBoxsizeArr[0]:0;
						$width = isset($OrderBoxsizeArr[1])?$OrderBoxsizeArr[1]:0;
						$height = isset($OrderBoxsizeArr[2])?$OrderBoxsizeArr[2]:0;
						$boxSize = isset($OrderBoxsizeArr[3])?$OrderBoxsizeArr[3]:0;

						$WeightOZ = (int)$OrderShipWeightTotal;
						if($boxSize > 0) {
							$WeightOZ += (int)$boxSize;
						}
						$WeightLB = (float)Conversion::convertStockValue($WeightOZ, "oz", "lb");
						break;
					}
				}
			}

		}

		else if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop') {
			$filename = $store. '/' . $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(count($orderInfo)>0){
				foreach($orderInfo as $customerkey => $orderInfoRow){
					foreach($orderInfoRow['Order'] as $orderkey => $order) {
						if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
							$customerIndex = $customerkey;
							$orderIndex = $orderkey;
							/*if(isset($order['OrderLabelId']) && $order['OrderLabelId'] != ''){
								$result['SUCCESS'] = false;
								$result['ERROR'] = 'Label ID already generated.';
								return $result;
							}*/
							$OrderAddressType = $order['OrderAddressType'];
							$CustomerName = $orderInfoRow['CustomerName'];
							if(isset($orderInfoRow['Addresses']) && !empty($orderInfoRow['Addresses'])) {
								foreach ($orderInfoRow['Addresses'] as $addressArr) {
									if($addressArr['AddressStreet'] == $OrderAddressType || $addressArr['AddressZip'] == $OrderAddressType) {
										$AddressLine = array();
										if(isset($addressArr['AddressStreet']) && $addressArr['AddressStreet']!='') {
											$AddressLine[] = $addressArr['AddressStreet'];
										}
										if(isset($addressArr['AddressUnit']) && $addressArr['AddressUnit']!='') {
											$AddressLine[] = $addressArr['AddressUnit'];
										}
										if($addressArr['AddressName'] =='' && $orderInfoRow['CustomerName']!='') {
											$addressArr['AddressName'] = $orderInfoRow['CustomerName'];
										}
										$to_address = array(
											"Name" => $addressArr['AddressName'],
											"Address" => array(
												"AddressLine" => $AddressLine,
												"City" => $addressArr['AddressCity'],
												"StateProvinceCode" => $addressArr['AddressState'],
												"PostalCode" =>  $addressArr['AddressZip'],
												"CountryCode" => isset($this->countryCode[$addressArr['AddressCountry']])?$this->countryCode[$addressArr['AddressCountry']]:$addressArr['AddressCountry'], //Only 2 character
											)
										);
										break;
									}
								}
							}

							if(isset($shipweightTotal) && $shipweightTotal>0) {
								$OrderShipWeightTotal = $shipweightTotal;
							}
							else {
								$OrderShipWeightTotal = $order['OrderShipWeightTotal'];
							}

							$OrderBoxsizeArr = explode(',',$OrderBoxsize);
							$length = isset($OrderBoxsizeArr[0])?$OrderBoxsizeArr[0]:0;
							$width = isset($OrderBoxsizeArr[1])?$OrderBoxsizeArr[1]:0;
							$height = isset($OrderBoxsizeArr[2])?$OrderBoxsizeArr[2]:0;
							$boxSize = isset($OrderBoxsizeArr[3])?$OrderBoxsizeArr[3]:0;

							$WeightOZ = (int)$OrderShipWeightTotal;
							if($boxSize > 0) {
								$WeightOZ += (int)$boxSize;
							}
							$WeightLB = (float)Conversion::convertStockValue($WeightOZ, "oz", "lb");
							break;

						}
					}
				}
			}
		}

		$options = array();
		$options['to_address'] = $to_address;
		$options['length'] = $length;
		$options['width'] = $width;
		$options['height'] = $height;
		$options['Weight'] = '';
		$options['WeightUnitCode'] = '';
		$options['WeightUnitDesc'] = "";
		$options['service_code'] = $ServiceCode;
		$options['service_description'] = $ServiceDescription;

		$options['ShipperNumber'] = $accountNo;
		$options['service_code'] = $ServiceCode;
		$options['service_description'] = $ServiceDescription;

		if($ServiceCode == '93' || $ServiceCode == '03' || $ServiceCode == '02' || $ServiceCode == '13') {
			$options['Weight'] = $WeightLB;
			$options['WeightUnitCode'] = 'LBS';
			$options['WeightUnitDesc'] = "Pounds";
		}
		else {
			$options['Weight'] = $WeightOZ;
			$options['WeightUnitCode'] = 'OZS';
			$options['WeightUnitDesc'] = "Ounces";
		}

		/* echo "AA";
		pr($requestData);
		echo "BB";
		pr($options);
		die('SSS'); */
		$UpsData = $this->UpsModel->getShippingLabel($options);
		//pr($UpsData);
		/*die('ABCD'); */
		if(!$UpsData) {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Invalid Session.';
			return $result;
		}
		else if(!empty($UpsData)) {

			if(isset($UpsData['ShipmentResponse']['Response']['ResponseStatus']['Code']) && $UpsData['ShipmentResponse']['Response']['ResponseStatus']['Code'] == '1') {

				$tracking_number = $UpsData['ShipmentResponse']['ShipmentResults']['PackageResults']['TrackingNumber']??'';
				$base64 = $UpsData['ShipmentResponse']['ShipmentResults']['PackageResults']['ShippingLabel']['GraphicImage']??'';
				$LabelPrint = '';
				if($base64 != '') {

					 $LabelPrint = 'ups_label/' . date('Y-m-d') . '_' . $tracking_number . '.jpg';
					/*$DPI = 203;
					$targetHeight = 6 * $DPI; // 1218 px

					$imageData = base64_decode($base64);
					$srcImage  = imagecreatefromstring($imageData);

					// Rotate (UPS labels usually need this)
					$rotated = imagerotate($srcImage, -90, 0);

					// Original size
					$srcWidth  = imagesx($rotated);
					$srcHeight = imagesy($rotated);

					// Maintain aspect ratio
					$scale       = $targetHeight / $srcHeight;
					$targetWidth = (int)($srcWidth * $scale);

					// Create resized image
					$resized = imagecreatetruecolor($targetWidth, $targetHeight);
					imagecopyresampled(
						$resized,
						$rotated,
						0, 0, 0, 0,
						$targetWidth,
						$targetHeight,
						$srcWidth,
						$srcHeight
					);

					// Save label
					imagegif($resized, $LabelPrint);

					// Free memory
					imagedestroy($srcImage);
					imagedestroy($rotated);
					imagedestroy($resized); */

					$imageData = base64_decode($base64);
					$img = imagecreatefromstring($imageData);

					// Rotate if required
					$img = imagerotate($img, -90, 0);

					$width  = imagesx($img);
					$height = imagesy($img);

					$bgColor = imagecolorat($img, 0, $height - 1);

					// Find last non-white row
					$cropHeight = $height;

					for ($y = $height - 1; $y >= 0; $y--) {
						for ($x = 0; $x < $width; $x++) {
							if (imagecolorat($img, $x, $y) !== $bgColor) {
								$cropHeight = $y + 1;
								break 2;
							}
						}
					}

					// Crop
					$cropped = imagecrop($img, [
						'x'      => 0,
						'y'      => 0,
						'width'  => $width,
						'height' => $cropHeight
					]);

					// Save (GIF preferred for UPS)
					imagegif($cropped, $LabelPrint);

					// Cleanup
					imagedestroy($img);
					imagedestroy($cropped);

				}

				$LabelId = $UpsData['ShipmentResponse']['ShipmentResults']['ShipmentIdentificationNumber']??'';
				$shippingResdata = array(
					'LabelId' => $LabelId,
					'tracking_number' => $tracking_number,
					'LabelPrint' => $LabelPrint,
					'carrier' => 'ups',
					'service_type' => $service_type,
				);
				if($orderIndex>=0){
					if($store=='Bodi4life' || $store == 'Bodi2business' || $store=='Equine'){
						$customerInfo['Order'][$orderIndex]['OrderStatus']='Shipped';
						$customerInfo['Order'][$orderIndex]['OrderLabelId']=$LabelId;
						$customerInfo['Order'][$orderIndex]['OrderLabelPrint']=$LabelPrint;
						//$customerInfo['Order'][$orderIndex]['OrderCarrierFeeRetail']=$packaging_price;
						$customerInfo['Order'][$orderIndex]['OrderCarrierFeeCost']=$packaging_price;
						$customerInfo['Order'][$orderIndex]['OrderLastUpDate']=date('Y-m-d');
						$customerInfo['Order'][$orderIndex]['OrderCarrierServiceAccount']=$OrderCarrierServiceAccount;

						if(strpos($service_type, 'ups_') !== false) {
						   $customerInfo['Order'][$orderIndex]['OrderCarrier']='ups';
						}
						else if(strpos($service_type, 'usps_') !== false) {
						    $customerInfo['Order'][$orderIndex]['OrderCarrier']='usps';
						}

						//OrderTracking------------
						$OrderTracking = array();
						array_push($OrderTracking,$tracking_number);
						if(isset($customerInfo['Order'][$orderIndex]['OrderTracking']) && is_array($customerInfo['Order'][$orderIndex]['OrderTracking']) && !empty($customerInfo['Order'][$orderIndex]['OrderTracking'])) {
							foreach($customerInfo['Order'][$orderIndex]['OrderTracking'] as $prevTrack) {
								if($prevTrack != '') {
									array_push($OrderTracking,$prevTrack);
								}
							}
						}
						else if(isset($customerInfo['Order'][$orderIndex]['OrderTracking']) && !is_array($customerInfo['Order'][$orderIndex]['OrderTracking']) && $customerInfo['Order'][$orderIndex]['OrderTracking']!='') {
							array_push($OrderTracking,$customerInfo['Order'][$orderIndex]['OrderTracking']);
						}
						$customerInfo['Order'][$orderIndex]['OrderTracking']=$OrderTracking;
						//OrderTracking------------
						$customerInfo = $this->arrangeCustomer($customerInfo);
						$this->saveFile($customerInfoDir.$file.'.json', $customerInfo);
					}
					else if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop') {
						if($customerIndex>=0){
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderStatus']='Shipped';
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderLabelId']=$LabelId;
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderLabelPrint']=$LabelPrint;
							//$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderCarrierFeeRetail']=$packaging_price;
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderCarrierFeeCost']=$packaging_price;
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderLastUpDate']=date('Y-m-d');
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderCarrierServiceAccount']=$OrderCarrierServiceAccount;

							if(strpos($service_type, 'ups_') !== false) {
							    $orderInfo[$customerIndex]['Order'][$orderIndex]['OrderCarrier']='ups';
							}
							else if(strpos($service_type, 'usps_') !== false) {
							    $orderInfo[$customerIndex]['Order'][$orderIndex]['OrderCarrier']='usps';
							}

							//OrderTracking------------
							$OrderTracking = array();
							array_push($OrderTracking,$tracking_number);
							if(isset($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']) && is_array($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']) && !empty($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking'])) {
								foreach($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking'] as $prevTrack) {
									if($prevTrack != '') {
										array_push($OrderTracking,$prevTrack);
									}
								}
							}
							else if(isset($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']) && !is_array($orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']) && $orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']!='') {
								array_push($OrderTracking,$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']);
							}
							$orderInfo[$customerIndex]['Order'][$orderIndex]['OrderTracking']=$OrderTracking;
							//OrderTracking------------

							$this->saveFile($customerInfoDir.$file.'.json', $orderInfo);
						}
					}
					$this->updateLog(array('store'=>$store));
				}
			}
		}




		if(!empty($shippingResdata)){
			$result['SUCCESS'] = true;
			$result['DATA'] = $shippingResdata;
		}
		else {
			$result['SUCCESS'] = false;
			$result['ERROR'] = 'Something went wrong!';
		}
		return $result;
	}
	public function getProductListData(){
		return array(
			'products' => $this->getProductList()
		);
	}
	public function getCustomerListData(){
		return array(
			'customers' => $this->getCustomerList()
		);
	}
	public function getProductList() {
		$retail = new Retail();
        $inventoryFiles = $this->inventory->getList();
        $products = array();
        $cnt=0;
        foreach ($inventoryFiles as $filename) {
            $data = $this->inventory->loadInventory($filename);
            if (is_array($data)) {
                foreach ($data as $i => $product) {
                	$cnt++;
                	if($cnt>=50000){
						break;
					}
                	$product['Format'] = $this->inventory->removeExt($filename);
                	/*$attributes = array('4oz');
                	if (isset($product['Retail']) && is_array($product['Retail'])) {
						$attributes = array_keys($product['Retail']);
					}*/
					//if($product['Product'] == 'Tongkat Ali Root 10:1 Extract Powder') {
					//	pr($product['Retail']);
					//}

					$attributes = array();
					if (isset($product['Retail']) && is_array($product['Retail'])) {
						foreach($product['Retail'] as $RetailIndex => $retailRow) {
							if($RetailIndex!='NONE' && isset($retailRow['RetailSize']) && $retailRow['RetailSize']!='' && isset($retailRow['RetailUnit']) && $retailRow['RetailUnit']!='') {
								$attribute = $retailRow['RetailSize'].''.$retailRow['RetailUnit'];
								array_push($attributes,$attribute);
							}
						}
					}
                	$proImgUrl = '';
					$firstImg = '';
					if(!empty($product['Image'])){
						$imgCnt = 0;
						foreach($product['Image'] as $ProImg){
							if($ProImg!=''){
								$imgCnt++;
								if($imgCnt==1){
									$firstImg = $ProImg;
								}
								if(strpos($ProImg, "_2.jpg") !== false){
									$proImgUrl = $ProImg;
								}
							}
						}
					}
					/*if($proImgUrl==''){
						if($firstImg!=''){
							$proImgUrl = $firstImg;
						} else {
							continue;
						}
					}*/
					$SKUArr = array();
					$isfoundRetail = false;
					if(isset($product['Retail']) && is_array($product['Retail']) && !empty($product['Retail']) && $product['Retail'] != '') {
						foreach($product['Retail'] as $RetailIndex => $RetailRow){
							if($RetailIndex != '') {
								array_push($SKUArr, $RetailIndex);
							}
						}
					}
					else {
						continue;
					}
					if(empty($SKUArr)){
						continue;
					}
					$ProductName = $product['Product'];
					$Specification = '';
					if(isset($product['Title']['ProductName']) && $product['Title']['ProductName'] != '') {
						$ProductName = $product['Title']['ProductName'];
					}
					if(isset($product['Title']['Specification']) && $product['Title']['Specification'] != '') {
						$Specification = $product['Title']['Specification'];
					}

                	$products[] = array(
                		'label' => $product['Product'],
                		'SKU' => $SKUArr,
                		'value' => array(
                    		'inventory' => $this->inventory->removeExt($filename),
                    		'product' => $product['Product'],
                    		'SubCategory' => $product['SubCategory']??'',
                    		'CategoryStoreAccount' => $product['CategoryStoreAccount'],
                    		'itemData' => array(
                    			'Format' => $this->inventory->removeExt($filename),
                    			'Product' => $product['Product'],
                    			'ProductName' => $ProductName,
                    			'Specification' => $Specification,
                    			'StockMin' => $product['StockMin'],
                    			'Retail' => $product['Retail'],
                    			'Suppliers' => $product['Suppliers'],
                    			'SuppliersPricing' => $product['SuppliersPricing'],
                    			'StoreListingASIN' => $product['StoreListingASIN'] ?? '',
                    			'Image' => $proImgUrl
                    		),
                    		'attributes' => $attributes,
                		),
                	);
                }
            }
        }
        usort($products, function($a, $b) {
        	return strcmp($a['label'], $b['label']);
        });
        return $products;
	}
	public function getCustomerList() {
        $customers = array();
        $stores = array('Equine', 'Amazon', 'Bodi4life', 'Bodi2business', 'Ebay', 'BodiShop', 'Etsy');
        $orders = array();
		foreach ($stores as $store) {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			//Read Log---
			$customerLogData = $this->loadFile($customerInfoDir.'_log.json');
			if(!empty($customerLogData)){
				foreach($customerLogData as $customerLogRow) {
					//Read from customer file---
					$fileName = $customerLogRow['CustomerID'];
					$customerInfo = $this->loadFile($customerInfoDir.$fileName.'.json');
					$Username = '';
					$Zipcode = '';
					$exfileName = explode('+', $fileName);
					if(isset($exfileName[0]) && isset($exfileName[1])){
						$Username = $exfileName[1];
						$Zipcode = $exfileName[0];
					}
					$customer = array();
					$customer['Phone'] = isset($customerInfo['Phone'])?$customerInfo['Phone']:'';
					$customer['CustomerName'] = isset($customerInfo['CustomerName'])?$customerInfo['CustomerName']:'';
					$customer['Email'] = isset($customerInfo['Email'])?$customerInfo['Email']:'';
					$customer['Username'] = $Username;
					$customer['Zipcode'] = $Zipcode;
					$customer['Password'] = isset($customerInfo['Password'])?$customerInfo['Password']:'';
					$customer['OrderRetailStore'] = $store;
					$customer['fileName'] = $fileName;
					array_push($customers,$customer);
				}
			}
		}
        return $customers;
	}
	public function getOrderTemplate($options){
		$OrderStore = $options['OrderStore'];
		if($OrderStore == 'BodiStaff') {
			$singleOrderData = $this->loadFile("../Staff/Contact/contact-template.json");
		}
		else {
			$singleOrderData = $this->loadFile("template.json");
		}
		$orderRow = $singleOrderData['Order'][0];
		$OrderDate = date('Y-m-d H:i:s');
		$orderRow['OrderDate'] = 'new-'.$OrderDate;
		//$orderRow['OrderDateShow'] = 'NEW - '.(date('Y-m-d h:i A', strtotime($OrderDate)));
		$orderRow['OrderDateShow'] = date('Y-m-d h:i A', strtotime($OrderDate));
		$orderRow['OrderStatus'] = 'Ordered';
		$orderRow['OrderCarrier'] = 'usps';
		$orderRow['OrderCarrierService'] = 'ground';
		$singleOrderData['Order'] = $orderRow;
		$singleOrderData['OrderRetailStore'] = "";
		$singleOrderData['fileName'] = "";
		$singleOrderData['Username'] = "";
		$singleOrderData['Zipcode'] = "";
		$singleOrderData['prevOrderDates'] = "";
		$singleOrderData['CartipAddress'] = "";
		$orders[] = $singleOrderData;
		return array(
			'orders' => $orders,
			'setting' => $this->inventory->loadJson($this->settingPath),
			'supplierLog' => $this->inventory->loadJson($this->supplierLogPath),
		);
	}
	public function getSingleOrder($options){
		$result = array('success' => false, 'orders' => '', 'errMsg' => '');
		$filePath = $options['filePath'];
		$fileName = $options['fileName'];
		$OrderDate = $options['OrderDate'];
		$OrderStore = $options['OrderStore'];
		$Username = '';
		$Zipcode = '';

		$singleOrderData = $this->loadFile("template.json");
		if (file_exists($filePath.'/'.$fileName.'.json')) {

			$isOrderFound = false;
			$prevOrderDates = array();
			$singleOrder = '';
			if($OrderStore == 'Bodi4life' || $OrderStore == 'Bodi2business' || $OrderStore == 'Equine') {
				$customerInfo = $orderFileData = $this->loadFile($filePath.'/'.$fileName.'.json');
				if(isset($orderFileData['Order']) && !empty($orderFileData['Order'])) {
					foreach($orderFileData['Order'] as $orderRow) {
						if(isset($orderRow['OrderDate']) && $orderRow['OrderDate'] != '' && $orderRow['OrderDate'] == $OrderDate) {
							$isOrderFound = true;
							$orderRow['OrderDateShow'] = date('Y-m-d h:i A', strtotime($orderRow['OrderDate']));
							$singleOrder = $orderRow;
							if(isset($orderRow['OrderDate']) && $orderRow['OrderDate'] != ''){
								$prevOrderDates[] = date('Y-m-d h:i A', strtotime($orderRow['OrderDate']));
							}
						}
					}
				}
				if(!$isOrderFound) {
					$result['success'] = false;
					$result['errMsg'] = 'Order not found';
					return $result;
				}
				rsort($prevOrderDates);


				$isCart = false;
				if (strpos($filePath, 'Cart') !== false) {
				    $isCart = true;
				}
				if(!$isCart) {
					$Username = '';
					$Zipcode = '';
					$exfileName = explode('+', $fileName);
					if(isset($exfileName[0]) && isset($exfileName[1])){
						$Username = $exfileName[1];
						$Zipcode = $exfileName[0];
					}
				}
				//Read from Cart file (IP address)
				else {

				}

			}
			else {
				$customerInfo = $this->loadFile('template.json');
				$orderFileData = $this->loadFile($filePath.'/'.$fileName.'.json');

				if(!empty($orderFileData)) {
					foreach($orderFileData as $orderMRow) {
						if(isset($orderMRow['Order']) && !empty($orderMRow['Order'])) {
							foreach($orderMRow['Order'] as $orderRow) {
								if(isset($orderRow['OrderDate']) && $orderRow['OrderDate'] != '' && $orderRow['OrderDate'] == $OrderDate) {
									$isOrderFound = true;
									$orderRow['OrderDateShow'] = date('Y-m-d h:i A', strtotime($orderRow['OrderDate']));
									$singleOrder = $orderRow;
									if(isset($orderRow['OrderDate']) && $orderRow['OrderDate'] != ''){
										$prevOrderDates[] = date('Y-m-d', strtotime($orderRow['OrderDate']));
									}
								}
							}
						}
					}
				}
				if(!$isOrderFound) {
					$result['success'] = false;
					$result['errMsg'] = 'Order not found';
					return $result;
				}

			}
			$obj = $customerInfo;
			$obj['OrderRetailStore'] = $OrderStore;
			$obj['Order'] = $singleOrder;
			$obj['fileName'] = $fileName;
			$obj['Username'] = $Username;
			$obj['Zipcode'] = $Zipcode;
			$obj['prevOrderDates'] = $prevOrderDates;
			$obj['CartipAddress'] = '';
			$orders[] = $obj;


			return array(
				'orders' => $orders,
				'setting' => $this->inventory->loadJson($this->settingPath),
				'supplierLog' => $this->inventory->loadJson($this->supplierLogPath),
			);

		}
		else {
			$result['success'] = false;
			$result['errMsg'] = 'File not found';
			return $result;
		}
		return $result;
	}
	public function msort($array, $key, $sort_flags = SORT_REGULAR, $order = SORT_DESC) {
	    if (is_array($array) && count($array) > 0) {
	        if (!empty($key)) {
	            $mapping = array();
	            foreach ($array as $k => $v) {
	                $sort_key = '';
	                if (!is_array($key)) {
	                    $sort_key = $v[$key];
	                } else {
	                    foreach ($key as $key_key) {
	                        $sort_key .= $v[$key_key];
	                    }
	                    $sort_flags = SORT_STRING;
	                }
	                $mapping[$k] = $sort_key;
	            }
	            switch ($order) {
					case SORT_ASC:
						asort($mapping, $sort_flags);
						break;
					case SORT_DESC:
						arsort($mapping, $sort_flags);
						break;
				}
	            $sorted = array();
	            foreach ($mapping as $k => $v) {
	                $sorted[] = $array[$k];
	            }
	            return $sorted;
	        }
	    }
	    return $array;
	}
	public function msortASC($array, $key, $sort_flags = SORT_REGULAR, $order = SORT_ASC) {
	    if (is_array($array) && count($array) > 0) {
	        if (!empty($key)) {
	            $mapping = array();
	            foreach ($array as $k => $v) {
	                $sort_key = '';
	                if (!is_array($key)) {
	                	if(isset($v[$key])) {
							$sort_key = $v[$key];
						}

	                } else {
	                    // @TODO This should be fixed, now it will be sorted as string
	                    foreach ($key as $key_key) {
	                        $sort_key .= $v[$key_key];
	                    }
	                    $sort_flags = SORT_STRING;
	                }
	                $mapping[$k] = $sort_key;
	            }
	            switch ($order) {
					case SORT_ASC:
						asort($mapping, $sort_flags);
						break;
					case SORT_DESC:
						arsort($mapping, $sort_flags);
						break;
				}
	            //asort($mapping, $sort_flags);
	            $sorted = array();
	            foreach ($mapping as $k => $v) {
	                $sorted[] = $array[$k];
	            }
	            return $sorted;
	        }
	    }
	    return $array;
	}
	//From Order ---
	public function getCustomerByFile($customer) {
		$res = array('Success' => 0, 'customer' => '');
		$OrderRetailStore = isset($customer['OrderRetailStore'])?$customer['OrderRetailStore']:'';
		$CustomerFile = isset($customer['CustomerFile'])?$customer['CustomerFile']:'';
		$customerInfoDir = "../../bodiforbusiness/retail/{$OrderRetailStore}/";
		$customerInfo = $this->loadFile($customerInfoDir.$CustomerFile.'.json');
		unset($customerInfo['Favorite']);
		unset($customerInfo['Order']);
		$res = array('Success' => 1, 'customer' => $customerInfo);
        return $res;
	}
	public function array_union($x, $y) {
		$aunion=  array_merge(
		    array_intersect($x, $y),
		    array_diff($x, $y),
		    array_diff($y, $x)
		);
		return $aunion;
	}
	public function syncOrderLog() {
		$customerLogTemplateDir = "../../bodiforbusiness/retail/";
		$customerLogTemplate = $this->loadFile($customerLogTemplateDir."_log-template.json");
		$stores = array('Equine', 'Amazon', 'Bodi4life', 'Bodi2business', 'Ebay', 'BodiShop', 'Etsy');
		foreach ($stores as $store) {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";

			//From Customer file---
			$fileNameArr = array();
			$fileNameArr = preg_grep("/.*\.json$/", scandir($customerInfoDir));
			$customerLogData = array();
			if(!empty($fileNameArr)) {
				foreach($fileNameArr as $fileNameTemp) {
					$fileName = str_replace('.json','',$fileNameTemp);
					$customerInfo = $this->loadFile($customerInfoDir.$fileNameTemp);
					if (isset($customerInfo['Order']) && is_array($customerInfo['Order'])) {
						$orderStatusArr = array();
	        			foreach($customerInfo['Order'] as $order) {
	        				if($order['OrderStatus']!=''){
								if(!in_array($order['OrderStatus'], $orderStatusArr)){
									array_push($orderStatusArr, $order['OrderStatus']);
								}
							}
	        			}
	        			if(!empty($orderStatusArr)){
							$logTemplate = $customerLogTemplate;
							$logTemplate['CustomerID'] = $fileName;
							$logTemplate['CustomerStatus'] = 'Good'; //Need to check it in blocked json file.
							$logTemplate['OrderActive'] = $orderStatusArr;

							if(!empty($customerLogData)){
								foreach($customerLogData as $customerLogKey => $customerLogRow){
									if($customerLogRow['CustomerID'] == $fileName) {
										$is_found = true;
										$logTemplate['OrderActive'] = $this->array_union($customerLogRow['OrderActive'], $logTemplate['OrderActive']);
										$customerLogData[$customerLogKey] = $logTemplate;
										break;
									}
								}
								if(!$is_found) {
									array_push($customerLogData, $logTemplate);
								}
							} else {
								array_push($customerLogData, $logTemplate);
							}
						}
					}
				}
			}
			//From Order file for "Cart" Status---
			$fileNameArr = preg_grep("/.*\.json$/", scandir('../'.$store.'/'));
			if(!empty($fileNameArr)) {
				foreach($fileNameArr as $fileNameTemp) {
					$fileName = str_replace('.json','',$fileNameTemp);
					$fileData = $this->loadInfoByStore($store, $fileName);
					$CustomerID = $fileData['CustomerID'];
					if($CustomerID != '' && isset($fileData['Order']) && is_array($fileData['Order'])) {
						$orderStatusArr = array();
						foreach($fileData['Order'] as $order) {
							if($order['OrderStatus']!=''){
		        				if(!in_array($order['OrderStatus'], $orderStatusArr)){
									array_push($orderStatusArr, $order['OrderStatus']);
								}
							}
	        			}
	        			if(!empty($orderStatusArr)){
		        			$logTemplate = $customerLogTemplate;
							$logTemplate['CustomerID'] = $CustomerID;
							$logTemplate['CustomerStatus'] = 'Good'; //Need to check it in blocked json file.
							$logTemplate['OrderActive'] = $orderStatusArr;
							if(!empty($customerLogData)){
								foreach($customerLogData as $customerLogKey => $customerLogRow){
									if($customerLogRow['CustomerID'] == $CustomerID) {
										$is_found = true;
										$logTemplate['OrderActive'] = $this->array_union($customerLogRow['OrderActive'], $logTemplate['OrderActive']);
										$customerLogData[$customerLogKey] = $logTemplate;
										break;
									}
								}
								if(!$is_found) {
									array_push($customerLogData, $logTemplate);
								}
							} else {
								array_push($customerLogData, $logTemplate);
							}
						}
	        		}
				}
			}
			if(isset($customerLogData)){
				$this->saveFile($customerInfoDir.'_log.json', $customerLogData);
			}
		}
		return true;
	}

	public function updateOrderLogByCustomerId($CustomerID=null, $store=null) {
		if(!$CustomerID){
			return false;
		}
		if(!$store){
			$stores = array('Equine', 'Amazon', 'Bodi4life', 'Bodi2business', 'Ebay', 'BodiShop', 'Etsy');
		}
		else {
			$stores = array($store);
		}
		/*
		"CustomerID": 400,
        "CustomerName": 400,
        "Email": "",
        "Phone": "",
        "CustomerStatus": "Good",
        "OrderStatus": {
            "2022-02-05": "Delivered"
        }
		*/
		$customerLogTemplateDir = "../../bodiforbusiness/retail/";
		$customerLogTemplate = $this->loadFile($customerLogTemplateDir."_log-template.json");
		foreach ($stores as $store) {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerLogData = $this->loadFile($customerInfoDir.'_log.json');
			$customerLogIndex = -1;
			if(!empty($customerLogData)){
				$is_indexfound = false;
				foreach($customerLogData as $customerLogIndex => $customerLogRow){
					if($customerLogRow['CustomerID'] == $CustomerID) {
						$is_indexfound = true;
						break;
					}
				}
				if(!$is_indexfound){
					$customerLogIndex++;
				}
			}

			//From Customer file---
			$customerInfo = $this->loadFile($customerInfoDir.$CustomerID.'.json');
			if (isset($customerInfo['Order']) && is_array($customerInfo['Order'])) {
				$orderStatusArr = array();
    			foreach($customerInfo['Order'] as $order) {
    				if($order['OrderStatus']!=''){
						$orderStatusArr[$order['OrderDate']] = $order['OrderStatus'];
					}
    			}
    			if(!empty($orderStatusArr)){
					$logTemplate = $customerLogTemplate;
					$logTemplate['CustomerID'] = $CustomerID;
					$logTemplate['CustomerName'] = isset($customerInfo['CustomerName'])?$customerInfo['CustomerName']:'';
					$logTemplate['Email'] = isset($customerInfo['Email'])?$customerInfo['Email']:'';
					$logTemplate['Phone'] = isset($customerInfo['Phone'])?$customerInfo['Phone']:'';
					$logTemplate['CustomerStatus'] = 'Good';
					if($is_indexfound){
						if(!empty($customerLogData[$customerLogIndex]['OrderStatus'])){
							foreach($customerLogData[$customerLogIndex]['OrderStatus'] as $OrderDate => $OrderStatus){
								foreach($orderStatusArr as $OrderDateNew => $OrderStatusNew){
									if($OrderDate == $OrderDateNew) {
										$customerLogData[$customerLogIndex]['OrderStatus'][$OrderDateNew] = $OrderStatusNew;
										unset($orderStatusArr[$OrderDateNew]);
									}
								}
							}
							if(!empty($orderStatusArr)) {
								foreach($orderStatusArr as $OrderDateNew => $OrderStatusNew){
									$customerLogData[$customerLogIndex]['OrderStatus'][$OrderDateNew] = $OrderStatusNew;
								}
							}


							$logTemplate['OrderStatus'] = $customerLogData[$customerLogIndex]['OrderStatus'];
						}
					}
					$customerLogData[$customerLogIndex] = $logTemplate;
					$is_indexfound = true;
				}

			}
			else {
				//if file is removed---
				if($is_indexfound){
					array_splice($customerLogData, $customerLogIndex, 1);
				}
			}
			if(isset($customerLogData)){
				$this->saveFile($customerInfoDir.'_log.json', $customerLogData);
			}
		}
		return true;
	}
	public function removeOrderLogByCustomerId($CustomerID=null, $store=null) {
		if(!$CustomerID){
			return false;
		}
		if(!$store){
			return false;
		}
		$stores = array($store);
		foreach ($stores as $store) {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerLogData = json_decode(file_get_contents($customerInfoDir.'_log.json'), true);
			$customerLogIndex = -1;
			if(!empty($customerLogData)){
				foreach($customerLogData as $customerLogIndex => $customerLogRow){
					if($customerLogRow['CustomerID'] == $CustomerID) {
						array_splice($customerLogData, $customerLogIndex, 1);
						$this->saveFile($customerInfoDir.'_log.json', $customerLogData);
						return true;
					}
				}
			}
		}
		return false;
	}
	public function getPrice($data) {
		$rs = array('success' => true);
		$inventory = $data['inventory'];
		$productName = $data['product'];
		$attribute = $data['attribute'];
		//load inventory
		$inventoryData = $this->inventory->loadInventory($inventory);
		if (!$inventoryData) {
			$rs['success'] = false;
			$rs['err'] = "Can't load inventory {$inventory}";
			return $rs;
		}
		//search product
		$product = null;
		foreach ($inventoryData as $key => $item) {
			if ($item['Product'] == $productName) {
				$product = $item;
				break;
			}
		}
		if (!$product) {
			$rs['success'] = false;
			$rs['err'] = "Product {$productName} not found";
			return $rs;
		}
		//check retail
		$is_attrFound = false;
		$sizeData = array();
		if (isset($product['Retail']) && is_array($product['Retail'])) {
			foreach($product['Retail'] as $RetailIndex => $retailRow) {
				if($RetailIndex!='NONE' && $retailRow['RetailSize']!='' && $retailRow['RetailUnit']!='' && $RetailIndex != 'Bulk' && $RetailIndex != 'Recipe') {
					$attr = $retailRow['RetailSize'].''.$retailRow['RetailUnit'];
					if($attribute==$attr) {
						$is_attrFound = true;
						$sizeData = $retailRow;
						break;
					}
				}
			}
		}



		if (!$is_attrFound) {
			$rs['success'] = false;
			$rs['err'] = "{$attribute} not found";
			return $rs;
		}
		$product['inventory'] = $inventory;
		//pr($product);die;
		$productForReturn = array();
		$productForReturn['inventory'] = $inventory;
		$productForReturn['Suppliers'] = $product['Suppliers'];
		$productForReturn['Retail'] = $product['Retail'];
		$productForReturn['SuppliersPricing'] = $product['SuppliersPricing'];
		//calculate price
		$rs['product'] = $productForReturn;
		$rs['sizeData'] = $sizeData;
		return $rs;
	}
	public function getProductBySKU($reqdata) {
		$rs = array('success' => true, 'DATA' => '');
		$OrderProductSKU = $reqdata['OrderProductSKU'];

		if($OrderProductSKU != '') {
			//SKUCategory
			$OrderProductSKUArr = explode('.',$OrderProductSKU); //Juic.Acai.Berry.Powd.4oz
			$longFilename = $sortFilename = isset($OrderProductSKUArr[0])?$OrderProductSKUArr[0]:'';
			$proPart1 = isset($OrderProductSKUArr[1])?$OrderProductSKUArr[1]:'';
			$proPart2 = '';
			$proPart3 = '';
			$attribute = '';
			if(!is_numeric($OrderProductSKU) && $proPart1 != '') {
				$setting = $this->inventory->loadJson($this->settingPath);
				$SKUCategoryStr = $setting['SKUCategory'];
				$SKUCategoryStr = str_replace('(','',$SKUCategoryStr);
				$SKUCategoryStr = str_replace(')','',$SKUCategoryStr);

				$SKUCategoryArr = explode(',',$SKUCategoryStr);
				foreach($SKUCategoryArr as $SKUCategoryEach) {
					$SKUCategoryEachArr = explode(' ', trim($SKUCategoryEach));
					if($SKUCategoryEachArr[1] == $sortFilename) {
						$longFilename = trim($SKUCategoryEachArr[0]);
						break;
					}
				}

				$inventoryFiles = $this->inventory->getList();
			}
			else {
				$inventoryFiles = $this->inventory->getList();
			}
	        $products = array();
	        $cnt=0;
	        foreach ($inventoryFiles as $filename) {
	        	$chkedFilename = false;
                if(!is_numeric($OrderProductSKU) && $proPart1!='') {
                	$fileposition = stripos($filename, $longFilename);
                	if (is_numeric($fileposition)) {
                		$chkedFilename = true;
					}
				}
	        	else {
					$chkedFilename = true;
				}
		        if ($chkedFilename) {
		            $data = $this->inventory->loadInventory($filename);
		            if (is_array($data)) {
                		foreach ($data as $i => $product) {
                			$product['Format'] = $this->inventory->removeExt($filename);
                			$chkRetail = false;
                			if(!is_numeric($OrderProductSKU) && $proPart1!='') {
								$proposition = stripos($product['Product'], $proPart1);
								if(is_numeric($proposition)) {
									$chkRetail = true;
								}
							}
							else {
								$chkRetail = true;
							}
                			if ($chkRetail) {
		        				if(isset($product['Retail']) && is_array($product['Retail']) && !empty($product['Retail']) && $product['Retail'] != '') {
									foreach($product['Retail'] as $RetailIndex => $RetailRow){
										$attribute = $RetailRow['RetailSize'].''.$RetailRow['RetailUnit'];
										if($RetailIndex == $OrderProductSKU) {
											$rs['success'] = true;
											//calculate price
											//$inventory = $filename;
											$product['inventory'] = $this->inventory->removeExt($filename);
											$rs['product'] = $product;
											$rs['sizeData'] = $product['Retail'][$RetailIndex];
											$rs['attribute'] = $attribute;
											$rs['shipweight'] = $RetailRow['ShipWeight'];
											return $rs;
										}
									}
								}
							}

						}
					}
		        }
			}
			$rs['success'] = false;
			$rs['err'] = 'Invalid SKU';
			return $rs;
		}
		$rs['success'] = false;
		$rs['err'] = 'Please enter SKU';
        return $rs;
    }
	public function saveFile($filename, $data) {
		$save = file_put_contents($filename . '_temp', json_encode($data, JSON_PRETTY_PRINT));
		if ($save) {
			$move = rename($filename . '_temp', $filename);
			return true;
		}
		return false;
	}
	public function getCustomerFilename($customerLog) {
		return reset($customerLog);
	}
	public function loadInfo($customerLog) {
		$filename = $this->getCustomerFilename($customerLog);
		if (!is_file($this->folderPath . $filename . '.json')) {
			return null;
		}

		return json_decode(file_get_contents($this->folderPath . $filename . '.json'), true);
	}
	public function enableOrder($customer) {
		$customerLog = $this->loadFile('customers-log.json');
		foreach ($customerLog as &$log) {
			if ($log['CustomerName'] == $customer['CustomerName'] && ($log['Phone'] == $customer['CustomerFile'] || $log['Email'] == $customer['CustomerFile'])) {
				$log['OrderStatus'] = "true";
				if ($this->saveFile('customers-log.json', $customerLog)) {
					return $log;
				}
			}
		}
		return false;
	}
	public function addItem($store, $file, $OrderDate, $item) {
		$rs = array('success' => true);
		$isNew = strpos($file, 'new-') !== false;
		if ($isNew) {
			if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop'){
				$_SESSION['isNew'] = 'New';
				$customer = array();
				$customer['OrderItems'] = array();
				$customer['Order']['OrderRetailStore'] = $store;
				$customer['Order']['OrderStatus'] = 'Delivered';
				$customer['Order']['OrderCarrier'] = isset($customer['Carrier'])?$customer['Carrier']:'';
				$customer['Order']['OrderCarrierService'] = isset($customer['CarrierService'])?$customer['CarrierService']:'';
				$customer['Username'] = isset($customer['Username'])?$customer['Username']:'';
				$customer['Zipcode'] = isset($customer['Zipcode'])?$customer['Zipcode']:'';
				$result = $this->createQuickOrder($customer);
				if($result['success']){
					$file = $result['fileName'];
					$OrderDate = $result['OrderDate'];
					$CustomerID = $result['CustomerID'];
				}
				else {
					$rs['success'] = false;
					$rs['err'] = "Can't find Order..";
					return $rs;
				}
			}
			else {
				$rs['success'] = false;
				$rs['err'] = "Invalid Store..";
				return $rs;
			}
		}
		//File Checking-------
		$fromOrderTempLog = false;
		$fileChkArr = explode('+',$file);
		if($fileChkArr[0] == 'OrderTempLogData') {
			$fromOrderTempLog = true;
			$fromCustomerName = '';
			$fromEmail = '';
			$fromZipcode = '';
			if(isset($fileChkArr[1]))
				$fromCustomerName = $fileChkArr[1];
			if(isset($fileChkArr[2]))
				$fromEmail = $fileChkArr[2];
			if(isset($fileChkArr[3]))
				$fromZipcode = $fileChkArr[3];
		}
		//--------------------
		if($fromOrderTempLog){
			$AllOrderTempLog = $this->loadFile("OrderTempLogData.json");
			if(!empty($AllOrderTempLog)){
				foreach($AllOrderTempLog as $tempLogKey => $OrderTempLog) {
					$searchArr = array();
					if($fromCustomerName!=''){
						$searchArr['CustomerName'] = $fromCustomerName;
					} else if($fromEmail!=''){
						$searchArr['Email'] = $fromEmail;
					} else if($fromZipcode!=''){
						$searchArr['Zipcode'] = $fromZipcode;
					}
					if(empty($searchArr)){
						$rs = array(
							'success' => false,
							'err' => "Can't find Order Temp Log",
						);
						return $rs;
					}
					$found = true;
					foreach($searchArr as $searchOnField => $searchOn) {
						if($OrderTempLog[$searchOnField] != $searchOn){
							$found = false;
							break;
						}
					}
					if($found){
						if(!empty($OrderTempLog['Order'])){
							foreach($OrderTempLog['Order'] as $key => $order){
								if ($order['OrderDate'] == $OrderDate) {

									if (!isset($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderItems']) || !is_array($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderItems'])) {
										$AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderItems'] = array();
									}
									$AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderItems'][] = $item;

									$totalOrderPrice = 0.00;
									$totalProductPrice = 0.00;
									if(isset($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderItems'])){
										foreach($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderItems'] as $OrderItem) {
											if($OrderItem['OrderProduct']!=''){
												$itemTotal = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
												if(isset($OrderItem['OrderItemDiscount']) && $OrderItem['OrderItemDiscount']!=''){
													$OrderItemDiscount = (float)$OrderItem['OrderItemDiscount'];
													$itemTotal = $itemTotal-($itemTotal*$OrderItemDiscount/100);
												}
												$totalProductPrice += $itemTotal;
											}
										}
									}
									$totalOrderPrice += $totalProductPrice;

					                //Base Discount-----------------
					                $baseDiscountRate = isset($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderDiscount'])?$AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderDiscount']:0;
									$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
									$totalOrderPrice -= $baseDiscountAmount;

									//Coupon Code ---------
									$OrderCoupon = isset($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderCoupon'])?$AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderCoupon']:'';
									$couponCodeDiscountRate = $OrderCoupon!=''?$OrderCoupon:0;
									$couponDiscountAmount = $couponCodeDiscountRate;
									$totalOrderPrice -= $couponDiscountAmount;

					                $totalWithoutShipping = $totalOrderPrice;
					                //Shipping ---------
					                $OrderCarrierFeeRetail = isset($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderCarrierFeeRetail'])?$AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderCarrierFeeRetail']:'';
					                if($OrderCarrierFeeRetail!='') {
										$totalOrderPrice += (float)$OrderCarrierFeeRetail;
									}

									$totalOrderPrice = number_format($totalOrderPrice,2,".","");
									$AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderDiscount'] = "$baseDiscountRate";
									$AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderTotal'] = $totalOrderPrice;

									$filename = 'OrderTempLogData.json';
									$rs['success'] = $this->saveFile($filename, $AllOrderTempLog);
									$rs['Order'] = $AllOrderTempLog[$tempLogKey]['Order'][$key];
									return $rs;

								}
							}
						}
					}
				}
			}
		}
		else {

			$is_order_found = false;
			//For Ebay Order json file-----
			if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop'){
				$filename = $store. '/'. $file . '.json';
				$orderInfo = $this->loadFile($filename);

				//copy OrderCarrierCost => OrderCarrierFeeRetail
				if(isset($orderInfo['Order']) && !empty($orderInfo['Order'])) {
					foreach($orderInfo['Order'] as $oKey => $order) {
						if(!isset($order['OrderCarrierFeeRetail']) && isset($order['OrderCarrierCost'])) {
							$orderInfo['Order'][$oKey]['OrderCarrierFeeRetail'] = $order['OrderCarrierCost'];
							$orderInfo['Order'][$oKey]['OrderCarrierFeeCost'] = '';
						}
					}
				}


				if(count($orderInfo)>0){
					foreach($orderInfo as $OrderIndex => $orderInfoRow){
						foreach($orderInfoRow['Order'] as $key => $order) {
							if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
								$is_order_found = true;

								if (!isset($orderInfo[$OrderIndex]['Order'][$key]['OrderItems']) || !is_array($orderInfo[$OrderIndex]['Order'][$key]['OrderItems'])) {
									$orderInfo[$OrderIndex]['Order'][$key]['OrderItems'] = array();
								}
								$orderInfo[$OrderIndex]['Order'][$key]['OrderItems'][] = $item;

								$totalOrderPrice = 0.00;
								$totalProductPrice = 0.00;
								if(isset($orderInfo[$OrderIndex]['Order'][$key]['OrderItems'])){
									foreach($orderInfo[$OrderIndex]['Order'][$key]['OrderItems'] as $OrderItem) {
										if($OrderItem['OrderProduct']!=''){
											$itemTotal = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
											if(isset($OrderItem['OrderItemDiscount']) && $OrderItem['OrderItemDiscount']!=''){
												$OrderItemDiscount = (float)$OrderItem['OrderItemDiscount'];
												$itemTotal = $itemTotal-($itemTotal*$OrderItemDiscount/100);
											}
											$totalProductPrice += $itemTotal;
										}
									}
								}
								$totalOrderPrice += $totalProductPrice;

								//Base Discount-----------------
				                $baseDiscountRate = isset($orderInfo[$OrderIndex]['Order'][$key]['OrderDiscount']) && $orderInfo[$OrderIndex]['Order'][$key]['OrderDiscount']!=''?$orderInfo[$OrderIndex]['Order'][$key]['OrderDiscount']:0;
								$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
								$totalOrderPrice -= $baseDiscountAmount;

								//Coupon Code ---------
								$couponCodeDiscountRate = isset($orderInfo[$OrderIndex]['Order'][$key]['OrderCoupon']) && $orderInfo[$OrderIndex]['Order'][$key]['OrderCoupon']!=''?$orderInfo[$OrderIndex]['Order'][$key]['OrderCoupon']:0;
								$couponDiscountAmount = $couponCodeDiscountRate;
								$totalOrderPrice -= $couponDiscountAmount;

				                $totalWithoutShipping = $totalOrderPrice;
				                //Shipping ---------
				                $OrderCarrierFeeRetail = isset($orderInfo[$OrderIndex]['Order'][$key]['OrderCarrierFeeRetail']) && $orderInfo[$OrderIndex]['Order'][$key]['OrderCarrierFeeRetail']!=''?$orderInfo[$OrderIndex]['Order'][$key]['OrderCarrierFeeRetail']:'';
				                if($OrderCarrierFeeRetail!= '') {
									$totalOrderPrice += (float)$OrderCarrierFeeRetail;
								}

								$totalOrderPrice = number_format($totalOrderPrice,2,".","");
								$orderInfo[$OrderIndex]['Order'][$key]['OrderDiscount'] = "$baseDiscountRate";
								$orderInfo[$OrderIndex]['Order'][$key]['OrderTotal'] = $totalOrderPrice;

								$rs['success'] = $this->saveFile($filename, $orderInfo);
								$rs['Order'] = $orderInfo[$OrderIndex]['Order'][$key];
								$rs['fileName'] = $file;
								$rs['OrderDate'] = $OrderDate;
								$rs['CustomerID'] = isset($CustomerID)?$CustomerID:'';
								if ($isNew) {
									$option = array('store' => $store);
									$this->updateLog($option);
								}
								return $rs;
							}
						}
					}
				}
			}
			//For customer file----
			if(!$is_order_found){
				$customerInfoDir = "../../bodiforbusiness/{$store}/";
				$CustomerID = $file;
				$customerInfo = $this->loadFile($customerInfoDir.$CustomerID.'.json');
				foreach ($customerInfo['Order'] as $key => $order) {
					$dateToChk = $order['OrderDate'];
					if ($dateToChk == $OrderDate) {
						if (!isset($customerInfo['Order'][$key]['OrderItems']) || !is_array($customerInfo['Order'][$key]['OrderItems'])) {
							$customerInfo['Order'][$key]['OrderItems'] = array();
						}
						$customerInfo['Order'][$key]['OrderItems'][] = $item;
						$totalOrderPrice = 0.00;
						$totalProductPrice = 0.00;
						if(isset($customerInfo['Order'][$key]['OrderItems'])){
							foreach($customerInfo['Order'][$key]['OrderItems'] as $OrderItem) {
								if($OrderItem['OrderProduct']!=''){
									$itemTotal = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
									if(isset($OrderItem['OrderItemDiscount']) && $OrderItem['OrderItemDiscount']!=''){
										$OrderItemDiscount = (float)$OrderItem['OrderItemDiscount'];
										$itemTotal = $itemTotal-($itemTotal*$OrderItemDiscount/100);
									}
									$totalProductPrice += $itemTotal;
								}
							}
						}
						$totalOrderPrice += $totalProductPrice;

		                //Base Discount-----------------
		                $baseDiscountRate = isset($customerInfo['Order'][$key]['OrderDiscount'])?$customerInfo['Order'][$key]['OrderDiscount']:0;
						$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
						$totalOrderPrice -= $baseDiscountAmount;

						//Coupon Code ---------
						$couponCodeDiscountRate = isset($customerInfo['Order'][$key]['OrderCoupon'])?$customerInfo['Order'][$key]['OrderCoupon']:0;
						$couponDiscountAmount = $couponCodeDiscountRate;
						$totalOrderPrice -= $couponDiscountAmount;

		                $totalWithoutShipping = $totalOrderPrice;
		                //Shipping ---------
		                $OrderCarrierFeeRetail = isset($customerInfo['Order'][$key]['OrderCarrierFeeRetail'])?$customerInfo['Order'][$key]['OrderCarrierFeeRetail']:'';
		                if($OrderCarrierFeeRetail!=''){
							$totalOrderPrice += (float)$OrderCarrierFeeRetail;
						}

						$totalOrderPrice = number_format($totalOrderPrice,2,".","");
						$customerInfo['Order'][$key]['OrderTotal'] = $totalOrderPrice;

						$rs['success'] = $this->saveFile($customerInfoDir.$CustomerID.'.json', $customerInfo);
						$rs['Order'] = $customerInfo['Order'][$key];
						$rs['fileName'] = $file;
						$rs['OrderDate'] = $OrderDate;
						$rs['CustomerID'] = isset($CustomerID)?$CustomerID:'';
						return $rs;
					}
				}
			}
		}
		$rs['success'] = false;
		$rs['err'] = "Can't find Order";
		return $rs;
	}
	public function deleteItem($store, $file, $OrderDate, $itemName) {
		//File Checking-------
		$fromOrderTempLog = false;
		$fileChkArr = explode('+',$file);
		if($fileChkArr[0] == 'OrderTempLogData') {
			$fromOrderTempLog = true;
			$fromCustomerName = '';
			$fromEmail = '';
			$fromZipcode = '';
			if(isset($fileChkArr[1]))
				$fromCustomerName = $fileChkArr[1];
			if(isset($fileChkArr[2]))
				$fromEmail = $fileChkArr[2];
			if(isset($fileChkArr[3]))
				$fromZipcode = $fileChkArr[3];
		}
		//--------------------
		if($fromOrderTempLog){
			$AllOrderTempLog = $this->loadFile("OrderTempLogData.json");
			if(!empty($AllOrderTempLog)){
				foreach($AllOrderTempLog as $tempLogKey => $OrderTempLog) {
					$searchArr = array();
					if($fromCustomerName!=''){
						$searchArr['CustomerName'] = $fromCustomerName;
					} else if($fromEmail!=''){
						$searchArr['Email'] = $fromEmail;
					} else if($fromZipcode!=''){
						$searchArr['Zipcode'] = $fromZipcode;
					}
					if(empty($searchArr)){
						$rs = array(
							'success' => false,
							'err' => "Can't find Order Temp Log",
						);
						return $rs;
					}
					$found = true;
					foreach($searchArr as $searchOnField => $searchOn) {
						if($OrderTempLog[$searchOnField] != $searchOn){
							$found = false;
							break;
						}
					}
					if($found){
						if(!empty($OrderTempLog['Order'])){
							foreach($OrderTempLog['Order'] as $key => $order){
								if ($order['OrderDate'] == $OrderDate) {
									if (is_array($order['OrderItems'])) {
										foreach ($order['OrderItems'] as $j => $item) {
											if ($item['OrderProduct'] == $itemName) {
												array_splice($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderItems'], $j, 1);

												$totalOrderPrice = 0.00;
												$totalProductPrice = 0.00;
												if(isset($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderItems'])){
													foreach($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderItems'] as $OrderItem) {
														if($OrderItem['OrderProduct']!=''){
															$itemTotal = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
															if(isset($OrderItem['OrderItemDiscount']) && $OrderItem['OrderItemDiscount']!=''){
																$OrderItemDiscount = (float)$OrderItem['OrderItemDiscount'];
																$itemTotal = $itemTotal-($itemTotal*$OrderItemDiscount/100);
															}
															$totalProductPrice += $itemTotal;
														}
													}
												}
												$totalOrderPrice += $totalProductPrice;
												//Base Discount-----------------
												$baseDiscountRate = isset($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderDiscount'])?$AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderDiscount']:0;
												$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
												$totalOrderPrice -= $baseDiscountAmount;

												//Coupon Code ---------
												$OrderCoupon = isset($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderCoupon'])?$AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderCoupon']:'';
												$couponCodeDiscountRate = $OrderCoupon!=''?$OrderCoupon:0;
												$couponDiscountAmount = $couponCodeDiscountRate;
												$totalOrderPrice -= $couponDiscountAmount;

												$totalWithoutShipping = $totalOrderPrice;
												//Shipping ---------
												$OrderCarrierFeeRetail = isset($AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderCarrierFeeRetail'])?$AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderCarrierFeeRetail']:'';
												if($OrderCarrierFeeRetail!='') {
													$totalOrderPrice += (float)$OrderCarrierFeeRetail;
												}

												$totalOrderPrice = number_format($totalOrderPrice,2,".","");
												$AllOrderTempLog[$tempLogKey]['Order'][$key]['OrderTotal'] = $totalOrderPrice;


												$filename = 'OrderTempLogData.json';
												$rs['success'] = $this->saveFile($filename, $AllOrderTempLog);
												$rs['Order'] = $AllOrderTempLog[$tempLogKey]['Order'][$key];
												return $rs;
											}
										}
									} else {
										$rs['success'] = false;
										$rs['err'] = "No item found";
									}
								}
							}
						}
					}
				}
			}
		}
		else {
			$is_order_found = false;
			//For Ebay Order json file-----
			if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop'){
				$filename = $store. '/'. $file . '.json';
				$orderInfo = $this->loadFile($filename);

				//copy OrderCarrierCost => OrderCarrierFeeRetail
				if(isset($orderInfo['Order']) && !empty($orderInfo['Order'])) {
					foreach($orderInfo['Order'] as $oKey => $order) {
						if(!isset($order['OrderCarrierFeeRetail']) && isset($order['OrderCarrierCost'])) {
							$orderInfo['Order'][$oKey]['OrderCarrierFeeRetail'] = $order['OrderCarrierCost'];
							$orderInfo['Order'][$oKey]['OrderCarrierFeeCost'] = '';
						}
					}
				}

				if(count($orderInfo)>0){
					foreach($orderInfo as $OrderIndex => $orderInfoRow){
						foreach($orderInfoRow['Order'] as $key => $order) {
							if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
								$is_order_found = true;

								if (is_array($order['OrderItems'])) {
									foreach ($order['OrderItems'] as $j => $item) {
										if ($item['OrderProduct'] == $itemName) {
											array_splice($orderInfo[$OrderIndex]['Order'][$key]['OrderItems'], $j, 1);

											$totalOrderPrice = 0.00;
											$totalProductPrice = 0.00;
											if(isset($orderInfo[$OrderIndex]['Order'][$key]['OrderItems'])){
												foreach($orderInfo[$OrderIndex]['Order'][$key]['OrderItems'] as $OrderItem) {
													if($OrderItem['OrderProduct']!=''){
														$itemTotal = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
														if(isset($OrderItem['OrderItemDiscount']) && $OrderItem['OrderItemDiscount']!=''){
															$OrderItemDiscount = (float)$OrderItem['OrderItemDiscount'];
															$itemTotal = $itemTotal-($itemTotal*$OrderItemDiscount/100);
														}
														$totalProductPrice += $itemTotal;
													}
												}
											}
											$totalOrderPrice += $totalProductPrice;
											//Base Discount-----------------
											$baseDiscountRate = isset($orderInfo[$OrderIndex]['Order'][$key]['OrderDiscount']) && $orderInfo[$OrderIndex]['Order'][$key]['OrderDiscount']!=''?$orderInfo[$OrderIndex]['Order'][$key]['OrderDiscount']:0;
											$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
											$totalOrderPrice -= $baseDiscountAmount;

											//Coupon Code ---------
											$couponCodeDiscountRate = isset($orderInfo[$OrderIndex]['Order'][$key]['OrderCoupon']) && $orderInfo[$OrderIndex]['Order'][$key]['OrderCoupon']!=''?$orderInfo[$OrderIndex]['Order'][$key]['OrderCoupon']:0;
											$couponDiscountAmount = $couponCodeDiscountRate;
											$totalOrderPrice -= $couponDiscountAmount;

											$totalWithoutShipping = $totalOrderPrice;
											//Shipping ---------
											$OrderCarrierFeeRetail = isset($orderInfo[$OrderIndex]['Order'][$key]['OrderCarrierFeeRetail']) && $orderInfo[$OrderIndex]['Order'][$key]['OrderCarrierFeeRetail']!=''?$orderInfo[$OrderIndex]['Order'][$key]['OrderCarrierFeeRetail']:'';
											if($OrderCarrierFeeRetail!=''){
												$totalOrderPrice += (float)$OrderCarrierFeeRetail;
											}

											$totalOrderPrice = number_format($totalOrderPrice,2,".","");
											$orderInfo[$OrderIndex]['Order'][$key]['OrderTotal'] = $totalOrderPrice;


											$rs['success'] = $this->saveFile($filename, $orderInfo);
											$rs['Order'] = $orderInfo[$OrderIndex]['Order'][$key];
											return $rs;
										}
									}
								}

							}
						}
					}
				}
			}


			if(!$is_order_found){
				$rs = array('success' => true);
				$filename = $store. '/'. $file . '.json';
				$customerInfo = $this->loadFile($filename);

				//copy OrderCarrierCost => OrderCarrierFeeRetail
				if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
					foreach($customerInfo['Order'] as $oKey => $order) {
						if(!isset($order['OrderCarrierFeeRetail']) && isset($order['OrderCarrierCost'])) {
							$customerInfo['Order'][$oKey]['OrderCarrierFeeRetail'] = $order['OrderCarrierCost'];
							$customerInfo['Order'][$oKey]['OrderCarrierFeeCost'] = '';
						}
					}
				}

				if (!isset($customerInfo['Order'])) {
					$customerInfo['Order'] = array();
				}
				//For Order IP json file-----
				foreach ($customerInfo['Order'] as $key => $order) {
					if($store == 'Temp') {
						$dateToChk = date('Y-m-d H:i:s', strtotime($order['OrderDate']));
					}
					else {
						$lastModifiedOn = filemtime($fileName);
						$dateToChk = date('Y-m-d H:i:s', $lastModifiedOn);
					}
					if ($dateToChk == $OrderDate && ($order['OrderStatus'] == 'Cart' || $store == 'Temp')) {
						$is_order_found = true;
						if (is_array($order['OrderItems'])) {
							foreach ($order['OrderItems'] as $j => $item) {
								if ($item['OrderProduct'] == $itemName) {
									array_splice($customerInfo['Order'][$key]['OrderItems'], $j, 1);

									$totalOrderPrice = 0.00;
									$totalProductPrice = 0.00;
									if(isset($customerInfo['Order'][$key]['OrderItems'])){
										foreach($customerInfo['Order'][$key]['OrderItems'] as $OrderItem) {
											if($OrderItem['OrderProduct']!=''){
												$itemTotal = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
												if(isset($OrderItem['OrderItemDiscount']) && $OrderItem['OrderItemDiscount']!=''){
													$OrderItemDiscount = (float)$OrderItem['OrderItemDiscount'];
													$itemTotal = $itemTotal-($itemTotal*$OrderItemDiscount/100);
												}
												$totalProductPrice += $itemTotal;
											}
										}
									}
									$totalOrderPrice += $totalProductPrice;
									//Base Discount-----------------
									$baseDiscountRate = isset($customerInfo['Order'][$key]['OrderDiscount'])?$customerInfo['Order'][$key]['OrderDiscount']:0;
									$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
									$totalOrderPrice -= $baseDiscountAmount;

									//Coupon Code ---------
									$couponCodeDiscountRate = isset($customerInfo['Order'][$key]['OrderCoupon'])?$customerInfo['Order'][$key]['OrderCoupon']:0;
									$couponDiscountAmount = $couponCodeDiscountRate;
									$totalOrderPrice -= $couponDiscountAmount;

									$totalWithoutShipping = $totalOrderPrice;
									//Shipping ---------
									$OrderCarrierFeeRetail = isset($customerInfo['Order'][$key]['OrderCarrierFeeRetail'])?$customerInfo['Order'][$key]['OrderCarrierFeeRetail']:'';
									if($OrderCarrierFeeRetail!='') {
										$totalOrderPrice += (float)$OrderCarrierFeeRetail;
									}

									$totalOrderPrice = number_format($totalOrderPrice,2,".","");
									$customerInfo['Order'][$key]['OrderTotal'] = $totalOrderPrice;


									$rs['success'] = $this->saveFile($filename, $customerInfo);
									$rs['Order'] = $customerInfo['Order'][$key];
									return $rs;
								}
							}
						}
						else {
							$rs['success'] = false;
							$rs['err'] = "No item found";
						}
					}
				}
			}
			//For customer file----
			if(!$is_order_found){
				$customerInfoDir = "../../bodiforbusiness/{$store}/";
				$CustomerID = $file;
				$customerInfo = $this->loadFile($customerInfoDir.$CustomerID.'.json');

				//copy OrderCarrierCost => OrderCarrierFeeRetail
				if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
					foreach($customerInfo['Order'] as $oKey => $order) {
						if(!isset($order['OrderCarrierFeeRetail']) && isset($order['OrderCarrierCost'])) {
							$customerInfo['Order'][$oKey]['OrderCarrierFeeRetail'] = $order['OrderCarrierCost'];
							$customerInfo['Order'][$oKey]['OrderCarrierFeeCost'] = '';
						}
					}
				}

				foreach ($customerInfo['Order'] as $key => $order) {
					$dateToChk = $order['OrderDate'];
					if ($dateToChk == $OrderDate) {
						if (is_array($order['OrderItems'])) {
							foreach ($order['OrderItems'] as $j => $item) {
								if ($item['OrderProduct'] == $itemName) {
									array_splice($customerInfo['Order'][$key]['OrderItems'], $j, 1);

									$totalOrderPrice = 0.00;
									$totalProductPrice = 0.00;
									if(isset($customerInfo['Order'][$key]['OrderItems'])){
										foreach($customerInfo['Order'][$key]['OrderItems'] as $OrderItem) {
											if($OrderItem['OrderProduct']!=''){
												$itemTotal = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
												if(isset($OrderItem['OrderItemDiscount']) && $OrderItem['OrderItemDiscount']!=''){
													$OrderItemDiscount = (float)$OrderItem['OrderItemDiscount'];
													$itemTotal = $itemTotal-($itemTotal*$OrderItemDiscount/100);
												}
												$totalProductPrice += $itemTotal;
											}
										}
									}
									$totalOrderPrice += $totalProductPrice;

									//Base Discount-----------------
									$baseDiscountRate = isset($customerInfo['Order'][$key]['OrderDiscount'])?$customerInfo['Order'][$key]['OrderDiscount']:0;
									$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
									$totalOrderPrice -= $baseDiscountAmount;

									//Coupon Code ---------
									$couponCodeDiscountRate = isset($customerInfo['Order'][$key]['OrderCoupon'])?$customerInfo['Order'][$key]['OrderCoupon']:0;
									$couponDiscountAmount = $couponCodeDiscountRate;
									$totalOrderPrice -= $couponDiscountAmount;

									$totalWithoutShipping = $totalOrderPrice;
									//Shipping ---------
									$OrderCarrierFeeRetail = isset($customerInfo['Order'][$key]['OrderCarrierFeeRetail'])?$customerInfo['Order'][$key]['OrderCarrierFeeRetail']:'';
									if($OrderCarrierFeeRetail!='') {
										$totalOrderPrice += (float)$OrderCarrierFeeRetail;
									}

									$totalOrderPrice = number_format($totalOrderPrice,2,".","");
									$customerInfo['Order'][$key]['OrderTotal'] = $totalOrderPrice;


									$rs['success'] = $this->saveFile($customerInfoDir.$CustomerID.'.json', $customerInfo);
									$rs['Order'] = $customerInfo['Order'][$key];
									return $rs;
								}
							}
						} else {
							$rs['success'] = false;
							$rs['err'] = "No item found";
						}
					}
				}
			}

		}
		$rs['success'] = false;
		$rs['err'] = "Can't find Order";
		return $rs;
	}
    public function moveOrder($store, $file, $customer, $order, $isSave=true) {
        $rs = array('success' => true);
        $filename = $store. '/'. $file . '.json';
        if (!is_file($filename)) {
            $this->addCustomerInfo($store, $customer);
        }
        $template = $this->loadFile("ShoppingCartTemplate.json");
        $customerInfo = $this->loadFile($filename);
        if (!isset($customerInfo['Order'])) {
            $customerInfo['Order'] = array();
        }
        $order = array_replace($template['Order'][0], $order);
        if($isSave){
			$customerInfo['Order'][] = $order;
			if (!$this->saveFile($filename, $customerInfo)) {
	            $rs = array(
	                'success' => false,
	                'err' => "Can't save customer file",
	            );
	        }
	        $rs['Order'] = $customerInfo;
	        $rs['Order']['Order'] = $order;
	        return $rs;
		} else {
			return $order;
		}
    }
	public function priceTest() {
		$retail = new Retail();
		$products = $this->inventory->loadJson(__DIR__.'/../../setting/uploadsync.json');
		if(!empty($products)) {
			foreach($products as $product) {
				$product['Format'] = $product['Category'];
				foreach($product['Retail'] as $retailName => $listing) {
					$price = $retail->calculateRetailUniversal($product, $listing, 'bodiretailer');
					echo "<br>retailName=$retailName";
					echo "<br>price=$price";
				}



			}
		}

		die('STOP');
	}
	public function ChangeStatusToPaid($options) {
		$rs = array();
		$retail = new Retail();
		$staff = $options['staff'];
		$store = $options['store'];
		$file = $options['file'];
		$OrderDate = $options['OrderDate'];
		$items = $options['OrderItems'];
		$OrderStatus = $OrderStatusInRequest = $options['OrderStatus'];
		$setting = $this->inventory->loadJson($this->settingPath);

		$DiscountType = $options['DiscountType']!=''?$options['DiscountType']:0;
		$OrderReward = $options['OrderReward']!=''?$options['OrderReward']:0;
		$OrderDiscountCoupon = $options['OrderDiscountCoupon']!=''?$options['OrderDiscountCoupon']:0;
		$CouponCode = $options['CouponCode']!=''?$options['CouponCode']:0;
		$CouponStaff = $options['CouponStaff']!=''?$options['CouponStaff']:0;

		$OrderCarrierFeeRetail = '';
		$OrderCarrierFeeCost = '';
		$OrderCarrierFeeRetail = isset($options['OrderCarrierFeeRetail'])?$options['OrderCarrierFeeRetail']:'';
		if($store=='Amazon') {
			$OrderCarrierFeeCost = (isset($options['OrderCarrierFeeCost']) && $options['OrderCarrierFeeCost']!='')?$options['OrderCarrierFeeCost']:'4.5';
		}
		else {
			$OrderCarrierFeeCost = isset($options['OrderCarrierFeeCost'])?$options['OrderCarrierFeeCost']:'';
		}
		$PriceBreakup = $options['PriceBreakup'];

		$customerInfoDir = "../../bodiforbusiness/{$store}/";
		$customerTemplateDir = "../../bodiforbusiness/retail/";
		$fromOrderTempLog = false;
		$fileChkArr = explode('+',$file);
		if($fileChkArr[0] == 'OrderTempLogData') {
			$fromOrderTempLog = true;
			$fromCustomerName = '';
			$fromEmail = '';
			$fromZipcode = '';
			if(isset($fileChkArr[1]))
				$fromCustomerName = $fileChkArr[1];
			if(isset($fileChkArr[2]))
				$fromEmail = $fileChkArr[2];
			if(isset($fileChkArr[3]))
				$fromZipcode = $fileChkArr[3];
		}
		//--------------------
		$products = $this->getProductList();
		$is_order_found = false;
		//Use onle for Equine/Bodi2business/BodiFranchise-----
		if($store=='Equine' || $store=='Bodi2business'  || $store=='BodiFranchise'){
			if($store=='BodiFranchise'){
				$OrderStatus = 'Delivered';
			}
			//For customer file----
			if(!$is_order_found){
				$CustomerID = $file;
				if ($store == 'BodiFranchise') {
					$storeInst = StoreFactory::create($store);
					$customerInfo = $storeInst->getJson([
						'date' => $OrderDate,
						'CustomerID' => $CustomerID
					]);
				} else {
					$customerInfo = $this->loadFile($customerInfoDir.$CustomerID.'.json');
				}

				$Customertemplate = $this->loadFile($customerTemplateDir."template.json");
				$Ordertemplate = $Customertemplate['Order'][0];

				//copy OrderCarrierCost => OrderCarrierFeeRetail
				if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
					foreach($customerInfo['Order'] as $oKey => $order) {
						if(!isset($order['OrderCarrierFeeRetail']) && isset($order['OrderCarrierCost'])) {
							$customerInfo['Order'][$oKey]['OrderCarrierFeeRetail'] = $order['OrderCarrierCost'];
							$customerInfo['Order'][$oKey]['OrderCarrierFeeCost'] = '';
						}
					}
				}
				//New order check---
				$isNewOrder = false;
				foreach ($customerInfo['Order'] as $key => $order) {
					$isNewOrder = strpos($OrderDate, 'new-') !== false;
					if($isNewOrder) {
						$OrderDate = str_replace('new-', '',$OrderDate);
						$newOrder = $Ordertemplate;
						$newOrder['OrderDate'] = $OrderDate;
						$newOrder['OrderStatus'] = $OrderStatus!=''?$OrderStatus:'Ordered';
						$customerInfo['Order'][] = $newOrder;
						$this->saveFile($customerInfoDir.$CustomerID.'.json', $customerInfo);
						$options['OrderDate'] = $OrderDate;
						break;
					}
				}
				//New order check End---

				foreach ($customerInfo['Order'] as $key => $order) {
					if ($order['OrderDate'] == $OrderDate) {
						$is_order_found = true;
						$customerInfo['Order'][$key]['OrderItems'] = $items;

						$totalOrderPrice = 0.00;
						$totalProductPrice = 0.00;
						$OrderCostTotal = 0.00;
						$shipweightTotal = 0;

						$OrderExpenseCostTotal = 0.00;
						$OrderCostDeliveryTotal = 0.00;
						$PackingFeeExpenseTotal = 0.00;
						$ShipFeeForProductCostTotal = 0.00;
						$OrderCarrierFeeRetail = '';
						$OrderCarrierFeeCost = '';
						if($customerInfo['Order'][$key]['OrderCarrierService'] == 'pickup') {
							$OrderCarrierFeeRetail = 0.00;
							$OrderCarrierFeeCost = 0.00;
						}
						else {
							if($customerInfo['Order'][$key]['OrderCarrierFeeRetail']!='') {
								$OrderCarrierFeeRetail = (float)$customerInfo['Order'][$key]['OrderCarrierFeeRetail'];
							}
							if($customerInfo['Order'][$key]['OrderCarrierFeeCost']!='') {
								$OrderCarrierFeeCost = (float)$customerInfo['Order'][$key]['OrderCarrierFeeCost'];
							}
						}

						if(isset($customerInfo['Order'][$key]['OrderItems'])){
							foreach($customerInfo['Order'][$key]['OrderItems'] as $itemKey => $OrderItem) {
								if(!empty($OrderItem['OrderProduct'])) {
									$itemTotal = (float)$OrderItem['OrderPrice']*(float)$OrderItem['OrderQuantity'];
									if(isset($OrderItem['OrderItemDiscount']) && $OrderItem['OrderItemDiscount']!=''){
										$OrderItemDiscount = (float)$OrderItem['OrderItemDiscount'];
										$itemTotal = $itemTotal-($itemTotal*$OrderItemDiscount/100);
									}
									$totalProductPrice += $itemTotal;
									$OrderProduct = $OrderItem['OrderProduct'];
									$OrderAttribute = $OrderItem['OrderAttribute'];
									$OrderProductSKU = $OrderItem['OrderProductSKU'];
									$OrderQuantity = (int)$OrderItem['OrderQuantity'];
									$OrderShipWeight = isset($OrderItem['OrderShipWeight']) && $OrderItem['OrderShipWeight']!=''?(float)$OrderItem['OrderShipWeight']:0;

									$shipweightTotal += ($OrderShipWeight*$OrderQuantity);

									$cost = 0;
									$feePacking = 0;
									if(isset($OrderItem['OrderCost']) && $OrderItem['OrderCost'] != ''){
										$cost = $OrderItem['OrderCost'];
									}

									//Product loop Start------------------
									$isfoundItem = false;
									if(!empty($products)) {
										foreach($products as $productTemp1) {
											$productTemp = $productTemp1['value']['itemData'];
											if($OrderProductSKU != '') {
												foreach($productTemp['Retail'] as $RetailIndex => $RetailRow){
													if($RetailIndex == $OrderProductSKU) {
														$isfoundItem = true;
														$product = $productTemp;
														break;
													}
												}
											}
											if(!$isfoundItem) {
												if(isset($productTemp['Product']) && $productTemp['Product'] == $OrderProduct){
													$isfoundItem = true;
													$product = $productTemp;
												}
											}
											if(!$isfoundItem) {
												continue;
											}

											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($OrderProductSKU != '') {
	                									if($RetailIndex == $OrderProductSKU) {
	                										$isAttrFound = true;
	                									}
	                								}
	                								if($retailAttribute == $OrderAttribute) {
	                									$isAttrFound = true;
	                								}
													if($isAttrFound) {
														$isfoundItem = true;
														$feePacking = 0;
														$inventory = $retail->getFormat($product['Format']);
														if (isset($RetailRow['FeePacking']) && $RetailRow['FeePacking'] > 0) {
															$feePacking = (isset($RetailRow['FeePacking']) && $RetailRow['FeePacking']!='')?$RetailRow['FeePacking']:0;
															//echo "<br>feePacking1=$feePacking";
												        } else {
												            $feePacking = $retail->getFeePacking($inventory, $RetailRow);
												            //echo "<br>feePacking2=$feePacking";
												        }

												        if(isset($OrderItem['OrderCost']) && $OrderItem['OrderCost'] != ''){
															$cost = $OrderItem['OrderCost'];
															//echo "<br>cost1=$cost";
														}
														else {
															$cost = $retail->calculateCost($product, $RetailRow);
															$customerInfo['Order'][$key]['OrderItems'][$itemKey]['OrderCost']=$cost;
															//echo "<br>cost2=$cost";
														}


														break;
													}
												}
											}

											if($isfoundItem) {
												break;
											}
										}
									}
									//Product loop End------------------
									$CostTotal = (($cost+$feePacking)*$OrderQuantity);
									$OrderCostTotal += $CostTotal;


									$CostOnly = ($cost*$OrderQuantity);
									$OrderExpenseCostTotal += $CostOnly;
									$PackingFeeExpenseTotal += ($feePacking*$OrderQuantity);

									//echo "<br>cost=$cost";
									//echo "<br>feePacking=$feePacking";
									//echo "<br>OrderQuantity=$OrderQuantity";
									//echo "<br>OrderExpenseCostTotal=$OrderExpenseCostTotal";
									//echo "<br>PackingFeeExpenseTotal=$PackingFeeExpenseTotal";

								}
							}

							if($OrderCarrierFeeCost!=='') {
								$OrderCostTotal += (float)$OrderCarrierFeeCost;
								$OrderCostDeliveryTotal += (float)$OrderCarrierFeeCost;
							}
							if($shipweightTotal>0 && $customerInfo['Order'][$key]['OrderCarrierService'] != 'pickup') {
								$ShipFeeForProductCostTotal = $retail->getFeeShippingTotal($shipweightTotal);
								//echo "<br>ShipFeeForProductCostTotal=$ShipFeeForProductCostTotal";
							}
						}

						$totalOrderPrice += $totalProductPrice;

						//Discount section Start----------------
						$is_valid = false;
						if($OrderDiscountCoupon!='' && $CouponCode==''){
							$is_valid = true;
						}
						else if($CouponCode!='') {
							$Coupon = array(
								'DiscountType' => $DiscountType,
								'OrderDiscountCoupon' => $OrderDiscountCoupon,
								'CouponCode' => $CouponCode,
								'CouponStaff' => $CouponStaff
							);
							$resultCoupon = $this->validateCoupon($Coupon, true);
							if($resultCoupon['SUCCESS'] == 1) {
								$is_valid = true;
							}
						}
						$baseDiscountRate = 0;
						$baseDiscountAmount = 0.00;
						$couponCodeDiscountRate = 0;
						$couponDiscountAmount = 0.00;
						if($is_valid) {
							//Apply the coupon
							if(isset($OrderDiscountCoupon) && $OrderDiscountCoupon!=''){
								//Base Discount-----------------
								if(isset($DiscountType) && $DiscountType == 'P') {
									$baseDiscountRate = $OrderDiscountCoupon;
									$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
								}
								//Coupon Discount ---------
								else if(isset($DiscountType) && $DiscountType == 'F') {
									$couponDiscountAmount = $OrderDiscountCoupon;
								}
							}
						}
						else {
							//Calculate prev discount --
							$baseDiscountRate = 0;
							$baseDiscountAmount = 0;
							$couponDiscountAmount = 0;
							if(isset($customerInfo['Order'][$key]['OrderDiscount']) && $customerInfo['Order'][$key]['OrderDiscount'] != '') {
								$baseDiscountRate = $customerInfo['Order'][$key]['OrderDiscount'];
								$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
							}
							if(isset($customerInfo['Order'][$key]['OrderCoupon']) && $customerInfo['Order'][$key]['OrderCoupon'] != '') {
								$couponDiscountAmount = $customerInfo['Order'][$key]['OrderCoupon'];
							}
						}
						$totalOrderPrice -= $baseDiscountAmount;
						$totalOrderPrice -= $couponDiscountAmount;
						$totalOrderPrice -= $OrderReward;
						//Discount section End----------------


		                $totalWithoutShipping = $totalOrderPrice;

		                //Shipping ---------
						if($OrderCarrierFeeRetail!=''){
							$totalOrderPrice += $OrderCarrierFeeRetail;
							$OrderCarrierFeeRetail = number_format($OrderCarrierFeeRetail,2,".","");
						}

						//For Bodi4life/Equine/Bodi2business
						$OrderPaymentType = $customerInfo['Order'][$key]['OrderPaymentType'];
						$FeePercentage = $setting['Markup']['FeeMerchant'];
						if($OrderPaymentType == 'Paypal'){
							$FeePercentage = $setting['Markup']['FeePaypal'];
						}
						$RetailCost = 0;
						if($FeePercentage>0){
							$RetailCost = ($totalOrderPrice)*($FeePercentage/100);
						}


						$totalOrderPrice = number_format($totalOrderPrice,2,".","");
						$customerInfo['Order'][$key]['OrderDiscount'] = "$baseDiscountRate";
						$customerInfo['Order'][$key]['OrderReward'] = "$OrderReward";
						$customerInfo['Order'][$key]['OrderCoupon'] = "$couponDiscountAmount";
						$customerInfo['Order'][$key]['OrderCouponCode'] = "$CouponCode,$CouponStaff";
						$customerInfo['Order'][$key]['OrderCarrierFeeRetail'] = $OrderCarrierFeeRetail;
						$customerInfo['Order'][$key]['OrderCarrierFeeCost'] = $OrderCarrierFeeCost;
						$customerInfo['Order'][$key]['OrderTotal'] = $totalOrderPrice;
						$customerInfo['Order'][$key]['OrderPaid'] = $totalOrderPrice;
						$customerInfo['Order'][$key]['OrderStatus'] = $OrderStatus;
						if ($store == 'BodiFranchise') {
							$storeInst->saveJson([
								'date' => $OrderDate,
								'CustomerID' => $CustomerID
							], $customerInfo);
						} else {
							$this->saveFile($customerInfoDir.$CustomerID.'.json', $customerInfo);
						}
						$rs['addpoint'] = $this->addPoint($staff, $customerInfo['Order'][$key]['OrderItems']);


						//Update Sales Data----
						$OrderCostTotal = $PriceBreakup['TotalCost']['Total'];
						$OrderStore = $store;
						//$OrderProfitTotal = (float)$totalOrderPrice-(float)$OrderCostTotal;
						$OrderProfitTotal = $PriceBreakup['TotalProfit']['Total'];
						/*echo "<br>totalOrderPrice=$totalOrderPrice";
						echo "<br>OrderCostTotal=$OrderCostTotal";
						echo "<br>OrderProfitTotal=$OrderProfitTotal";*/

						$accounting = new Accounting();
						$accountingBusiness = new AccountingBusiness();
						$CustomerName = isset($customerInfo['CustomerName'])?$customerInfo['CustomerName']:'';
						$dataExpense = array(
							'OrderStore' => $OrderStore,
							// 'TaxCost' => $PriceBreakup['TotalCost']['TaxCost']??0.00,
							'RetailCost' => $PriceBreakup['TotalCost']['MarkupRetail']??0.00,
							'DeliveryCost' => $PriceBreakup['TotalCost']['ShipCost']??0.00,
							'ProductCost' => $PriceBreakup['TotalCost']['SupplierCost']??0.00,
							'PackagingCost' => $PriceBreakup['TotalCost']['FeePacking']??0.00,
							'ServiceCost' => $PriceBreakup['TotalCost']['ServiceCost']??0.00,
							'PromoCost' => $PriceBreakup['SubCharge']['Discount']??0.00
						);
						$accountingBusiness->onlyUpdateMonthlySales($totalOrderPrice, $OrderProfitTotal, $OrderStore);
						$accountingBusiness->onlyUpdateMonthlyExpenses($dataExpense);
						if($store=='BodiFranchise') {
							$accounting->onlyUpdateMonthlyExpenses($dataExpense);
							if($CustomerName != 'Bodi Nutritions') {
								$accounting->onlyUpdateMonthlySales('0', $OrderProfitTotal, $OrderStore);
							}
						}
						else {
							$accounting->onlyUpdateMonthlySales($totalOrderPrice, $OrderProfitTotal, $OrderStore);
							$accounting->onlyUpdateMonthlyExpenses($dataExpense);
						}



						// if($store!='BodiFranchise' || ($store=='BodiFranchise' && $CustomerName != 'Bodi Nutritions')) {
						// 	$accounting->onlyUpdateMonthlySales($totalOrderPrice, $OrderProfitTotal, $OrderStore);
						// 	$accounting->onlyUpdateMonthlyExpenses($dataExpense);
						// }
						if(($store=='BodiFranchise' && $CustomerName == 'Bodi Nutritions')) {
							$this->addupInvFromLog($items, $products);
						}
						else {
							$this->reduceInv($items, $products, $OrderStore, true, $OrderStatusInRequest); //false = update sale data also..//true for no update sale...
						}
						if($OrderStatusInRequest=='AddToShop') {
							$this->addSupplierToInv($items);
						}


		            	$rs['success'] = true;
		            	$rs['CustomerID'] = $CustomerID;
		            	$rs['fileName'] = $file;
		            	$rs['OrderStatus'] = $OrderStatus;
						return $rs;
					}
				}
			}


		}

		$rs = array(
			'success' => false,
			'err' => "Something went wrong. Please try again later.",
		);
		return $rs;
	}
    public function addPoint($staff, $orderItems) {
        $rs = array('success' => true);
        try {
            $staffPath = "../../staff/Contact/{$staff['name']}+{$staff['password']}.json";
            $loadedStaff = $this->inventory->loadJson($staffPath);
            if (!$loadedStaff) {
            	throw new Exception("{$staff['name']} not found");
            }
            $updatedStaff = $this->updateStaffRate($loadedStaff, $orderItems);
            $this->inventory->saveJson($staffPath, $updatedStaff);
        } catch (Exception $e) {
            $rs['success'] = false;
            $rs['error'] = $e->getMessage();
            $rs['line'] = $e->getLine();
        }
        return $rs;
    }
    public function updateStaffRate($staff, $items) {
        $learn = [];
        foreach ($items as $item) {
            if (isset($item['OrderTaskPoint']) && isset($item['OrderSubCategory'])) {
                if (empty($item['OrderSubCategory']) || $item['OrderSubCategory'] == '0') continue;
                if (strtolower($item['OrderSubCategory']) != 'packaging')
                	continue;
                if (!isset($staff['Rate'][$item['OrderSubCategory']])) {
                    $staff['Rate'][$item['OrderSubCategory']] = [0, 0];
                }
                if (isset($staff['Rate'][$item['OrderSubCategory']]) && count($staff['Rate'][$item['OrderSubCategory']]) > 1) {
                    if (empty($learn[$item['OrderSubCategory']])) {
                        $learn[$item['OrderSubCategory']] = true;
                        $staff['Rate'][$item['OrderSubCategory']][0] += 10;
                        if ($staff['Rate'][$item['OrderSubCategory']][0] > 10) $staff['Rate'][$item['OrderSubCategory']][0] = 10;
                        $staff['Rate'][$item['OrderSubCategory']][0] = (string)$staff['Rate'][$item['OrderSubCategory']][0];
                    }
                    $staff['Rate'][$item['OrderSubCategory']][1] += (float)$item['OrderQuantity'] * (float)$item['OrderTaskPoint'];
                    $staff['Rate'][$item['OrderSubCategory']][1] = (string)$staff['Rate'][$item['OrderSubCategory']][1];
                }
            }
        }
        return $staff;
    }
	function addupInvFromLog($OrderItems, $products){
		if(!empty($OrderItems) && !empty($products)) {
			foreach($OrderItems as $OrderItem) {
				$OrderProduct = trim($OrderItem['OrderProduct']);
				$OrderProductID = isset($OrderItem['OrderProductID'])?trim($OrderItem['OrderProductID']):'';
				$OrderProductSKU = isset($OrderItem['OrderProductSKU'])?trim($OrderItem['OrderProductSKU']):'';
				$OrderAttribute = trim($OrderItem['OrderAttribute']);
				$OrderQuantity = $OrderItem['OrderQuantity'];
				$OrderPrice = $OrderItem['OrderPrice'];
				$size = '';
				$unit = '';
				if($OrderProduct!='' && $OrderQuantity > 0) {
					foreach($products as $product){
						$isOrderProductFound = false;
						$isProductSKUFound = false;
						//Finf product by SKU
						if($OrderProductSKU!=''){
							if(isset($product['value']['itemData']['Retail'])) {
								foreach($product['value']['itemData']['Retail'] as $RKey => $Rval) {
									if($RKey == $OrderProductSKU){
										$isOrderProductFound = true;
										$isProductSKUFound = true;
										$OrderAttribute = $RKey;
										$size = $Rval['RetailSize'];
	                					$unit = $Rval['RetailUnit'];
										break;
									}
								}
							}
						}

						if($isOrderProductFound) {
							//Add reduce to update log-------
							$OrderDate = date('Y-m-d H:i:s');
							$convertTo = 'Gr';
							if($unit == 'mL' || $unit == 'Li' ||$unit == 'FlOz') {
								$convertTo = 'mL';
							}
							$saleInGram = Conversion::convertStockValue($OrderQuantity*$size, $unit, $convertTo);
							$saleInGram = round($saleInGram, 0);
							$addupLog = array(
								"category" => $product["value"]["inventory"],
								"product" => $product["value"]["product"],
								"datetime" => $OrderDate,
								"addup" => array(
									"Retail" => array(
										"Bulk" => array(
											"StockRetailShop" => $saleInGram
										)
									)
								)
							);

							$logs = array();
							$oldlogs = $this->inventory->loadJson('../../setting/update-log.json');

					        if(!empty($oldlogs)) {
					        	$isInserted = false;
								foreach($oldlogs as $logKey => $logVal) {
									if(!$isInserted){
										if($logVal['datetime']==$OrderDate){
											$logs[] = $logVal;
											$logs[] = $addupLog;
											if(!empty($productSoldLog)) {
												$logs[] = $productSoldLog;
											}
											$isInserted = true;
										}
										else if($logVal['datetime']>$OrderDate){
											$logs[] = $addupLog;
											$logs[] = $logVal;
											if(!empty($productSoldLog)) {
												$logs[] = $productSoldLog;
											}
											$isInserted = true;
										}
										else {
											$logs[] = $logVal;
										}
									}
									else {
										$logs[] = $logVal;
									}
								}
								if(!$isInserted){
									$logs[] = $addupLog;
									if(!empty($productSoldLog)) {
										$logs[] = $productSoldLog;
									}
								}
							}
							else {
								$logs[] = $addupLog;
								if(!empty($productSoldLog)) {
									$logs[] = $productSoldLog;
								}
							}
					        $this->inventory->saveJson('../../setting/update-log.json', $logs);
        					//---------------

							break;
						}
					}
				}
			}
		}
		return true;
	}
	public function reduceInv($OrderItems, $products, $store, $noUpdateSaleData = true, $OrderStatus=''){
		if(!empty($OrderItems) && !empty($products)) {
			foreach($OrderItems as $OrderItem) {
				$OrderProduct = trim($OrderItem['OrderProduct']);
				if (empty($OrderProduct)) continue;
				$OrderProductID = isset($OrderItem['OrderProductID'])?trim($OrderItem['OrderProductID']):'';
				$OrderProductSKU = isset($OrderItem['OrderProductSKU'])?trim($OrderItem['OrderProductSKU']):'';
				$OrderAttribute = trim($OrderItem['OrderAttribute']);
				$OrderQuantity = $OrderItem['OrderQuantity'];
				$OrderPrice = $OrderItem['OrderPrice'];
				$size = '';
				$unit = '';
				if($OrderProduct!='' && $OrderQuantity > 0) {
					foreach($products as $product){
						$isOrderProductFound = false;
						$isProductSKUFound = false;
						//Finf product by SKU
						if($OrderProductSKU!=''){
							if(isset($product['value']['itemData']['Retail'])) {
								foreach($product['value']['itemData']['Retail'] as $RKey => $Rval) {
									if($RKey == $OrderProductSKU){
										$isOrderProductFound = true;
										$isProductSKUFound = true;
										$OrderAttribute = $RKey;
										$size = $Rval['RetailSize'];
	                					$unit = $Rval['RetailUnit'];
										break;
									}
								}
							}
						}

						if($isOrderProductFound) {
							//Add reduce to update log-------
							$OrderDate = date('Y-m-d H:i:s');
							if($store=='Ebay' || $store=='Etsy'){
								$OrderDate = isset($OrderItem['OrderDate'])?trim($OrderItem['OrderDate']):date('Y-m-d H:i:s');
							}
							$reduceLog = array(
								'category' => $product['value']['inventory'],
								'product' => $product['value']['product'],
								'datetime' => $OrderDate,
								'reduceFromRetail' => array(
									'OrderQuantity' => $OrderQuantity,
									'productSKU' => $OrderProductSKU,
									'store' => $store
								)
							);
							if($OrderStatus=='AddToShop'){
								$this->addUpInv($reduceLog);
							}

							//Update product sold in inventory...
							//Add to update log...
							$productSoldLog = array();
							if($store=='Equine' || $store=='Bodi2business'){$convertTo = 'Gr';
								if($unit == 'mL' || $unit == 'Li' ||$unit == 'FlOz') {
									$convertTo = 'mL';
								}
								$saleInGram = Conversion::convertStockValue($OrderQuantity*$size, $unit, $convertTo);
								$saleInGram = round($saleInGram, 2);
								$productSoldLog = array(
									'category' => $product['value']['inventory'],
									'product' => $product['value']['product'],
									'datetime' => $OrderDate,
									'ProductSold' => array(
										'type' => 'Wholesale',
										'sale' => $saleInGram
									)
								);
							}

							$logs = array();
							$oldlogs = $this->inventory->loadJson('../../setting/update-log.json');

					        if(!empty($oldlogs)) {
					        	$isInserted = false;
								foreach($oldlogs as $logKey => $logVal) {
									if(!$isInserted){
										if($logVal['datetime']==$OrderDate){
											$logs[] = $logVal;
											$logs[] = $reduceLog;
											if(!empty($productSoldLog)) {
												$logs[] = $productSoldLog;
											}
											$isInserted = true;
										}
										else if($logVal['datetime']>$OrderDate){
											$logs[] = $reduceLog;
											$logs[] = $logVal;
											if(!empty($productSoldLog)) {
												$logs[] = $productSoldLog;
											}
											$isInserted = true;
										}
										else {
											$logs[] = $logVal;
										}
									}
									else {
										$logs[] = $logVal;
									}
								}
								if(!$isInserted){
									$logs[] = $reduceLog;
									if(!empty($productSoldLog)) {
										$logs[] = $productSoldLog;
									}
								}
							}
							else {
								$logs[] = $reduceLog;
								if(!empty($productSoldLog)) {
									$logs[] = $productSoldLog;
								}
							}
					        $this->inventory->saveJson('../../setting/update-log.json', $logs);

        					//---------------

							//Return data for cache Mgnt----------
							$inventoryName = $product['value']['inventory'];
							$ProductName = trim($product['value']['product']);
							$inventoryFullData = $this->inventory->loadInventory($inventoryName);
					        foreach($inventoryFullData as $inventoryData) {
					        	if($ProductName == $inventoryData['Product']){
									$inventorytempData = array();
							        $inventorytempData['inventoryName'] = $inventoryName;
							        $inventorytempData['Product'] = $ProductName;
							        //$inventorytempData['ProductSold'] = isset($inventoryData['ProductSold'])?$inventoryData['ProductSold']:'';
							        //$inventorytempData['ProductSoldWeekly'] = isset($inventoryData['ProductSoldWeekly'])?$inventoryData['ProductSoldWeekly']:'';
							        $inventorytempData['Retail'] = isset($inventoryData['Retail'])?$inventoryData['Retail']:'';
							        $inventorytempData['Suppliers'] = isset($inventoryData['Suppliers'])?$inventoryData['Suppliers']:'';
							        $isFound = false;
							        if(!empty($this->InvDataForCache)) {
										foreach($this->InvDataForCache as $tempKey => $tempVal) {
											if($tempVal['inventoryName'] == $inventoryName && $tempVal['Product'] == $ProductName) {
												$isFound = false;
												$this->InvDataForCache[$tempKey] = $inventorytempData;
												break;
											}
										}
									}
									if(!$isFound){
										array_push($this->InvDataForCache, $inventorytempData);
									}
								}
							}
							break;
						}
					}
				}
			}
		}
		return true;
	}
	public function addSupplierToInv($OrderItems){
		if(!empty($OrderItems) ) {
			$setting = $this->inventory->loadJson($this->settingPath);
			foreach($OrderItems as $OrderItem) {
				$OrderProduct = trim($OrderItem['OrderProduct']);
				$OrderProductID = isset($OrderItem['OrderProductID'])?trim($OrderItem['OrderProductID']):'';
				$OrderProductSKU = isset($OrderItem['OrderProductSKU'])?trim($OrderItem['OrderProductSKU']):'';
				$OrderAttribute = trim($OrderItem['OrderAttribute']);
				$OrderQuantity = $OrderItem['OrderQuantity'];
				$SupplierCost = $OrderPrice = $OrderItem['OrderPrice'];
				//$SupplierCost = $OrderItem['OrderCost'];
				$RetailSize = '';
				$RetailUnit = '';
				$filename = $OrderItem['OrderFormat'].'.json';
				$filePath = $this->franchiseInventoryPath.$filename;
			    $products = $this->loadFile($filePath);
				if($OrderProduct!='' && $OrderQuantity > 0 && !empty($products)) {
					foreach($products as $productKey => $product){
						$isOrderProductFound = false;
						if($product['Product']==$OrderProduct) {
							if(isset($product['Retail'])) {
								foreach($product['Retail'] as $RKey => $Rval) {
									if($Rval['StockLocation'] == 'Shop'){
										$isOrderProductFound = true;
										$OrderAttribute = $RKey;
										$RetailSize = $Rval['RetailSize'];
										$RetailUnit = $Rval['RetailUnit'];
										break;
									}
								}
							}
						}

						//Finf product by SKU
						/*if($OrderProductSKU!=''){
							if(isset($product['Retail'])) {
								foreach($product['Retail'] as $RKey => $Rval) {
									if($RKey == $OrderProductSKU){
										$isOrderProductFound = true;
										$isProductSKUFound = true;
										$OrderAttribute = $RKey;
										$RetailSize = $Rval['RetailSize'];
										$RetailUnit = $Rval['RetailUnit'];
										break;
									}
								}
							}
						}*/

						if($isOrderProductFound) {
							//Add new supplier---
							$TemplateSupplier = BodiTemplate::createTemplateSupplier();
							$dateDelivery = date('Y-m-d');
							$TemplateSupplier['Supplier'] = 'Bodi Nutritions_'.date('Y-m-d');
							$TemplateSupplier['SupplierSize'] = $RetailSize;
							$TemplateSupplier['SupplierUnit'] = $RetailUnit;
							$TemplateSupplier['Cost'] = $SupplierCost;
							$TemplateSupplier['Purchase'] = $OrderQuantity;
							$TemplateSupplier['DateDelivery'] = $dateDelivery;
							$TemplateSupplier['DateExpiration'] = CategoryHelper::getDateExpiration($OrderItem['OrderFormat'], $dateDelivery, $setting)->format('Y-m-d');
							array_unshift($products[$productKey]['Suppliers'] , $TemplateSupplier);

							//update SuppliersPricing cost---
							if(isset($products[$productKey]['SuppliersPricing']) && !empty($products[$productKey]['SuppliersPricing'])) {
								$is_pricingFound = false;
								foreach($products[$productKey]['SuppliersPricing'] as $pricingKey => $SuppliersPricing){
									if($SuppliersPricing['SupplierSize'] == $RetailSize && $SuppliersPricing['SupplierUnit'] == $RetailUnit) {
										$is_pricingFound = true;
										$products[$productKey]['SuppliersPricing'][$pricingKey]['Cost'] = $SupplierCost;
									}
								}
								if(!$is_pricingFound && isset($products[$productKey]['SuppliersPricing'][0]['Cost'])){
									$products[$productKey]['SuppliersPricing'][0]['SupplierSize'] = $RetailSize;
									$products[$productKey]['SuppliersPricing'][0]['SupplierUnit'] = $RetailUnit;
									$products[$productKey]['SuppliersPricing'][0]['Cost'] = $SupplierCost;
								}
							}

						}
					}
					$this->saveFile($filePath, $products);

				}
			}
		}
		return true;
	}
	public function calculateShipFee($sizeData) {
        if ($sizeData['ShipWeight'] == 0) {
            $shipfee = 0;
        } else if ($sizeData['ShipWeight'] < 5) {
            $shipfee = 3.50;
        } else if ($sizeData['ShipWeight'] < 16) {
            $shipfee = 3.50+($sizeData['ShipWeight']-4)*0.2;
        } else if ($sizeData['ShipWeight'] < 33) {
            $shipfee = 8.00;
        } else if ($sizeData['ShipWeight'] < 80) {
            $shipfee = 8.00+($sizeData['ShipWeight']-32)*0.12;
        } else {
            $shipfee = 15.00+(($sizeData['ShipWeight']-80)*0.08);
        }
        return $shipfee;
    }
    public function calculateShipFeeExpress($sizeData) {
        if ($sizeData['ShipWeight'] == 0) {
            $shipfee = 0;
        } else if ($sizeData['ShipWeight'] < 35) {
            $shipfee = 23.25;
        } else {
            $shipfee = 50.00+(($sizeData['ShipWeight']-32)*0.25);
        }
        return $shipfee;
    }
    public function calculateShipFeeCanada($sizeData) {
        if ($sizeData['ShipWeight'] == 0) {
            $shipfee = 0;
        } else if ($sizeData['ShipWeight'] < 13) {
            $shipfee = 13.50;
        } else {
            $shipfee = 20.00+(($sizeData['ShipWeight']-12)*0.2);
        }
        return $shipfee;
    }
	public function ChangeCostStatusToPaid($options) {
		$store = $options['store'];
		$file = $options['file'];
		$OrderDate = $options['OrderDate'];
		$items = $options['OrderItems'];
		$OrderStatus = 'Delivered';

		$DiscountType = $options['DiscountType']!=''?$options['DiscountType']:0;
		$OrderDiscountCoupon = $options['OrderDiscountCoupon']!=''?$options['OrderDiscountCoupon']:0;
		$CouponCode = $options['CouponCode']!=''?$options['CouponCode']:0;
		$CouponStaff = $options['CouponStaff']!=''?$options['CouponStaff']:0;
		$OrderReward = isset($options['OrderReward']) && $options['OrderReward']!=''?$options['OrderReward']:0;


		$OrderCarrierFeeRetail = $options['OrderCarrierFeeRetail']!=''?$options['OrderCarrierFeeRetail']:'';
		$OrderCarrierFeeCost = $options['OrderCarrierFeeCost']!=''?$options['OrderCarrierFeeCost']:'';

		$customerInfoDir = "../Staff/Contact/";

		$products = $this->getProductList();
		$is_order_found = false;

		//For customer file----
		if(!$is_order_found){
			$CustomerID = $file;
			$customerInfo = $this->loadFile($customerInfoDir.$CustomerID.'.json');
			foreach ($customerInfo['Order'] as $key => $order) {
				if ($order['OrderDate'] == $OrderDate) {
					$is_order_found = true;
					$customerInfo['Order'][$key]['OrderItems'] = $items;

					$totalOrderPrice = 0.00;
					$totalProductPrice = 0.00;
					if(isset($customerInfo['Order'][$key]['OrderItems'])){
						foreach($customerInfo['Order'][$key]['OrderItems'] as $OrderItem) {
							if($OrderItem['OrderProduct']!=''){
								$itemTotal = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
								if(isset($OrderItem['OrderItemDiscount']) && $OrderItem['OrderItemDiscount']!=''){
									$OrderItemDiscount = (float)$OrderItem['OrderItemDiscount'];
									$itemTotal = $itemTotal-($itemTotal*$OrderItemDiscount/100);
								}
								$totalProductPrice += $itemTotal;
							}
						}
					}

					$totalOrderPrice += $totalProductPrice;

					//Discount section Start----------------
					$is_valid = false;
					if($OrderDiscountCoupon!='' && $CouponCode==''){
						$is_valid = true;
					}
					else if($CouponCode!='') {
						$Coupon = array(
							'DiscountType' => $DiscountType,
							'OrderDiscountCoupon' => $OrderDiscountCoupon,
							'CouponCode' => $CouponCode,
							'CouponStaff' => $CouponStaff
						);
						$resultCoupon = $this->validateCoupon($Coupon,true);
						if($resultCoupon['SUCCESS'] == 1) {
							$is_valid = true;
						}
					}

					$baseDiscountRate = 0;
					$baseDiscountAmount = 0.00;
					$couponCodeDiscountRate = 0;
					$couponDiscountAmount = 0.00;
					if($is_valid) {
						//Apply the coupon
						if(isset($OrderDiscountCoupon) && $OrderDiscountCoupon!=''){
							//Base Discount-----------------
							if(isset($DiscountType) && $DiscountType == 'P') {
								$baseDiscountRate = $OrderDiscountCoupon;
								$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
							}
							//Coupon Discount ---------
							else if(isset($DiscountType) && $DiscountType == 'F') {
								$couponDiscountAmount = $OrderDiscountCoupon;
							}
						}
					}
					else {
						//Calculate prev discount --
						$baseDiscountRate = 0;
						$baseDiscountAmount = 0;
						$couponDiscountAmount = 0;
						if(isset($customerInfo['Order'][$key]['OrderDiscount']) && $customerInfo['Order'][$key]['OrderDiscount'] != '') {
							$baseDiscountRate = $customerInfo['Order'][$key]['OrderDiscount'];
							$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
						}
						if(isset($customerInfo['Order'][$key]['OrderCoupon']) && $customerInfo['Order'][$key]['OrderCoupon'] != '') {
							$couponDiscountAmount = $customerInfo['Order'][$key]['OrderCoupon'];
						}
					}
					$totalOrderPrice -= $baseDiscountAmount;
					$totalOrderPrice -= $couponDiscountAmount;
					$totalOrderPrice -= $OrderReward;
					//Discount section End----------------


	                $totalWithoutShipping = $totalOrderPrice;

	                //Shipping ---------
					if($OrderCarrierFeeRetail!=''){
						$totalOrderPrice += $OrderCarrierFeeRetail;
						$OrderCarrierFeeRetail = number_format($OrderCarrierFeeRetail,2,".","");
					}

					$totalOrderPrice = number_format($totalOrderPrice,2,".","");
					$customerInfo['Order'][$key]['OrderStatus'] = "$OrderStatus";
					$customerInfo['Order'][$key]['OrderDiscount'] = "$baseDiscountRate";
					$customerInfo['Order'][$key]['OrderReward'] = "$OrderReward";
					$customerInfo['Order'][$key]['OrderCoupon'] = "$couponDiscountAmount";
					$customerInfo['Order'][$key]['OrderCarrierFeeRetail'] = $OrderCarrierFeeRetail;
					$customerInfo['Order'][$key]['OrderCarrierFeeCost'] = $OrderCarrierFeeCost;
					$customerInfo['Order'][$key]['OrderTotal'] = $totalOrderPrice;
					$customerInfo['Order'][$key]['OrderPaid'] = $totalOrderPrice;
					$this->saveFile($customerInfoDir.$CustomerID.'.json', $customerInfo);

					$rs = array();
	            	$rs['success'] = true;
	            	$rs['CustomerID'] = $CustomerID;
	            	$rs['fileName'] = $file;

					//Reduce---
					$OrderStoreINV = $store;
					$this->reduceInv($items, $products, $OrderStoreINV, true); //true for no update sale...

					//Update Sales Data----
					//Update Log--------------------
					$option = array('store' => $store);
					$this->updateLog($option);
					return $rs;
				}
			}
		}
		$rs = array(
			'success' => false,
			'err' => "Something went wrong. Please try again later..",
		);
		return $rs;

	}
	public function printInvoice($store, $file, $address, $date, $alphaSortItem='') {
		$logo = array(
			'Bodi4life' => '../../images/logo/bodi4life.png',
			'Equine' => '../../images/logo/EquineSolution.png',
			'Bodi2business' => '../../images/logo/bodi4life.png',
		);
		$invoice = array();
		//For Ebay Order json file-----
		if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop'){
			$filename = $store. '/'. $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(count($orderInfo)>0){
				foreach($orderInfo as $OrderIndex => $orderInfoRow){
					foreach($orderInfoRow['Order'] as $key => $order) {
						if($order['OrderDate'] == $date){
							$invoice['address'] = isset($orderInfoRow['Addresses'][0])?$orderInfoRow['Addresses'][0]:'';
							$invoice['order'] = $order;
						}
					}
				}
			}
		}
		else if($store=='Temp'){
			$filename = $store. '/'.$file.'.json';
			$orderInfo = $this->loadFile($filename);
			foreach ($orderInfo['Addresses'] as $a) {
				if ($a['AddressStreet'] == $address || $a['AddressZip'] == $address) {
					$invoice['address'] = $a;
				}
			}
			foreach ($orderInfo['Order'] as $o) {
				if ($o['OrderDate'] == $date) {
					$invoice['order'] = $o;
				}
			}
		}
		else if($store=='BodiFranchise'){
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			foreach ($customerInfo['Addresses'] as $a) {
				if ($a['AddressStreet'] == $address || $a['AddressZip'] == $address) {
					$invoice['address'] = $a;
				}
			}
			foreach ($customerInfo['Order'] as $o) {
				if ($o['OrderDate'] == $date) {
					$invoice['order'] = $o;
				}
			}
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			foreach ($customerInfo['Addresses'] as $a) {
				if ($a['AddressStreet'] == $address || $a['AddressZip'] == $address) {
					$invoice['address'] = $a;
				}
			}
			foreach ($customerInfo['Order'] as $o) {
				if ($o['OrderDate'] == $date) {
					$invoice['order'] = $o;
				}
			}
		}
		if($alphaSortItem!=''){
			if($alphaSortItem=='1'){
				$invoice['order']['OrderItems'] = $this->msortASC($invoice['order']['OrderItems'], 'OrderProduct');
			}
			else if($alphaSortItem=='-1'){
				$invoice['order']['OrderItems'] = $this->msort($invoice['order']['OrderItems'], 'OrderProduct');
			}
		}
		$setting = $this->inventory->loadJson($this->settingPath);
		require 'order-print-template.php';
	}
	public function printPackingSlip($store, $file, $address, $date, $alphaSortItem='') {
		$logo = array(
			'Bodi4life' => '../../images/logo/bodi4life.png',
			'Equine' => '../../images/logo/EquineSolution.png',
			'Bodi2business' => '../../images/logo/bodi4life.png',
		);
		$map = [
			'Franchise' => 'BodiFranchise'
		];
		if (isset($map[$store])) $store = $map[$store];
		$invoice = array();
		if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop'){
			$filename = $store. '/'. $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(count($orderInfo)>0){
				foreach($orderInfo as $OrderIndex => $orderInfoRow){
					foreach($orderInfoRow['Order'] as $key => $order) {
						if($order['OrderDate'] == $date){
							$invoice['address'] = isset($orderInfoRow['Addresses'][0])?$orderInfoRow['Addresses'][0]:'';
							$invoice['order'] = $order;
						}
					}
				}
			}
		} elseif ($store == 'Temp') {
			$filename = $store. '/'.$file.'.json';
			$orderInfo = $this->loadFile($filename);
			foreach ($orderInfo['Addresses'] as $a) {
				if ($a['AddressStreet'] == $address || $a['AddressZip'] == $address) {
					$invoice['address'] = $a;
				}
			}
			foreach ($orderInfo['Order'] as $o) {
				if ($o['OrderDate'] == $date) {
					$invoice['order'] = $o;
				}
			}
		} elseif ($store == 'BodiFranchise') {
			$storeInst = StoreFactory::create('BodiFranchise');
			$customerInfo = $storeInst->getJson([
				'date' => $date,
				'CustomerID' => $file
			]);
			foreach ($customerInfo['Addresses'] as $a) {
				if ($a['AddressStreet'] == $address || $a['AddressZip'] == $address) {
					$invoice['address'] = $a;
				}
			}
			foreach ($customerInfo['Order'] as $o) {
				if ($o['OrderDate'] == $date) {
					$invoice['order'] = $o;
				}
			}
		} else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			foreach ($customerInfo['Addresses'] as $a) {
				if ($a['AddressStreet'] == $address || $a['AddressZip'] == $address) {
					$invoice['address'] = $a;
				}
			}
			foreach ($customerInfo['Order'] as $o) {
				if ($o['OrderDate'] == $date) {
					$invoice['order'] = $o;
				}
			}
		}
		if($alphaSortItem!=''){
			if($alphaSortItem=='1'){
				$invoice['order']['OrderItems'] = $this->msortASC($invoice['order']['OrderItems'], 'OrderProduct');
			}
			else if($alphaSortItem=='-1'){
				$invoice['order']['OrderItems'] = $this->msort($invoice['order']['OrderItems'], 'OrderProduct');
			}
		}
		$inventories = [];
		foreach ($invoice['order']['OrderItems'] as $key => $item) {
			if (empty($item['OrderFormat'])) continue;
			if (!isset($inventories[$item['OrderFormat']])) {
				$inventories[$item['OrderFormat']] = $this->inventory->loadInventory($item['OrderFormat']);
			}
			if (!isset($shopInventories[$item['OrderFormat']])) {
				$shopInventories[$item['OrderFormat']] = $this->shopInventory->loadInventory($item['OrderFormat']);
			}
			$product = new Product($item['OrderFormat'], $item['OrderProduct'], $inventories[$item['OrderFormat']]);
			if ($product->data) {
				$productData = $product->data;
				foreach ($productData['Retail'] as $retail) {
					if ($retail['StockLocation'] == 'Bulk') {
						$invoice['order']['OrderItems'][$key]['StockShelve'] = $retail['StockShelve'];
						break;
					}
				}

				$locations = ['Recipe', 'Bulk', 'Delivery'];
				foreach ($locations as $location) {
					$retail = $product->getRetailByStockLocation($location);
					$invoice['order']['OrderItems'][$key][$location] = $retail ? Conversion::convertStockValue($retail['StockRetailShop'], 'gr', $retail['RetailUnit'])/$retail['RetailSize'] : 0;
				}
			}
			$shopProduct = new ShopProduct($item['OrderFormat'], $item['OrderProduct'], $shopInventories[$item['OrderFormat']]);
			if ($shopProduct->data) {
				$retail = $shopProduct->getRetailByStockLocation('Shop');
				$invoice['order']['OrderItems'][$key]['Shop'] = ($retail && $retail['StockRetailShop'] >= 112) ? Conversion::convertStockValue($retail['StockRetailShop'], 'gr', 'lb') : 0;
			}

		}
		$setting = $this->inventory->loadJson($this->settingPath);
		require 'order-print-packingslip-template.php';
	}
	public function printQuickInvoice($store, $itemData) {
		$logo = array(
			'Bodi4life' => '../images/logo/bodi4life.png',
			'Equine' => '../images/logo/EquineSolution.png',
			'Bodi2business' => '../images/logo/bodi4life.png',
		);
		$invoice = array();
		//For Ebay Order json file-----
		if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop'){
			$OrderItems = array();
			if(isset($itemData->Items) && !empty($itemData->Items)) {
				foreach($itemData->Items as $item){
					$temp = array(
						'OrderProduct' => $item->OrderProduct,
						'OrderAttribute' => $item->OrderAttribute,
						'OrderQuantity' => $item->OrderQuantity,
						'OrderPrice' => $item->OrderPrice
					);
					array_push($OrderItems, $temp);
				}
			}
			$order = array();
			$order['OrderDate'] = date('Y-m-d');
			$order['OrderItems'] = $OrderItems;
			$order['OrderDiscount'] = 0.00;
			$order['OrderCoupon'] = 0.00;
			$order['OrderCarrierFeeRetail'] = 0.00;

			$invoice['address'] = '';
			$invoice['order'] = $order;
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			foreach ($customerInfo['Addresses'] as $a) {
				if ($a['AddressStreet'] == $address) {
					$invoice['address'] = $a;
				}
			}
			foreach ($customerInfo['Order'] as $o) {
				if ($o['OrderDate'] == $date) {
					$invoice['order'] = $o;
				}
			}
		}
		require 'order-print-template.php';
	}

	public function printLabelForm($store, $file, $date) {
		$OrderLabelPrint = '';
		$invoice = array();
		$invoice['store'] = $store;
		//For Ebay Order json file-----
		if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop'){
			$filename = $store. '/'. $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(count($orderInfo)>0){
				foreach($orderInfo as $OrderIndex => $orderInfoRow){
					foreach($orderInfoRow['Order'] as $key => $order) {
						if($order['OrderDate'] == $date){
							$OrderLabelPrint = isset($order['OrderLabelPrint'])?$order['OrderLabelPrint']:'';
							$invoice['CustomerName'] = isset($orderInfoRow['CustomerName'])?$orderInfoRow['CustomerName']:'';
							$invoice['order'] = $order;
						}
					}
				}
			}
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			$invoice['CustomerName'] = isset($customerInfo['CustomerName'])?$customerInfo['CustomerName']:'';
			foreach ($customerInfo['Order'] as $order) {
				if ($order['OrderDate'] == $date) {
					$OrderLabelPrint = isset($order['OrderLabelPrint'])?$order['OrderLabelPrint']:'';
					$invoice['order'] = $order;
				}
			}
		}
		if(isset($invoice['order']) && !empty($invoice['order'])) {
			foreach ($invoice['order']['OrderItems'] as $itemIndex => $item){
				$StockShelveContent = '';
				if(isset($item['OrderProductSKU']) && $item['OrderProductSKU'] != '') {
					$OrderProductSKU = $item['OrderProductSKU'];
					$reqdata = array(
						'OrderProductSKU' => $OrderProductSKU
					);
					$inventoryRes = $this->getProductBySKU($reqdata);
					if(isset($inventoryRes['sizeData']['StockShelve'])) {
						$StockShelveContent .= $inventoryRes['sizeData']['StockShelve'];
					}
				}
				$invoice['order']['OrderItems'][$itemIndex]['StockShelveContent'] = $StockShelveContent;
			}
		}
		$contents = 'N/A';
		if(isset($OrderLabelPrint) && $OrderLabelPrint != '') {
			$contents = file_get_contents($OrderLabelPrint);
		}
		require 'order-print-label-template.php';
	}
	public function printSlipForm($store, $file, $date) {
		$OrderLabelPrint = '';
		$invoice = array();
		$invoice['store'] = $store;
		//For Ebay Order json file-----
		if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop'){
			$filename = $store. '/'. $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(count($orderInfo)>0){
				foreach($orderInfo as $OrderIndex => $orderInfoRow){
					foreach($orderInfoRow['Order'] as $key => $order) {
						if($order['OrderDate'] == $date){
							$OrderLabelPrint = isset($order['OrderLabelPrint'])?$order['OrderLabelPrint']:'';
							$invoice['CustomerName'] = isset($orderInfoRow['CustomerName'])?$orderInfoRow['CustomerName']:'';
							$invoice['order'] = $order;
						}
					}
				}
			}
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			$invoice['CustomerName'] = isset($customerInfo['CustomerName'])?$customerInfo['CustomerName']:'';
			foreach ($customerInfo['Order'] as $order) {
				if ($order['OrderDate'] == $date) {
					$OrderLabelPrint = isset($order['OrderLabelPrint'])?$order['OrderLabelPrint']:'';
					$invoice['order'] = $order;
				}
			}
		}
		if(isset($invoice['order']) && !empty($invoice['order'])) {
			foreach ($invoice['order']['OrderItems'] as $itemIndex => $item){
				$OrderProductSKU = $item['OrderProductSKU'];
				$OrderAttribute = $item['OrderAttribute'];
				$reqdata = array(
					'OrderProductSKU' => $OrderProductSKU
				);
				$inventoryRes = $this->getProductBySKU($reqdata);
				$StockShelveContent = '';
				if(isset($inventoryRes['sizeData']['StockShelve'])) {
					$StockShelveContent .= $inventoryRes['sizeData']['StockShelve'];
				}
				$invoice['order']['OrderItems'][$itemIndex]['StockShelveContent'] = $StockShelveContent;
			}
		}
		require 'order-print-slip-template.php';
	}
	public function printLabelInvoiceForm($store, $file, $date) {
		$invoice = array();
		//For Ebay Order json file-----
		if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop'){
			$filename = $store. '/'. $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(count($orderInfo)>0){
				foreach($orderInfo as $OrderIndex => $orderInfoRow){
					foreach($orderInfoRow['Order'] as $key => $order) {
						if($order['OrderDate'] == $date){
							$invoice['CustomerName'] = isset($orderInfoRow['CustomerName'])?$orderInfoRow['CustomerName']:'';
							$invoice['order'] = $order;
						}
					}
				}
			}
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			$invoice['CustomerName'] = isset($customerInfo['CustomerName'])?$customerInfo['CustomerName']:'';
			foreach ($customerInfo['Order'] as $o) {
				if ($o['OrderDate'] == $date) {
					$invoice['order'] = $o;
				}
			}
		}
		require 'order-print-label-invoice-template.php';
	}
	public function createQuickOrder($customer) {
		$rs = array('success' => false);
		$store = $customer['Order']['OrderRetailStore'];

		if($store=='Ebay' || $store=='Etsy'  || $store=='Amazon' || $store=='BodiShop'){

			$CustomerName = "";
			$Username = "";
			$Zipcode = "";
			$OrderStatus = isset($customer['Order']['OrderStatus'])?$customer['Order']['OrderStatus']:'';
			$OrderTracking = isset($customer['Order']['OrderTracking']) ? $customer['Order']['OrderTracking']:'';
			$OrderCarrier = isset($customer['Order']['OrderCarrier']) ? $customer['Order']['OrderCarrier']:'';
			$OrderCarrierService = isset($customer['Order']['OrderCarrierService']) ? $customer['Order']['OrderCarrierService']:'';
			$OrderCarrierFeeRetail = isset($customer['Order']['OrderCarrierFeeRetail'])?$customer['Order']['OrderCarrierFeeRetail']:'';
			if($store=='Amazon'){
				$OrderCarrierFeeCost = (isset($customer['Order']['OrderCarrierFeeCost']) && $customer['Order']['OrderCarrierFeeCost'] != '')?$customer['Order']['OrderCarrierFeeCost']:'4.5';
			}
			else {
				$OrderCarrierFeeCost = isset($customer['Order']['OrderCarrierFeeCost'])?$customer['Order']['OrderCarrierFeeCost']:'';
			}

			$OrderAddresses = isset($customer['orderAddress'])?$customer['orderAddress']:'';
			$OrderCards = isset($customer['card'])?$customer['card']:'';
			$orderInfoDir = "../../bodiforbusiness/".$store."/";
			$ebayOrderLogTemplatePath = "../../bodiforbusiness/retail/template.json";
			$cDate = date('Y-m-d');
			$fileNameWJ = $cDate;
			$fileName = $cDate.'.json';
			$fileData = '';
			$ebayOrderLogTemplate = json_decode(file_get_contents($ebayOrderLogTemplatePath), true);
			if(is_file($orderInfoDir.$fileName)) {
				$fileDataEn = file_get_contents($orderInfoDir.$fileName);
				if($fileDataEn!= '') {
					$fileData = json_decode($fileDataEn, true);
				}
			}
			$blankOrderId='';
			$nextCounter = 0;
			$is_found = false;
			if($fileData!= '' && count($fileData)>0) {
				$fileDataRev = array_reverse(array_values($fileData));
				foreach($fileDataRev as $OrderIndex => $fileDataRow){
					if (isset($fileDataRow['Order']) && is_array($fileDataRow['Order'])) {
						foreach ($fileDataRow['Order'] as $order) {
	        				if(isset($order['OrderId']) && $order['OrderId'] != '' && $order['OrderId'] != NULL) {
	        					$is_found = true;
								$nextCounter = (int)$order['OrderId'];
								if(!isset($order['OrderItems']) || empty($order['OrderItems'])) {
									//use this index---
									$blankOrderId = $nextCounter;
								}
								break;
							}
						}
					}
					if($is_found) {
						break;
					}
				}
			}
			if($blankOrderId != '') {
				$nextCounter = $blankOrderId;
			}
			else {
				$nextCounter++;
			}


			$ebayTotalLog = array();
			if($fileData!= '' && count($fileData)>0) {
				$ebayTotalLog = $fileData;
			}

			$ebayOrderLogInfo = $ebayOrderLogTemplate;
			$orderInfo = isset($ebayOrderLogInfo['Order'][0])?$ebayOrderLogInfo['Order'][0]:array();
			$tempAdd = isset($ebayOrderLogInfo["Addresses"][0])?$ebayOrderLogInfo["Addresses"][0]:array();
			$tempAdd['AddressName'] = isset($OrderAddresses['AddressName'])?ucwords(strtolower($OrderAddresses['AddressName'])):'';
			$tempAdd['AddressExtraName'] = isset($OrderAddresses['AddressExtraName'])?ucwords(strtolower($OrderAddresses['AddressExtraName'])):'';
			$tempAdd['AddressDetail'] = isset($OrderAddresses['AddressDetail'])?ucwords(strtolower($OrderAddresses['AddressDetail'])):'';
			$tempAdd['AddressStreet'] = isset($OrderAddresses['AddressStreet'])?ucwords(strtolower($OrderAddresses['AddressStreet'])):'';
			$tempAdd['AddressUnit'] = isset($OrderAddresses['AddressUnit'])?ucwords(strtolower($OrderAddresses['AddressUnit'])):'';
			$tempAdd['AddressBuilding'] = isset($OrderAddresses['AddressBuilding'])?ucwords(strtolower($OrderAddresses['AddressBuilding'])):'';
			$tempAdd['AddressCity'] = isset($OrderAddresses['AddressCity'])?ucwords(strtolower($OrderAddresses['AddressCity'])):'';
			$tempAdd['AddressState'] = isset($OrderAddresses['AddressState'])?$OrderAddresses['AddressState']:'';
			$tempAdd['AddressZip'] = isset($OrderAddresses['AddressZip'])?$OrderAddresses['AddressZip']:'';
			$tempAdd['AddressCountry'] = isset($OrderAddresses['AddressCountry'])?$OrderAddresses['AddressCountry']:'';


			$tempCard = isset($OrderCards["Payments"][0])?$OrderCards["Payments"][0]:array();
			$tempCard['CCLast4Digit'] = isset($OrderCards['selectedPaymentType'])?$OrderCards['selectedPaymentType']:'';
			$tempCard['CCName'] = isset($OrderCards['CCName'])?$OrderCards['CCName']:'';
			$tempCard['CCNumber'] = isset($OrderCards['CCNumber'])?$OrderCards['CCNumber']:'';
			$tempCard['CCExpMonth'] = isset($OrderCards['CCExpMonth'])?$OrderCards['CCExpMonth']:'';
			$tempCard['CCExpYear'] = isset($OrderCards['CCExpYear'])?$OrderCards['CCExpYear']:'';
			$tempCard['CCcode'] = isset($OrderCards['CCcode'])?$OrderCards['CCcode']:'';

			$OrderDate = date('Y-m-d H:i:s');
			$orderInfo['OrderId'] = "$nextCounter";
			$orderInfo['OrderStaff'] = "";
			$orderInfo['OrderDate'] = "$OrderDate";
			$orderInfo['OrderTotal'] = "";
			$orderInfo['OrderDiscount'] = "";
			$orderInfo['OrderCoupon'] = "";
			$orderInfo['OrderStatus'] = "$OrderStatus";
			$orderInfo['OrderLastUpDate'] = "$OrderDate";
			$orderInfo['OrderDeliveryDate'] = "";
			$orderInfo['OrderTracking'] = $OrderTracking;
			$orderInfo['OrderCarrier'] = "$OrderCarrier";
			$orderInfo['OrderCarrierService'] = "$OrderCarrierService";
			$orderInfo['OrderCarrierFeeRetail'] = "$OrderCarrierFeeRetail";
			$orderInfo['OrderCarrierFeeCost'] = "$OrderCarrierFeeCost";
			$orderInfo['OrderRetailer'] = "";
			$orderInfo['OrderNotes'] = "";
			$orderInfo['OrderAddressType'] = isset($OrderAddresses['selectedAddressStreet'])?$OrderAddresses['selectedAddressStreet']:"";
			$orderInfo['OrderPaymentType'] = isset($OrderCards['selectedPaymentType'])?$OrderCards['selectedPaymentType']:"";
			$orderInfo['OrderPaid'] = "";
			$orderInfo['OrderItems'] = [];

			$ebayOrderLogInfo["BuyerUserID"] = "";
			$ebayOrderLogInfo["CustomerName"] = isset($customer['CustomerName'])?ucwords(strtolower($customer['CustomerName'])):$orderInfo['OrderId'];
			$ebayOrderLogInfo["Phone"] = isset($customer['Phone'])?$customer['Phone']:"";
			$ebayOrderLogInfo["Addresses"][0] = $tempAdd;
			$ebayOrderLogInfo["Payments"][0] = $tempCard;
	        $ebayOrderLogInfo['Order'][0] = $orderInfo;
	        if($blankOrderId != '') {
	        	foreach($ebayTotalLog as $ebayTotalLogKey => $ebayTotalLogData){
					if (isset($ebayTotalLogData['Order']) && is_array($ebayTotalLogData['Order'])) {
						foreach ($ebayTotalLogData['Order'] as $order) {
							if(isset($order['OrderId']) && $order['OrderId'] == $blankOrderId) {
								$ebayTotalLog[$ebayTotalLogKey] = $ebayOrderLogInfo;
								break;
							}
						}
					}
				}
			}
			else {
				array_push($ebayTotalLog, $ebayOrderLogInfo);
			}

	        $this->saveFile($orderInfoDir.$fileName, $ebayTotalLog);

			$rs = array();
            $rs['success'] = true;
            $rs['Order'] = $ebayOrderLogInfo['Order'];
            $rs['fileName'] = $fileNameWJ;
            $rs['CustomerID'] = $orderInfo['OrderId'];
            $rs['OrderDate'] = $OrderDate;
		}
		else {
			$rs = array('success' => false);
		}
        return $rs;
	}
	public function createNewStoreFile($store, $file, $OrderDate) {
		//Create New File---
		$orderInfoDir = "../../bodiforbusiness/".$store."/";
		$ebayOrderLogTemplatePath = "../../bodiforbusiness/retail/template.json";
		$fileName = $file.'.json';
		$ebayOrderLogTemplate = json_decode(file_get_contents($ebayOrderLogTemplatePath), true);

		$fileData = '';
		if(is_file($orderInfoDir.$fileName)) {
			$fileDataEn = file_get_contents($orderInfoDir.$fileName);
			if($fileDataEn!= '') {
				$fileData = json_decode($fileDataEn, true);
			}
		}
		$blankOrderId='';
		$nextCounter = 0;
		$is_found = false;
		if($fileData!= '' && count($fileData)>0) {
			$fileDataRev = array_reverse(array_values($fileData));
			foreach($fileDataRev as $OrderIndex => $fileDataRow){
				if (isset($fileDataRow['Order']) && is_array($fileDataRow['Order'])) {
					foreach ($fileDataRow['Order'] as $order) {
        				if(isset($order['OrderId']) && $order['OrderId'] != '' && $order['OrderId'] != NULL) {
        					$is_found = true;
							$nextCounter = (int)$order['OrderId'];
							if(!isset($order['OrderItems']) || empty($order['OrderItems'])) {
								//use this index---
								$blankOrderId = $nextCounter;
							}
							break;
						}
					}
				}
				if($is_found) {
					break;
				}
			}
		}
		if($blankOrderId != '') {
			$nextCounter = $blankOrderId;
		}
		else {
			$nextCounter++;
		}

		$ebayTotalLog = array();
		if($fileData!= '' && count($fileData)>0) {
			$ebayTotalLog = $fileData;
		}

		$ebayOrderLogInfo = $ebayOrderLogTemplate;
		$orderInfo = isset($ebayOrderLogInfo['Order'][0])?$ebayOrderLogInfo['Order'][0]:array();
		$orderInfo['OrderId'] = "$nextCounter";
		$orderInfo['OrderStaff'] = "";
		$orderInfo['OrderDate'] = "$OrderDate";
		$orderInfo['OrderTotal'] = "";
		$orderInfo['OrderDiscount'] = "";
		$orderInfo['OrderCoupon'] = "";
		$orderInfo['OrderStatus'] = "Ordered";
		$orderInfo['OrderLastUpDate'] = "$OrderDate";
		$orderInfo['OrderDeliveryDate'] = "";
		$orderInfo['OrderTracking'] = "";
		$orderInfo['OrderCarrier'] = "";
		$orderInfo['OrderCarrierService'] = "";
		$orderInfo['OrderCarrierFeeRetail'] = "";
		$orderInfo['OrderCarrierFeeCost'] = "";
		$orderInfo['OrderRetailer'] = "";
		$orderInfo['OrderNotes'] = "";
		$orderInfo['OrderAddressType'] = "";
		$orderInfo['OrderPaymentType'] = "";
		$orderInfo['OrderPaid'] = "";
		$orderInfo['OrderItems'] = [];


        $ebayOrderLogInfo['Order'][0] = $orderInfo;
		array_push($ebayTotalLog, $ebayOrderLogInfo);
		$this->saveFile('../'.$store.'/'.$fileName, $ebayTotalLog);
		//Create New File END---
	}
	public function reduceAmazonQuick($customer) {
		$store = 'Amazon';
		$products = $this->getProductList();
		$items = $customer['OrderItems'];
		$this->reduceInv($items, $products, $store, false);
		$rs = array('success' => true);
		$rs['Data'] = $this->InvDataForCache;
		return $rs;
	}
	public function addTempOrder($options) {
		$rs = array('success' => true);
		$store = $options['OrderRetailStore'];
		$OrderStatus = $options['OrderStatus'];

		$orderInfoDir = "../../bodiforbusiness/".$store."/";
		$CustomerTemplatePath = "../../bodiforbusiness/retail/template.json";
		$nextCounter = 0;
		$fileNameArr = preg_grep("/.*\.json$/", scandir($orderInfoDir));
		if(!empty($fileNameArr)) {
			foreach($fileNameArr as $fileNameTemp) {

				$CurrentCounter = str_replace('customer','',$fileNameTemp);
				$CurrentCounter = str_replace('.json','',$CurrentCounter);
				if($nextCounter < $CurrentCounter){
					$nextCounter = $CurrentCounter;
				}
			}
		}
		$nextCounter++;

		$fileName = 'customer'.$nextCounter.'.json';
		$CustomerTemplate = json_decode(file_get_contents($CustomerTemplatePath), true);
		$CustomerInfo = $CustomerTemplate;
		$CustomerInfo['Order'][0]['OrderDate'] = date('Y-m-d H:i:s');
		$CustomerInfo['Order'][0]['OrderStatus'] = $OrderStatus;
		$CustomerInfo['Order'][0]['OrderLastUpDate'] = date('Y-m-d H:i:s');
		$CustomerInfo['Order'][0]['OrderItems'] = [];
		$this->saveFile($orderInfoDir.$fileName, $CustomerInfo);
		$rs = array();
        $rs['success'] = true;
        return $rs;
	}

	public function setAddress($customerData, $orderAddress, $orderKey=0){
		$customerTemplateDir = "../../bodiforbusiness/retail/";
		$Customertemplate = $this->loadFile($customerTemplateDir."template.json");
		if(isset($orderAddress['AddressEmail'])) {
			$customerData['Email'] = $orderAddress['AddressEmail'];
		}
		if(isset($orderAddress['AddressPhone'])) {
			$customerData['Phone'] = $orderAddress['AddressPhone'];
		}
		if(isset($orderAddress['selectedAddressStreet'])) {
			$customerData['Order'][$orderKey]['OrderAddressType'] = $orderAddress['selectedAddressStreet'];
		}
		if(isset($orderAddress['AddressStreet'])) {
			$customerData['Order'][$orderKey]['OrderAddressType'] = $orderAddress['AddressStreet'];
		}
		if(isset($orderAddress['is_NewAddress']) && $orderAddress['is_NewAddress'] == '1') {
			$CIAddresskey = 0;
			if(!empty($customerData['Addresses'])){
				if(isset($customerData['Addresses'][0]) && $customerData['Addresses'][0]['AddressName'] == '' && $customerData['Addresses'][0]['AddressStreet'] == '' ) {
					$CIAddresskey = 0;
				}
				else {
					$CIAddresskey = count($customerData['Addresses']);
				}
			}
			$customerData['Addresses'][$CIAddresskey] = $Customertemplate['Addresses'][0];

			if(isset($orderAddress['AddressName'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressName'] = $orderAddress['AddressName'];

				if($customerData['CustomerName'] == '' && $customerData['Addresses'][$CIAddresskey]['AddressName'] != ''){
					$customerData['CustomerName'] =$customerData['Addresses'][$CIAddresskey]['AddressName'];
				}
				if($customerData['CustomerName'] != '' && $customerData['Addresses'][$CIAddresskey]['AddressName'] == ''){
					$customerData['Addresses'][$CIAddresskey]['AddressName'] = $customerData['CustomerName'];
				}
			}
			if(isset($orderAddress['AddressExtraName'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressExtraName'] = $orderAddress['AddressExtraName'];
			}
			if(isset($orderAddress['AddressDetail'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressDetail'] = $orderAddress['AddressDetail'];
			}
			if(isset($orderAddress['AddressStreet'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressStreet'] = $orderAddress['AddressStreet'];
			}
			if(isset($orderAddress['AddressUnit'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressUnit'] = $orderAddress['AddressUnit'];
			}
			if(isset($orderAddress['AddressBuilding'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressBuilding'] = $orderAddress['AddressBuilding'];
			}
			if(isset($orderAddress['AddressCity'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressCity'] = $orderAddress['AddressCity'];
			}
			if(isset($orderAddress['AddressState'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressState'] = $orderAddress['AddressState'];
			}
			if(isset($orderAddress['AddressZip'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressZip'] = $orderAddress['AddressZip'];
			}
			if(isset($orderAddress['AddressCountry'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressCountry'] = $orderAddress['AddressCountry'];
			}

		}
		else if(isset($orderAddress['AddressIndex']) && $orderAddress['AddressIndex'] != ''){
			$CIAddresskey = $orderAddress['AddressIndex'];
			if(empty($customerData['Addresses'])){
				$customerData['Addresses'][$CIAddresskey] = $Customertemplate['Addresses'][0];
			}
			if(isset($orderAddress['AddressStreet']) && $orderAddress['AddressStreet'] != 'NOEDIT') {
				$customerData['Order'][$orderKey]['OrderAddressType'] = $orderAddress['AddressStreet'];
				$customerData['Addresses'][$CIAddresskey]['AddressStreet'] = $orderAddress['AddressStreet'];
			}

			if(isset($orderAddress['AddressName'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressName'] = $orderAddress['AddressName'];
				if($customerData['CustomerName'] == '' && $customerData['Addresses'][$CIAddresskey]['AddressName'] != ''){
					$customerData['CustomerName'] =$customerData['Addresses'][$CIAddresskey]['AddressName'];
				}
				if($customerData['CustomerName'] != '' && $customerData['Addresses'][$CIAddresskey]['AddressName'] == ''){
					$customerData['Addresses'][$CIAddresskey]['AddressName'] = $customerData['CustomerName'];
				}
			}
			if(isset($orderAddress['AddressExtraName'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressExtraName'] = $orderAddress['AddressExtraName'];
			}
			if(isset($orderAddress['AddressDetail'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressDetail'] = $orderAddress['AddressDetail'];
			}
			if(isset($orderAddress['AddressUnit'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressUnit'] = $orderAddress['AddressUnit'];
			}
			if(isset($orderAddress['AddressBuilding'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressBuilding'] = $orderAddress['AddressBuilding'];
			}
			if(isset($orderAddress['AddressCity'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressCity'] = $orderAddress['AddressCity'];
			}
			if(isset($orderAddress['AddressState'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressState'] = $orderAddress['AddressState'];
			}
			if(isset($orderAddress['AddressZip'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressZip'] = $orderAddress['AddressZip'];
			}
			if(isset($orderAddress['AddressCountry'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressCountry'] = $orderAddress['AddressCountry'];
			}
		}
		else {
			if(isset($orderAddress['selectedAddressStreet']) && $orderAddress['selectedAddressStreet'] != '') {
				if(isset($customerData['Addresses']) && !empty($customerData['Addresses'])) {
					foreach ($customerData['Addresses'] as $CIAddresskey => $CIAddress) {
						if($CIAddress['AddressStreet'] == $orderAddress['selectedAddressStreet']) {
							if(isset($orderAddress['AddressName']) ) {
								$customerData['Addresses'][$CIAddresskey]['AddressName'] = $orderAddress['AddressName'];
								if($customerData['CustomerName'] == '' && $customerData['Addresses'][$CIAddresskey]['AddressName'] != ''){
									$customerData['CustomerName'] =$customerData['Addresses'][$CIAddresskey]['AddressName'];
								}
								if($customerData['CustomerName'] != '' && $customerData['Addresses'][$CIAddresskey]['AddressName'] == ''){
									$customerData['Addresses'][$CIAddresskey]['AddressName'] = $customerData['CustomerName'];
								}
							}
							if(isset($orderAddress['AddressExtraName'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressExtraName'] = $orderAddress['AddressExtraName'];
							}
							if(isset($orderAddress['AddressDetail'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressDetail'] = $orderAddress['AddressDetail'];
							}
							if(isset($orderAddress['AddressStreet'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressStreet'] = $orderAddress['AddressStreet'];
							}
							if(isset($orderAddress['AddressUnit'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressUnit'] = $orderAddress['AddressUnit'];
							}
							if(isset($orderAddress['AddressBuilding'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressBuilding'] = $orderAddress['AddressBuilding'];
							}
							if(isset($orderAddress['AddressCity'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressCity'] = $orderAddress['AddressCity'];
							}
							if(isset($orderAddress['AddressState'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressState'] = $orderAddress['AddressState'];
							}
							if(isset($orderAddress['AddressZip'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressZip'] = $orderAddress['AddressZip'];
							}
							if(isset($orderAddress['AddressCountry'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressCountry'] = $orderAddress['AddressCountry'];
							}
						}
					}
				}

			}
		}

		return $customerData;
	}
	public function setPayments($customerData, $orderCard, $orderKey=0){
		if(isset($orderCard['selectedPaymentType']) && $orderCard['selectedPaymentType'] != '') {
			$customerData['Order'][$orderKey]['OrderPaymentType'] = $orderCard['selectedPaymentType'];
			if (isset($customerData['Payments'])) {
				foreach ($customerData['Payments'] as $paymentkey => $payment) {
					if($orderCard['selectedPaymentType']!='Paypal'){
						if (isset($payment['CCLast4Digit']) && $payment['CCLast4Digit'] == $orderCard['selectedPaymentType']) {
							$customerData['Payments'][$paymentkey]["CCName"] = $orderCard["CCName"];
							$customerData['Payments'][$paymentkey]["CCNumber"] = $orderCard["CCNumber"];
							$customerData['Payments'][$paymentkey]["CCExpMonth"] = $orderCard["CCExpMonth"];
							$customerData['Payments'][$paymentkey]["CCExpYear"] = $orderCard["CCExpYear"];
							$customerData['Payments'][$paymentkey]["CCcode"] = $orderCard["CCcode"];
							break;
						}
					}
					else {
						if (isset($payment['PaypalType']) && $payment['PaypalType'] == $orderCard['selectedPaymentType']) {
							$customerData['Payments'][$paymentkey]["PaypalName"] = $orderCard["PaypalName"];
							$customerData['Payments'][$paymentkey]["PaypalEmail"] = $orderCard["PaypalEmail"];
							break;
						}
					}
				}
			}
		}
		else {
			//Add New Card---
			$paymentkey = 0;
			if(!empty($customerData['Payments'])){
				if(isset($customerData['Payments'][0])) {
					if(isset($customerData['Payments'][0]['CCName']) && $customerData['Payments'][0]['CCName'] == '') {
						$paymentkey = 0;
					}
					else if(isset($customerData['Payments'][0]['PaypalName']) && $customerData['Payments'][0]['PaypalName'] == '') {
						$paymentkey = 0;
					}
					else {
						$paymentkey = count($customerData['Payments']);
					}
				}
				else {
					$paymentkey = count($customerData['Payments']);
				}
			}
			if(isset($orderCard['CCName']) && $orderCard['CCName'] != '') {
				$CCLast4Digit = '';
				if($orderCard["CCNumber"]!= '') {
					$CCLast4Digit = substr($orderCard["CCNumber"], -4);
				}
				$customerData['Order'][$orderKey]['OrderPaymentType'] = $CCLast4Digit;
				$customerData['Payments'][$paymentkey]["CCLast4Digit"] = $CCLast4Digit;
				$customerData['Payments'][$paymentkey]["CCName"] = $orderCard["CCName"];
				$customerData['Payments'][$paymentkey]["CCNumber"] = $orderCard["CCNumber"];
				$customerData['Payments'][$paymentkey]["CCExpMonth"] = $orderCard["CCExpMonth"];
				$customerData['Payments'][$paymentkey]["CCExpYear"] = $orderCard["CCExpYear"];
				$customerData['Payments'][$paymentkey]["CCcode"] = $orderCard["CCcode"];
				$paymentkey++;
			}
			if(isset($orderCard['PaypalName']) && $orderCard['PaypalName'] != '') {
				$customerData['Order'][$orderKey]['OrderPaymentType'] = 'Paypal';
				if(!empty($customerData['Payments'])){
					foreach($customerData['Payments'] as $PKey => $Payment){
						if(isset($Payment['PaypalType'])) {
							$paymentkey = $PKey;
						}
					}
				}
				$customerData['Payments'][$paymentkey]["PaypalType"] = 'Paypal';
				$customerData['Payments'][$paymentkey]["PaypalName"] = $orderCard["PaypalName"];
				$customerData['Payments'][$paymentkey]["PaypalEmail"] = $orderCard["PaypalEmail"];
			}
		}
		return $customerData;
	}

	public function setAddressForCart($customerData, $orderAddress, $orderKey=0){
		$customerTemplateDir = "../../bodiforbusiness/retail/";
		$Customertemplate = $this->loadFile($customerTemplateDir."template.json");

		if(isset($orderAddress['selectedAddressStreet'])) {
			$customerData['Order'][$orderKey]['OrderAddressType'] = $orderAddress['selectedAddressStreet'];
		}
		if(isset($orderAddress['AddressStreet'])) {
			$customerData['Order'][$orderKey]['OrderAddressType'] = $orderAddress['AddressStreet'];
		}
		if(isset($orderAddress['is_NewAddress']) && $orderAddress['is_NewAddress'] == '1') {
			$CIAddresskey = 0;
			if(!empty($customerData['Addresses'])){
				if(isset($customerData['Addresses'][0]) && $customerData['Addresses'][0]['AddressName'] == '' && $customerData['Addresses'][0]['AddressStreet'] == '' ) {
					$CIAddresskey = 0;
				}
				else {
					$CIAddresskey = count($customerData['Addresses']);
				}
			}
			$customerData['Addresses'][$CIAddresskey] = $Customertemplate['Addresses'][0];

			if(isset($orderAddress['AddressName'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressName'] = $orderAddress['AddressName'];
			}
			if(isset($orderAddress['AddressExtraName'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressExtraName'] = $orderAddress['AddressExtraName'];
			}
			if(isset($orderAddress['AddressDetail'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressDetail'] = $orderAddress['AddressDetail'];
			}
			if(isset($orderAddress['AddressStreet'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressStreet'] = $orderAddress['AddressStreet'];
			}
			if(isset($orderAddress['AddressUnit'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressUnit'] = $orderAddress['AddressUnit'];
			}
			if(isset($orderAddress['AddressBuilding'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressBuilding'] = $orderAddress['AddressBuilding'];
			}
			if(isset($orderAddress['AddressCity'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressCity'] = $orderAddress['AddressCity'];
			}
			if(isset($orderAddress['AddressState'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressState'] = $orderAddress['AddressState'];
			}
			if(isset($orderAddress['AddressZip'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressZip'] = $orderAddress['AddressZip'];
			}
			if(isset($orderAddress['AddressCountry'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressCountry'] = $orderAddress['AddressCountry'];
			}

		}
		else if(isset($orderAddress['AddressIndex']) && $orderAddress['AddressIndex'] != ''){
			$CIAddresskey = $orderAddress['AddressIndex'];
			if(empty($customerData['Addresses'])){
				$customerData['Addresses'][$CIAddresskey] = $Customertemplate['Addresses'][0];
			}
			if(isset($orderAddress['AddressStreet']) && $orderAddress['AddressStreet'] != 'NOEDIT') {
				$customerData['Order'][$orderKey]['OrderAddressType'] = $orderAddress['AddressStreet'];
				$customerData['Addresses'][$CIAddresskey]['AddressStreet'] = $orderAddress['AddressStreet'];
			}

			if(isset($orderAddress['AddressName'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressName'] = $orderAddress['AddressName'];
			}
			if(isset($orderAddress['AddressExtraName'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressExtraName'] = $orderAddress['AddressExtraName'];
			}
			if(isset($orderAddress['AddressDetail'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressDetail'] = $orderAddress['AddressDetail'];
			}
			if(isset($orderAddress['AddressUnit'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressUnit'] = $orderAddress['AddressUnit'];
			}
			if(isset($orderAddress['AddressBuilding'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressBuilding'] = $orderAddress['AddressBuilding'];
			}
			if(isset($orderAddress['AddressCity'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressCity'] = $orderAddress['AddressCity'];
			}
			if(isset($orderAddress['AddressState'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressState'] = $orderAddress['AddressState'];
			}
			if(isset($orderAddress['AddressZip'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressZip'] = $orderAddress['AddressZip'];
			}
			if(isset($orderAddress['AddressCountry'])) {
				$customerData['Addresses'][$CIAddresskey]['AddressCountry'] = $orderAddress['AddressCountry'];
			}
		}
		else {
			if(isset($orderAddress['selectedAddressStreet']) && $orderAddress['selectedAddressStreet'] != '') {
				if(isset($customerData['Addresses']) && !empty($customerData['Addresses'])) {
					foreach ($customerData['Addresses'] as $CIAddresskey => $CIAddress) {
						if($CIAddress['AddressStreet'] == $orderAddress['selectedAddressStreet']) {
							if(isset($orderAddress['AddressName']) ) {
								$customerData['Addresses'][$CIAddresskey]['AddressName'] = $orderAddress['AddressName'];
							}
							if(isset($orderAddress['AddressExtraName'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressExtraName'] = $orderAddress['AddressExtraName'];
							}
							if(isset($orderAddress['AddressDetail'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressDetail'] = $orderAddress['AddressDetail'];
							}
							if(isset($orderAddress['AddressStreet'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressStreet'] = $orderAddress['AddressStreet'];
							}
							if(isset($orderAddress['AddressUnit'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressUnit'] = $orderAddress['AddressUnit'];
							}
							if(isset($orderAddress['AddressBuilding'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressBuilding'] = $orderAddress['AddressBuilding'];
							}
							if(isset($orderAddress['AddressCity'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressCity'] = $orderAddress['AddressCity'];
							}
							if(isset($orderAddress['AddressState'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressState'] = $orderAddress['AddressState'];
							}
							if(isset($orderAddress['AddressZip'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressZip'] = $orderAddress['AddressZip'];
							}
							if(isset($orderAddress['AddressCountry'])) {
								$customerData['Addresses'][$CIAddresskey]['AddressCountry'] = $orderAddress['AddressCountry'];
							}
						}
					}
				}

			}
		}

		return $customerData;
	}
	public function validateCoupon($Coupon, $reduce=false){
		$rs = array('SUCCESS' => 0, 'DATA' => '');
		$is_valid = false;
		$DiscountType = $Coupon['DiscountType'];
		$CouponValue = $Coupon['OrderDiscountCoupon'];
		$CouponCode = $Coupon['CouponCode'];
		$CouponStaff = $Coupon['CouponStaff'];

		//Validate the Gift/Percent both Coupon---
		if($CouponValue!='' && $CouponCode!=''){
			$countCoupon = strlen($CouponCode);
			$is_codeValid = true;
			/*$is_codeValid = false;
			//check Date--
			if($countCoupon == 8) {
				$y = substr($CouponCode,0,4);
				$m = substr($CouponCode,4,2);
				$d = substr($CouponCode,6,2);
				$CouponDateStr = $y.'-'.$m.'-'.$d;
				$CouponDate = date('Y-m-d', strtotime($CouponDateStr));
				$cDate = date('Y-m-d');
				if($CouponDate>=$cDate) {
					$is_codeValid = true;
				}
			}
			else if($countCoupon == 4 || $countCoupon == 5) {
				$is_codeValid = true;
			}*/

			$settingCoupon = $this->loadFile("../../setting/adminCoupons.json");
			if($is_codeValid && isset($settingCoupon['Coupons']) && !empty($settingCoupon['Coupons'])){
				foreach($settingCoupon['Coupons']  as $couponIndex => $couponRow) {
					if(strtolower($couponRow['CouponCode'])==strtolower($CouponCode) && strtolower($couponRow['StaffCode'])==strtolower($CouponStaff)){
						if($DiscountType == 'F') {
							if(strpos($couponRow['DiscountAmount'], '$')  !== false) {
								$couponRow['DiscountAmount'] = trim(str_replace('$','',$couponRow['DiscountAmount']));

								//Reduce From adminCoupons--
								$remainBalance = $couponRow['DiscountAmount'];
								if($couponRow['DiscountAmount'] >= $CouponValue) {
									$remainBalance = $couponRow['DiscountAmount'] - $CouponValue;
								}
								if($reduce) {
									if($remainBalance>0) {
										$settingCoupon['Coupons'][$couponIndex]['DiscountAmount'] = $remainBalance.'$';
									}
									else {
										array_splice($settingCoupon['Coupons'], $couponIndex, 1);
									}
									$this->saveFile("../../setting/adminCoupons.json", $settingCoupon);
								}
								//---------------

							}
						}
						else if($DiscountType == 'P') {
							if(strpos($couponRow['DiscountAmount'], '%') !== false) {
								$couponRow['DiscountAmount'] = trim(str_replace('%','',$couponRow['DiscountAmount']));
							}
						}
						//if($couponRow['DiscountAmount']>=$CouponValue) {
							$is_valid = true;
							$rs['SUCCESS'] = 1;
							return $rs;
						//}
					}
				}
			}
		}

		$rs['SUCCESS'] = 0;
		return $rs;
	}
	public function arrangeCustomer($data){
		$customerTemplateDir = "../../bodiforbusiness/retail/";
		$templateData = $this->loadFile($customerTemplateDir."template.json");
		if(is_object($data)){
			if(!empty($data)) {
				foreach($data as $dataKey => $dataVal){
					$templateData->$dataKey = $dataVal;
				}
			}
		}
		else if(is_array($data)){
			if(!empty($data)) {
				foreach($data as $dataKey => $dataVal){
					$templateData[$dataKey] = $dataVal;
				}
			}
		}
		return $templateData;
	}
	public function arrangeCustomerEtsy($data){
		$customerTemplateDir = "../../bodiforbusiness/retail/";
		$templateData = $this->loadFile($customerTemplateDir."RetailerOrderLogTemplate.json");
		if(is_object($data)){
			if(!empty($data)) {
				foreach($data as $dataKey => $dataVal){
					$templateData->$dataKey = $dataVal;
				}
			}
		}
		else if(is_array($data)){
			if(!empty($data)) {
				foreach($data as $dataKey => $dataVal){
					$templateData[$dataKey] = $dataVal;
				}
			}
		}
		return $templateData;
	}
	public function DublicateOrder($request) {
		$rs = array('success' => true);
		//pr($request);die('SS');
		$store = $request['OrderStore'];
		$file = $request['file'];
		$OrderDate = $request['OrderDate'];

		if($store == 'BodiStaff') {
			$customerInfoDir = "../Staff/Contact/";
			$customerTemplateDir = "../Staff/Contact/";
			$Customertemplate = $this->loadFile($customerTemplateDir."contact-template.json");
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerTemplateDir = "../../bodiforbusiness/retail/";
			$Customertemplate = $this->loadFile($customerTemplateDir."template.json");
		}



		if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop'){
			$filename = $store. '/' . $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(empty($orderInfo)) {
				$rs = array(
					'success' => false,
					'err' => "File not found",
				);
				return $rs;
			}
			if(count($orderInfo)>0){
				$isOrderFound = false;
				foreach($orderInfo as $OrderIndex => $orderInfoRow){
					foreach($orderInfoRow['Order'] as $key => $order) {
						if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
							$isOrderFound = true;
							$newOrderDate = date('Y-m-d H:i:s');
							$newDupOrder = $order;
							$newDupOrder['OrderStaff'] = "";
							$newDupOrder['OrderDate'] = $newOrderDate;
							$newDupOrder['OrderLastUpDate'] = $newOrderDate;
							$newDupOrder['OrderDeliveryDate'] = "";
							$newDupOrder['OrderStatus'] = "Ordered";
							$newDupOrder['OrderTracking'] = "";
							$newDupOrder['OrderPaid'] = "";

							$newOrderInfo = $orderInfo[$OrderIndex];
							$newOrderInfo['Order'][0] = $newDupOrder;

							$orderInfo[]=$newOrderInfo;
							$CustomerName = $orderInfoRow['CustomerName'];

							$CustomerID = isset($orderInfo[$OrderIndex]['BuyerUserID'])?$orderInfo[$OrderIndex]['BuyerUserID']:'';
							if($CustomerID==''){
								if(isset($orderInfo[$OrderIndex]['CustomerName']) && $orderInfo[$OrderIndex]['CustomerName'] != '') {
									$CustomerID = str_replace(' ', '_', $orderInfo[$OrderIndex]['CustomerName']);
								}
							}
							break;
						}
					}
				}
				if($isOrderFound) {
					$this->saveFile($filename, $orderInfo);
					$rs = array();
					$rs['Order'] = $orderInfo[$OrderIndex];
					$rs['Order']['Order'] = $newDupOrder;
	                $rs['Order']['CustomerName'] = $CustomerName;
	                $rs['Order']['fileName'] = $file;
	                $rs['Order']['Username'] = "";
	                $rs['Order']['Zipcode'] = "";
					$rs['Order']['OrderRetailStore'] = $store;
					$rs['OrderRetailStore'] = $store;
                	$rs['success'] = true;
                	$rs['CustomerID'] = $CustomerID;
	            	$rs['fileName'] = $file;
	            	$rs['OrderDate'] = $newOrderDate;

					//Update status to log file [START]---
					$this->updateLog(array('store'=>$store));
					//Update status to log file [END]---
					return $rs;
				}
			}

		}
		else {
			$Username = '';
			$Zipcode = '';
			$exfileName = explode('+', $file);
			if(isset($exfileName[0]) && isset($exfileName[1])){
				$Username = $exfileName[1];
				$Zipcode = $exfileName[0];
			}

			if ($store == 'BodiFranchise') {
				$storeInst = StoreFactory::create($file);
				$customerInfo = $storeInst->getJson(['date' => $OrderDate]);
			} else {
				$customerInfo = $this->loadFile($customerInfoDir.$file.'.json');
			}

			$isOrderFound = false;
			if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
				foreach ($customerInfo['Order'] as $key => $order) {
					$dateToChk = $order['OrderDate'];
					if ($dateToChk == $OrderDate) {
						$isOrderFound = true;
						$newOrderDate = date('Y-m-d H:i:s');
						$newDupOrder = $order;
						$newDupOrder['OrderStaff'] = "";
						$newDupOrder['OrderDate'] = $newOrderDate;
						$newDupOrder['OrderLastUpDate'] = $newOrderDate;
						$newDupOrder['OrderDeliveryDate'] = "";
						$newDupOrder['OrderStatus'] = "Ordered";
						$newDupOrder['OrderTracking'] = "";
						$newDupOrder['OrderPaid'] = "";
						$customerInfo['Order'][]=$newDupOrder;
						break;
					}
				}
			}
			if($isOrderFound) {
				if ($store == 'BodiFranchise') {
					$storeInst = StoreFactory::create($file);
					$storeInst->saveJson(['date' => $OrderDate], $customerInfo);
				} else {
					$this->saveFile($customerInfoDir.$file.'.json', $customerInfo);
				}
				//Update status to log file [START]---
				$this->updateLog(array('store'=>$store));
				//Update status to log file [END]---

				$rs = array();
				$rs['success'] = true;
				$rs['Order'] = [];
				$rs['Order']['Order'] = $newDupOrder;
                $rs['Order']['CustomerName'] = $customerInfo['CustomerName'];
				$rs['Order']['OrderRetailStore'] = $store;
				$rs['Order']['fileName'] = $file;
                $rs['Order']['Username'] = $Username;
                $rs['Order']['Zipcode'] = $Zipcode;
				$rs['CustomerID'] = $file;
		        $rs['fileName'] = $file;
		        $rs['OrderDate'] = $newOrderDate;
				return $rs;

			}
			else {
				$rs = array(
					'success' => false,
					'err' => "Order not found",
				);
				return $rs;
			}
		}



	}
	public function updateOrder($customer) {

		$store = $customer['OrderStore'];
		$file = $customer['file'];
		$OrderDate = $customer['OrderDate'];
		$NewOrderDate = $customer['NewOrderDate'];
		$OrderStatus = $customer['OrderStatus'];

		if($store == 'BodiStaff') {
			$customerInfoDir = "../Staff/Contact/";
			$customerTemplateDir = "../Staff/Contact/";
			$Customertemplate = $this->loadFile($customerTemplateDir."contact-template.json");
		}
		else {
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$customerTemplateDir = "../../bodiforbusiness/retail/";
			$Customertemplate = $this->loadFile($customerTemplateDir."template.json");
		}
		$items = $customer['OrderItems'];
		$currOrderStatus = $customer['OrderStatus'];
		$CustomerID='';
		$customer_log = $customer['customerLogData']['customer_log'];
		$islogUpdatable = false;


		$products = array();
		if(($currOrderStatus == 'Shipped' && $store != 'BodiShop') || ($currOrderStatus == 'Delivered' && $store == 'BodiShop')){
			$products = $this->getProductList();
		}

		$is_order_found = false;
		$rs = array('success' => true);

		//For Ebay Order json file-----
		if($store=='Ebay' || $store=='Etsy' || $store=='Amazon' || $store=='BodiShop'){
			//Create New File---
			$isNewFile = strpos($file, 'newFile-') !== false;
			$isNew = strpos($file, 'new-') !== false;
			if($isNewFile || $isNew) {
				$order = array();
				$order['OrderItems'] = array();
				$order['Order']['OrderRetailStore'] = $store;
				$order['Order']['OrderStatus'] = 'Ordered';
				$OrderTracking = array();
				if(isset($customer['Tracking1'])) {
					array_push($OrderTracking, $customer['Tracking1']);
				}
				if(isset($customer['Tracking2'])) {
					array_push($OrderTracking, $customer['Tracking2']);
				}
				if(isset($customer['Tracking3'])) {
					array_push($OrderTracking, $customer['Tracking3']);
				}
				if(isset($customer['Tracking4'])) {
					array_push($OrderTracking, $customer['Tracking4']);
				}
				if(isset($customer['Tracking5'])) {
					array_push($OrderTracking, $customer['Tracking5']);
				}
				$order['Order']['OrderTracking'] = $OrderTracking;
				$order['Order']['OrderCarrier'] = isset($customer['Carrier'])?$customer['Carrier']:'';
				$order['Order']['OrderCarrierService'] = isset($customer['CarrierService'])?$customer['CarrierService']:'';
				$order['Username'] = isset($customer['Username'])?$customer['Username']:'';
				$order['Zipcode'] = isset($customer['Zipcode'])?$customer['Zipcode']:'';
				$result = $this->createQuickOrder($order);
				if($result['success']){
					$file = $result['fileName'];
					$OrderDate = $result['OrderDate'];
					$CustomerID = $result['CustomerID'];
					$customer['OrderStatus'] = 'Ordered';
					$customer['OrderId'] = $result['CustomerID'];
				}
				else {
					$rs['success'] = false;
					$rs['err'] = "Can't find Order..";
					return $rs;
				}
			}
			//Create New File END---


			//New order check---
			$isNew = false;
			$isNew = strpos($OrderDate, 'new-') !== false;
			if($isNew) {
				$OrderDate = str_replace('new-', '',$OrderDate);
				$this->createNewStoreFile($store,$file,$OrderDate);
			}

			$filename = $store. '/' . $file . '.json';
			$orderInfo = $this->loadFile($filename);
			if(empty($orderInfo)) {
				$rs = array(
					'success' => false,
					'err' => "File not found",
				);
				return $rs;
			}
			//pr($orderInfo);die('STOP');
			if(count($orderInfo)>0){
				foreach($orderInfo as $OrderIndex => $orderInfoRow){
					if(isset($orderInfoRow['Order']) && !empty($orderInfoRow['Order'])) {
						foreach($orderInfoRow['Order'] as $key => $order) {
							if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
								//pr($order);die('AAA');
								$is_order_found = true;
								$orderData = $order['OrderDate'];
								$prevOrderStatus = $order['OrderStatus']; //previous order status from file
								$currOrderStatus = $customer['OrderStatus']; //current order status from request
								$OrderId = $order['OrderId'];
								$CustomerName = $customer_log['CustomerName']!=''?$customer_log['CustomerName']:$orderInfoRow['CustomerName'];
								$Username = $customer_log['Username']!=''?$customer_log['Username']:$orderInfoRow['BuyerUserID'];
								$Zipcode = $customer_log['Zipcode']!=''?$customer_log['Zipcode']:'';
								if($isNew || ($prevOrderStatus != $currOrderStatus)) {
									$islogUpdatable = true;
								}
								if($CustomerID == '') {
									$CustomerID = isset($orderInfo[$OrderIndex]['BuyerUserID'])?$orderInfo[$OrderIndex]['BuyerUserID']:'';
									if($CustomerID==''){
										if(isset($orderInfo[$OrderIndex]['CustomerName']) && $orderInfo[$OrderIndex]['CustomerName'] != '') {
											$CustomerID = str_replace(' ', '_', $orderInfo[$OrderIndex]['CustomerName']);
										}
									}
								}
								//Remove from Order----------
								if($customer['OrderStatus'] == 'Delete') {
									array_splice($orderInfo, $OrderIndex, 1);
									$this->saveFile($filename, $orderInfo);
									//Update status to log file [START]---
									$this->updateLog(array('store'=>$store));
									//Update status to log file [END]---
									$rs = array();
				                	$rs['success'] = true;
					            	$rs['is_deleted'] = true;
					            	$rs['CustomerID'] = $CustomerID;
					            	$rs['fileName'] = $CustomerID;
					            	return $rs;

								}


								if($customer['EbayCustomerName']!='') {
									$orderInfo[$OrderIndex]['CustomerName'] = ucwords(strtolower($customer['EbayCustomerName']));
									$orderInfo[$OrderIndex]['Addresses'][0]['AddressName'] = ucwords(strtolower($customer['EbayCustomerName']));
								}
								if($customer['EbayAddressDetail']!='') {
									$orderInfo[$OrderIndex]['Addresses'][0]['AddressDetail'] = ucwords(strtolower($customer['EbayAddressDetail']));
								}
								if($customer['EbayAddressStreet']!='') {
									$orderInfo[$OrderIndex]['Addresses'][0]['AddressStreet'] = ucwords(strtolower($customer['EbayAddressStreet']));
								}
								if($customer['EbayAddressUnit']!='') {
									$orderInfo[$OrderIndex]['Addresses'][0]['AddressUnit'] = ucwords(strtolower($customer['EbayAddressUnit']));
								}
								if($customer['EbayAddressCity']!='') {
									$orderInfo[$OrderIndex]['Addresses'][0]['AddressCity'] = ucwords(strtolower($customer['EbayAddressCity']));
								}
								if($customer['EbayAddressState']!='') {
									$orderInfo[$OrderIndex]['Addresses'][0]['AddressState'] = $customer['EbayAddressState'];
								}
								if($customer['OrderAddressType']!='') {
									$orderInfo[$OrderIndex]['Addresses'][0]['AddressZip'] = $customer['OrderAddressType'];
								}
								if($customer['EbayAddressCountry']!='') {
									$orderInfo[$OrderIndex]['Addresses'][0]['AddressCountry'] = $customer['EbayAddressCountry'];
								}

								$orderInfo[$OrderIndex]['Order'][$key]['OrderCarrier'] = $customer['Carrier'];
								$orderInfo[$OrderIndex]['Order'][$key]['OrderCarrierService'] = $customer['CarrierService'];
								$OrderTracking = array();
								if(isset($customer['Tracking1'])) {
									array_push($OrderTracking, $customer['Tracking1']);
								}
								if(isset($customer['Tracking2'])) {
									array_push($OrderTracking, $customer['Tracking2']);
								}
								if(isset($customer['Tracking3'])) {
									array_push($OrderTracking, $customer['Tracking3']);
								}
								if(isset($customer['Tracking4'])) {
									array_push($OrderTracking, $customer['Tracking4']);
								}
								if(isset($customer['Tracking5'])) {
									array_push($OrderTracking, $customer['Tracking5']);
								}
								$orderInfo[$OrderIndex]['Order'][$key]['OrderTracking'] = $OrderTracking;
								$orderInfo[$OrderIndex]['Order'][$key]['OrderId'] = $customer['OrderId'];
								$orderInfo[$OrderIndex]['Order'][$key]['OrderNotes'] = ucwords(strtolower($customer['Notes']));
								$orderInfo[$OrderIndex]['Order'][$key]['OrderStatus'] = $customer['OrderStatus'];
								$orderInfo[$OrderIndex]['Order'][$key]['OrderAddressType'] = $customer['OrderAddressType'];
								$orderInfo[$OrderIndex]['Order'][$key]['OrderPaymentType'] = $customer['OrderPaymentType'];

								$orderInfo[$OrderIndex]['Order'][$key]['OrderItems'] = $items;

								$totalOrderPrice = 0.00;
								$totalProductPrice = 0.00;
								$OrderShipWeightTotal = 0;
								if(isset($orderInfo[$OrderIndex]['Order'][$key]['OrderItems'])){
									foreach($orderInfo[$OrderIndex]['Order'][$key]['OrderItems'] as $OrderItem) {
										if($OrderItem['OrderProduct']!='' && $OrderItem['OrderPrice']>0 && $OrderItem['OrderQuantity']>0){
											$itemTotal = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
											if(isset($OrderItem['OrderItemDiscount']) && $OrderItem['OrderItemDiscount']!=''){
												$OrderItemDiscount = (float)$OrderItem['OrderItemDiscount'];
												$itemTotal = $itemTotal-($itemTotal*$OrderItemDiscount/100);
											}
											$totalProductPrice += $itemTotal;
											if($OrderItem['OrderShipWeight']!='' && $OrderItem['OrderShipWeight']>0) {
												$OrderShipWeightTotal += $OrderItem['OrderShipWeight'];
											}
										}
									}
								}
								$totalOrderPrice += $totalProductPrice;
								//Overwrite OrderShipWeightTotal with requested ShipWeight
								if(isset($customer['shipweightTotal']) && $customer['shipweightTotal']>0) {
									$OrderShipWeightTotal = $customer['shipweightTotal'];
								}
								//Discount section Start----------------
								$baseDiscountRate = 0;
								$baseDiscountAmount = 0.00;
								$couponCodeDiscountRate = 0;
								$couponDiscountAmount = 0.00;
								$OrderReward = 0.00;
								if(isset($customer['OrderReward']) && $customer['OrderReward']!=''){
									$OrderReward = $customer['OrderReward'];
								}
								//Apply the coupon
								if(isset($customer['OrderDiscountCoupon']) && $customer['OrderDiscountCoupon']!=''){
									//Base Discount-----------------
									if(isset($customer['DiscountType']) && $customer['DiscountType'] == 'P') {
										$baseDiscountRate = $customer['OrderDiscountCoupon'];
										$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
									}
									//Coupon Discount ---------
									else if(isset($customer['DiscountType']) && $customer['DiscountType'] == 'F') {
										$couponDiscountAmount = $customer['OrderDiscountCoupon'];
									}
								}
								else {
									//Calculate prev discount --
									$baseDiscountRate = 0;
									$baseDiscountAmount = 0;
									$couponDiscountAmount = 0;
									if(isset($orderInfo[$OrderIndex]['Order'][$key]['OrderDiscount']) && $orderInfo[$OrderIndex]['Order'][$key]['OrderDiscount'] != '') {
										$baseDiscountRate = $orderInfo[$OrderIndex]['Order'][$key]['OrderDiscount'];
										$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
									}
									if(isset($orderInfo[$OrderIndex]['Order'][$key]['OrderCoupon']) && $orderInfo[$OrderIndex]['Order'][$key]['OrderCoupon'] != '') {
										$couponDiscountAmount = $orderInfo[$OrderIndex]['Order'][$key]['OrderCoupon'];
									}
								}
								$totalOrderPrice -= $baseDiscountAmount;
								$totalOrderPrice -= $couponDiscountAmount;
								$totalOrderPrice -= $OrderReward;
								//Discount section End----------------
				                $totalWithoutShipping = $totalOrderPrice;
				                //Shipping ---------
				                $OrderCarrierFeeRetail = '';
								if($customer['OrderCarrierFeeRetail']!=''){
									$OrderCarrierFeeRetail = $customer['OrderCarrierFeeRetail'];
									$totalOrderPrice += $OrderCarrierFeeRetail;
									$OrderCarrierFeeRetail = number_format($OrderCarrierFeeRetail,2,".","");
								}
				                $OrderCarrierFeeCost = '';
								if($customer['OrderCarrierFeeCost']!=''){
									$OrderCarrierFeeCost = $customer['OrderCarrierFeeCost'];
									$OrderCarrierFeeCost = number_format($OrderCarrierFeeCost,2,".","");
								}
								$totalOrderPrice = number_format($totalOrderPrice,2,".","");


								$orderInfo[$OrderIndex]['Order'][$key]['OrderDiscount'] = "$baseDiscountRate";
								$orderInfo[$OrderIndex]['Order'][$key]['OrderReward'] = "$OrderReward";
								$orderInfo[$OrderIndex]['Order'][$key]['OrderCoupon'] = "$couponDiscountAmount";
								$orderInfo[$OrderIndex]['Order'][$key]['OrderCarrierFeeRetail'] = $OrderCarrierFeeRetail;
								$orderInfo[$OrderIndex]['Order'][$key]['OrderCarrierFeeCost'] = $OrderCarrierFeeCost;
								$orderInfo[$OrderIndex]['Order'][$key]['OrderShipWeightTotal'] = "$OrderShipWeightTotal";
								if(isset($customer['OrderBoxsize']) && $customer['OrderBoxsize']!='') {
									$orderInfo[$OrderIndex]['Order'][$key]['OrderBoxsize'] = $customer['OrderBoxsize'];
								}
								$orderInfo[$OrderIndex]['Order'][$key]['OrderTotal'] = $totalOrderPrice;
								if($prevOrderStatus != 'Delivered' && $currOrderStatus == 'Delivered' && $store=='BodiShop') {
									$orderInfo[$OrderIndex]['Order'][$key]['OrderPaid'] = $totalOrderPrice;
								}
								//$orderInfo[$OrderIndex] = $this->arrangeCustomerEtsy($orderInfo[$OrderIndex]);
								$this->saveFile($filename, $orderInfo);

								$orderData = $orderInfo[$OrderIndex]['Order'][$key];
								$rs = array();
								$rs['Order'] = $orderInfo[$OrderIndex];
								$rs['Order']['Order'] = $orderData;
				                $rs['Order']['CustomerName'] = $CustomerName;
				                $rs['Order']['fileName'] = $file;
				                $rs['Order']['Username'] = $Username;
				                $rs['Order']['Zipcode'] = $Zipcode;
								$rs['Order']['OrderRetailStore'] = $store;
								$rs['OrderRetailStore'] = $store;
			                	$rs['success'] = true;
			                	$rs['CustomerID'] = $CustomerID;
				            	$rs['fileName'] = $file;
				            	$rs['OrderDate'] = $OrderDate;

								//For reduce inventory [Start]----
								/*$OrderStoreINV = $store;
								if($prevOrderStatus != 'Shipped' && $currOrderStatus == 'Shipped' && $store!='BodiShop') {
									$this->reduceInv($items, $products, $OrderStoreINV, true);//false = update sale data also..//true for no update sale...
									$rs['Data'] = $this->InvDataForCache;
								}
								else if($prevOrderStatus != 'Delivered' && $currOrderStatus == 'Delivered' && $store=='BodiShop') {
									//$this->reduceInv($items, $products, $OrderStoreINV, false);//false = update sale data also..//true for no update sale...
									$this->reduceInv($items, $products, $OrderStoreINV, true);//false = update sale data also..//true for no update sale...
									$rs['Data'] = $this->InvDataForCache;
								}*/

								//Update status to log file [START]---
								$this->updateLog(array('store'=>$store));
								//Update status to log file [END]---
								return $rs;
							}
						}
					}
				}
			}
		}

		else {
			//For Cart Folder (IPaddress File)--
			$isCart = strpos($file, 'Cart-') !== false;
			$orders = array();
			if($isCart) {
				$customerLogData = json_decode(file_get_contents("../../bodiforbusiness/".$store."/Cart/_log.json"), true);
				$shortOrderDate = str_replace('Cart-','',$file);
				if($shortOrderDate == '') {
					$rs['success'] = false;
					$rs['err'] = "Invalid Date.";
					return $rs;
				}
				$isLogFound = false;
				$isOrderFound = false;
				if(!empty($customerLogData)) {
					foreach($customerLogData as $customerLogKey => $customerLogRow){
						if($customerLogRow['CustomerID'] == $shortOrderDate) {
							$isLogFound = true;
							if(!empty($customerLogRow['OrderStatus'])) {
								foreach($customerLogRow['OrderStatus'] as $OrderDateKey => $ip){

									$customerInfo = json_decode(file_get_contents("../../bodiforbusiness/".$store."/Cart/".$ip.".json"), true);
									if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
										foreach($customerInfo['Order'] as $orderKey => $order) {
											if($order['OrderDate'] == '') {
												array_splice($customerInfo['Order'], $orderKey, 1);
											}
										}
										if(empty($customerInfo['Order'])) {
											@unlink("../../bodiforbusiness/".$store."/Cart/".$ip.".json");
										}
										else {
											$this->saveFile("../../bodiforbusiness/".$store."/Cart/".$ip.".json", $customerInfo);
										}
										$this->updateLog(array('store'=>$store.'/Cart'));
									}

									//echo "A".$OrderDateKey."===".$OrderDate."A";
									if($OrderDateKey == $OrderDate) {
										$isOrderFound = true;
										//Remove From Customer file---
										if($OrderStatus == 'Delete') {
											@unlink("../../bodiforbusiness/".$store."/Cart/".$ip.".json");
											//Update status to log file [START]---
											$this->updateLog(array('store'=>$store.'/Cart'));
											//Update status to log file [END]---
											$rs = array();
						                	$rs['success'] = true;
							            	$rs['is_deleted'] = true;
							            	$rs['CustomerID'] = $CustomerID;
							            	$rs['fileName'] = $CustomerID;
							            	return $rs;
										}
										break;
									}
								}
							}
							break;
						}
					}
				}

				if(!$isLogFound){
					$rs['success'] = false;
					$rs['err'] = "No Log found.";
					return $rs;
				}
				else if(!$isOrderFound){
					//Order not found but updated the log for next time.
					$rs = array();
                	$rs['success'] = true;
	            	$rs['is_deleted'] = true;
	            	$rs['CustomerID'] = $CustomerID;
	            	$rs['fileName'] = $CustomerID;
	            	return $rs;
				}
				else {
					$rs['success'] = false;
					$rs['err'] = "Save from Ip Address is still not completed.";
					return $rs;
				}


			}
			else {
				$isNewOrder = strpos($OrderDate, 'new-') !== false;
				if ($isNewOrder) {
					$OrderDate = str_replace('new-', '', $OrderDate);
				}
				$CustomerID = $file;
				$Username = '';
				$Zipcode = '';
				$exfileName = explode('+', $CustomerID);
				if(isset($exfileName[0]) && isset($exfileName[1])){
					$Username = $exfileName[1];
					$Zipcode = $exfileName[0];
				}
				if ($store == 'BodiFranchise') {
					$storeInst = StoreFactory::create('BodiFranchise');
					$customerInfo = $storeInst->getJson([
						'date' => $OrderDate,
						'CustomerID' => $CustomerID
					]);
				} else {
					$customerInfo = $this->loadFile($customerInfoDir.$CustomerID.'.json');
				}
				$customerInfo['CustomerName'] = ucwords(strtolower($customer['CustomerName']));
				//Remove From Customer file---
				if($customer['OrderStatus'] == 'Delete') {
					foreach ($customerInfo['Order'] as $key => $order) {
						$dateToChk = $order['OrderDate'];
						if ($dateToChk == $OrderDate) {
							//Only delete order---
							array_splice($customerInfo['Order'], $key, 1);
							if ($store == 'BodiFranchise') {
								$storeInst->saveJson([
									'date' => $OrderDate,
									'CustomerID' => $CustomerID
								], $customerInfo);
							} else {
								$this->saveFile($customerInfoDir.$CustomerID.'.json', $customerInfo);
								$this->updateLog(array('store'=>$store));
							}

							$rs = array();
			            	$rs['success'] = true;
			            	$rs['is_deleted'] = true;
			            	$rs['CustomerID'] = $CustomerID;
			            	$rs['fileName'] = $CustomerID;
			            	return $rs;
						}
					}
				}
				$customerInfo['CustomerName'] = ucwords(strtolower($customer['CustomerName']));
				if($customer_log['CustomerName']!='') {
					$customerInfo['CustomerName'] = ucwords(strtolower($customer_log['CustomerName']));
				}
				if($customer_log['Email']!='') {
					$customerInfo['Email'] = ucwords(strtolower($customer_log['Email']));
				}
				if($customer_log['Phone']!='') {
					$customerInfo['Phone'] = $customer_log['Phone'];
				}
				if($customer_log['Password']!='') {
					$customerInfo['Password'] = $customer_log['Password'];
				}
				//New order check---
				if($isNewOrder) {
					$newOrder = $customerInfo['Order'][0] ?? new Model\Order();
					$newOrder['OrderDate'] = $OrderDate;
					$customerInfo['Order'][] = $newOrder;
				}

				foreach ($customerInfo['Order'] as $key => $order) {
					$dateToChk = $order['OrderDate'];
					if ($dateToChk == $OrderDate) {
						$is_order_found = true;
						$prevOrderStatus = $order['OrderStatus']; //previous order status from file
						$currOrderStatus = $customer['OrderStatus']; //current order status from request

						//Update status to log file [START]---
						$is_OrderStatusChange = false;
						if($prevOrderStatus != $currOrderStatus){
							$is_OrderStatusChange = true;
						}
						//Update status to log file [END]---
						if($customerInfo['Order'][$key]['OrderDate'] == '') {
							$OrderDate = date('Y-m-d H:i:s');
							$customerInfo['Order'][$key]['OrderDate'] = $OrderDate;
						}
						$customerInfo['Order'][$key]['OrderCarrier'] = $customer['Carrier'];
						$customerInfo['Order'][$key]['OrderCarrierService'] = $customer['CarrierService'];
						$OrderTracking = array();
						if(isset($customer['Tracking1'])) {
							array_push($OrderTracking, $customer['Tracking1']);
						}
						if(isset($customer['Tracking2'])) {
							array_push($OrderTracking, $customer['Tracking2']);
						}
						if(isset($customer['Tracking3'])) {
							array_push($OrderTracking, $customer['Tracking3']);
						}
						if(isset($customer['Tracking4'])) {
							array_push($OrderTracking, $customer['Tracking4']);
						}
						if(isset($customer['Tracking5'])) {
							array_push($OrderTracking, $customer['Tracking5']);
						}
						$customerInfo['Order'][$key]['OrderTracking'] = $OrderTracking;
						$customerInfo['Order'][$key]['OrderId'] = $customer['OrderId'];
						$customerInfo['Order'][$key]['OrderNotes'] = ucwords(strtolower($customer['Notes']));
						$customerInfo['Order'][$key]['OrderStatus'] = $customer['OrderStatus'];
						if(isset($customer['OrderAddressType'])) {
							$customerInfo['Order'][$key]['OrderAddressType'] = $customer['OrderAddressType'];
						}
						if($customerInfo['Order'][$key]['OrderAddressType'] == ''){
							if(isset($customerInfo['Addresses']) && count($customerInfo['Addresses']) == 1){
								foreach($customerInfo['Addresses'] as $addressesData){
									if($addressesData['AddressZip'] != '') {
										$customerInfo['Order'][$key]['OrderAddressType'] = $addressesData['AddressZip'];
									}
								}
							}
						}



						if(isset($customer['OrderPaymentType'])) {
							$customerInfo['Order'][$key]['OrderPaymentType'] = $customer['OrderPaymentType'];
						}

						if($prevOrderStatus != 'Delivered' && $currOrderStatus == 'Delivered'){
							$customerInfo['Order'][$key]['OrderDeliveryDate'] = date("Y-m-d");
						}
						else if($prevOrderStatus == 'Ordered' && $currOrderStatus == 'Shipped'){
							$cDate = date("Y-m-d");
							$OrderDeliveryDateObj = new DateTime($cDate);
							$OrderDeliveryDateObj->add(new DateInterval('P7D'));
							$OrderDeliveryDate = $OrderDeliveryDateObj->format('Y-m-d');
							$customerInfo['Order'][$key]['OrderDeliveryDate'] = $OrderDeliveryDate;
						}

						//For removing previous Items key. Now it is renamed to OrderItems ....
						if(isset($customerInfo['Order'][$key]['Items'])) {
							$customerInfo['Order'][$key]['OrderItems'] = $customerInfo['Order'][$key]['Items'];
							unset($customerInfo['Order'][$key]['Items']);
						}
						$customerInfo['Order'][$key]['OrderItems'] = $items;

						$totalOrderPrice = 0.00;
						$totalProductPrice = 0.00;
						$OrderShipWeightTotal = 0.00;
						if(isset($customerInfo['Order'][$key]['OrderItems'])){
							foreach($customerInfo['Order'][$key]['OrderItems'] as $OrderItem) {
								if($OrderItem['OrderProduct']!='' && $OrderItem['OrderPrice']>0 && $OrderItem['OrderQuantity']>0){
									$itemTotal = $OrderItem['OrderPrice']*$OrderItem['OrderQuantity'];
									if(isset($OrderItem['OrderItemDiscount']) && $OrderItem['OrderItemDiscount']!=''){
										$OrderItemDiscount = (float)$OrderItem['OrderItemDiscount'];
										$itemTotal = $itemTotal-($itemTotal*$OrderItemDiscount/100);
									}
									$totalProductPrice += $itemTotal;
									if($OrderItem['OrderShipWeight']!='' && $OrderItem['OrderShipWeight']>0) {
										$OrderShipWeightTotal += $OrderItem['OrderShipWeight'];
									}
								}
							}
						}
						$totalOrderPrice += $totalProductPrice;

						//Overwrite OrderShipWeightTotal with requested ShipWeight
						if(isset($customer['shipweightTotal']) && $customer['shipweightTotal']>0) {
							$OrderShipWeightTotal = $customer['shipweightTotal'];
						}
						//Discount section Start----------------
						$DiscountType = isset($customer['DiscountType'])?$customer['DiscountType']:'F';
						$OrderDiscountCoupon = isset($customer['OrderDiscountCoupon'])?$customer['OrderDiscountCoupon']:'';
						$CouponCode = isset($customer['CouponCode'])?$customer['CouponCode']:'';
						$CouponStaff = isset($customer['CouponStaff'])?$customer['CouponStaff']:'';

						$is_valid = false;
						if($OrderDiscountCoupon!='' && $CouponCode==''){
							$is_valid = true;
						}
						else if($CouponCode!='') {
							if($OrderDiscountCoupon>$totalOrderPrice) {
								$OrderDiscountCoupon=$totalOrderPrice;
							}
							if(isset($DiscountType) && $DiscountType == 'F' && $OrderDiscountCoupon>$totalOrderPrice) {
								$OrderDiscountCoupon = $totalOrderPrice;
							}
							$Coupon = array(
								'DiscountType' => $DiscountType,
								'OrderDiscountCoupon' => $OrderDiscountCoupon,
								'CouponCode' => $CouponCode,
								'CouponStaff' => $CouponStaff
							);
							$resultCoupon = $this->validateCoupon($Coupon);
							if($resultCoupon['SUCCESS'] == 1) {
								$is_valid = true;
							}
						}


						$baseDiscountRate = 0;
						$baseDiscountAmount = 0.00;
						$couponCodeDiscountRate = 0;
						$couponDiscountAmount = 0.00;
						$OrderReward = 0.00;
						if(isset($customer['OrderReward']) && $customer['OrderReward']!=''){
							$OrderReward = $customer['OrderReward'];
						}

						//Apply the coupon
						if($is_valid) {
							if(isset($customer['OrderDiscountCoupon']) && $customer['OrderDiscountCoupon']!=''){
								//Base Discount-----------------
								if(isset($customer['DiscountType']) && $customer['DiscountType'] == 'P') {
									$baseDiscountRate = $customer['OrderDiscountCoupon'];
									$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
								}
								//Coupon Discount ---------
								else if(isset($customer['DiscountType']) && $customer['DiscountType'] == 'F') {
									$couponDiscountAmount = $customer['OrderDiscountCoupon'];
								}
							}
						}
						else {
							//Calculate prev discount --
							$baseDiscountRate = 0;
							$baseDiscountAmount = 0;
							$couponDiscountAmount = 0;
							if(isset($customerInfo['Order'][$key]['OrderDiscount']) && $customerInfo['Order'][$key]['OrderDiscount'] != '') {
								$baseDiscountRate = $customerInfo['Order'][$key]['OrderDiscount'];
								$baseDiscountAmount = $totalProductPrice*$baseDiscountRate/100;
							}
							if(isset($customerInfo['Order'][$key]['OrderCoupon']) && $customerInfo['Order'][$key]['OrderCoupon'] != '') {
								$couponDiscountAmount = $customerInfo['Order'][$key]['OrderCoupon'];
							}
						}
						$totalOrderPrice -= $baseDiscountAmount;
						$totalOrderPrice -= $couponDiscountAmount;
						$totalOrderPrice -= $OrderReward;
						//Discount section End----------------
		                $totalWithoutShipping = $totalOrderPrice;
		                //Shipping ---------
		                $OrderCarrierFeeRetail = '';
						if($customer['OrderCarrierFeeRetail']!=''){
							$OrderCarrierFeeRetail = $customer['OrderCarrierFeeRetail'];
							$totalOrderPrice += $OrderCarrierFeeRetail;
							$OrderCarrierFeeRetail = number_format($OrderCarrierFeeRetail,2,".","");
						}
		                $OrderCarrierFeeCost = '';
						if($customer['OrderCarrierFeeCost']!=''){
							$OrderCarrierFeeCost = $customer['OrderCarrierFeeCost'];
							$OrderCarrierFeeCost = number_format($OrderCarrierFeeCost,2,".","");
						}

						$totalOrderPrice = number_format($totalOrderPrice,2,".","");
						$customerInfo['Order'][$key]['OrderDiscount'] = "$baseDiscountRate";
						$customerInfo['Order'][$key]['OrderReward'] = "$OrderReward";
						$customerInfo['Order'][$key]['OrderCoupon'] = "$couponDiscountAmount";
						$customerInfo['Order'][$key]['OrderCouponCode'] = "$CouponCode,$CouponStaff";
						$customerInfo['Order'][$key]['OrderCarrierFeeRetail'] = $OrderCarrierFeeRetail;
						$customerInfo['Order'][$key]['OrderCarrierFeeCost'] = $OrderCarrierFeeCost;
						$customerInfo['Order'][$key]['OrderShipWeightTotal'] = "$OrderShipWeightTotal";
						if(isset($customer['OrderBoxsize']) && $customer['OrderBoxsize']!='') {
							$customerInfo['Order'][$key]['OrderBoxsize'] = $customer['OrderBoxsize'];
						}
						$customerInfo['Order'][$key]['OrderTotal'] = $totalOrderPrice;
				        $template = $this->loadFile("ShoppingCartTemplate.json");
				        $order = array_merge($template['Order'][0], array_intersect_key($customerInfo['Order'][$key], $template['Order'][0]));
						$customerInfo['Order'][$key] = $order;

						if($NewOrderDate != '') {
							if(isset($customerInfo['Order'][$key]['OrderDate']) && $customerInfo['Order'][$key]['OrderDate'] != '') {
								$orderTimeArr = explode(' ', $order['OrderDate']);
								$orderTime = $orderTimeArr[1];
								$OrderDate = $NewOrderDate = $NewOrderDate.' '.$orderTime;
								$customerInfo['Order'][$key]['OrderDate'] = $NewOrderDate;
							}
						}

						$orderData = $customerInfo['Order'][$key];
						$customerInfo = $this->arrangeCustomer($customerInfo);

						if ($store == 'BodiFranchise') {
							$is_success = $storeInst->saveJson([
								'date' => $OrderDate,
								'CustomerID' => $CustomerID
							], $customerInfo);
						} else {
							$is_success = $this->saveFile($customerInfoDir.$CustomerID.'.json', $customerInfo);
						}

						$rs = array();
						$rs['success'] = $is_success;
						$rs['Order'] = $customerInfo;
						$rs['Order']['Order'] = $orderData;
		                $rs['Order']['CustomerName'] = $customerInfo['CustomerName'];
						$rs['Order']['OrderRetailStore'] = $store;
						$rs['Order']['fileName'] = $file;
		                $rs['Order']['Username'] = $Username;
		                $rs['Order']['Zipcode'] = $Zipcode;
						$rs['CustomerID'] = $CustomerID;
				        $rs['fileName'] = $file;
				        $rs['OrderDate'] = $OrderDate;

						$this->updateLog(array('store'=>$store));
						//Update status to log file [END]---
						//For reduce inventory [Start]----
						/*$OrderStoreINV = $store;
						if($is_OrderStatusChange && $currOrderStatus == 'Shipped') {
							$this->reduceInv($items, $products, $OrderStoreINV, true);//false = update sale data also..//true for no update sale...
							$rs['Data'] = $this->InvDataForCache;
						}*/
						//For reduce inventory [End]----

						return $rs;
					}
				}
			}
		}

		if($islogUpdatable) {
			$option = array('store' => $store);
			$this->updateLog($option);
		}
		$rs['success'] = false;
		$rs['err'] = "Can't find Order";
		return $rs;
	}
	public function reduceInvFromLog($options=null){
		if(!$options){
			return false;
		}
		$category = $options['category'];
		$productName = $options['product'];
		$OrderQuantity = isset($options['reduceFromRetail']['OrderQuantity'])?$options['reduceFromRetail']['OrderQuantity']:0;
		$productSKU = isset($options['reduceFromRetail']['productSKU'])?$options['reduceFromRetail']['productSKU']:'';
		$store = isset($options['reduceFromRetail']['store'])?$options['reduceFromRetail']['store']:'';
		if($productSKU==''){
			return false;
		}

		$filename = $category.'.json';
		$products = $this->inventory->loadInventory($filename);
		$OrderAttribute = '';
		$Retail = array();
		if(!empty($products)){
			foreach($products as $productTemp) {
				if($productSKU!='') {
					foreach($productTemp['Retail'] as $RetailKey => $RetailTemp) {
						if($RetailKey == $productSKU) {
							$OrderAttribute = $RetailTemp['RetailSize'].''.$RetailTemp['RetailUnit'];
							$product = $productTemp;
							$Retail = $RetailTemp;
							break;
						}
					}
				}
			}
		}
		if(empty($Retail)) {
			return false;
		}
        if (!empty($product)) {
        	$reduceData = array(
				'category' => $category,
				'diff' => $OrderQuantity,
				'store' => $store,
				'format' => $category,
				'product' => $productName,
				'productID' => '',
				'productSKU' => $productSKU,
				'attribute' => $OrderAttribute,
				'updateData' => $Retail,
				'OrderPrice' => '',
				'noReduce' => false,
				'noUpdateSaleData' => true,
			);
			//pr($reduceData);
			return $this->reduce($reduceData); //call the reduce function of Retail/store-updates.php
        }
		return true;
	}
	public function addUpInv($reduceLog=null){
		if(!$reduceLog) {
			return false;
			/*$reduceLog = array(
				'category' => 'Mushroom',
				'product' => 'Cordyceps Mushroom Whole Dried',
				'datetime' => '2025-03-27 13:33:29',
				'reduceFromRetail' => array(
					'OrderQuantity' => '1',
					'productSKU' => 'Mush.Cord.Whol.4oz',
					'store' => 'BodiFranchise'
				)
			);*/
		}
		//pr($reduceLog);
		if($reduceLog['category'] != '') {
			$filename = $reduceLog['category'].'.json';
			$filePath = $this->franchiseInventoryPath.$filename;
	        $products = $this->loadFile($filePath);
	        $OrderAttribute = '';

			$OrderQuantity = $reduceLog['reduceFromRetail']['OrderQuantity'];
			$OrderProductSKU = $reduceLog['reduceFromRetail']['productSKU'];


			if($OrderQuantity>0 && !empty($products)) {
				foreach($products as $productKey => $product){
					$isOrderProductFound = false;
					$isProductSKUFound = false;
					if($OrderProductSKU!=''){
						if(isset($product['Retail'])) {
							foreach($product['Retail'] as $RKey => $Rval) {
								if($RKey == $OrderProductSKU){
									$isOrderProductFound = true;
									$isProductSKUFound = true;
									$RetailSize = $Rval['RetailSize'];
									$RetailUnit = $Rval['RetailUnit'];
									$StockRetailShop = 0;
									if($Rval['StockRetailShop']!='' && $Rval['StockRetailShop']>0) {
										$StockRetailShop = $Rval['StockRetailShop'];
									}

									$reduceValue = $RetailSize*$OrderQuantity;


									$convertTo = 'Gr';
									if($RetailUnit == 'mL' || $RetailUnit == 'Li' || $RetailUnit == 'FlOz') {
										$convertTo = 'mL';
									}
									$addupValueGr = (Conversion::convertStockValue($reduceValue, $RetailUnit, $convertTo));
									if($addupValueGr>0) {
										$totalStockRetailShop = (string)ceil($StockRetailShop+$addupValueGr);
										$products[$productKey]['Retail'][$RKey]['StockRetailShop'] = $totalStockRetailShop;
									}

									break;
								}
							}
						}
					}
				}
				$this->saveFile($filePath, $products);
				//echo "Saved";
			}
		}
		return true;
	}

	public function UpdateStatus($OrderDetails){
		$rs = array('success' => false,'Data' => '');
		if(!empty($OrderDetails)) {
			$products = $this->getProductList();
			foreach($OrderDetails as $OrderDetail){
				$file = $OrderDetail['fileName'];
				$OrderDate = $OrderDetail['OrderDate'];
				$store = $OrderDetail['OrderRetailStore'];
				$currOrderStatus = $OrderDetail['OrderStatusToUpdate'];

				if($store == 'Ebay' || $store == 'Etsy' || $store == 'Amazon' || $store == 'BodiShop') {
					$filename = $store.'/'. $file . '.json';
					$orderInfo = $this->loadFile($filename);
					if(count($orderInfo)>0){
						foreach($orderInfo as $OrderIndex => $orderInfoRow){
							foreach($orderInfoRow['Order'] as $key => $order) {
								if(isset($order['OrderDate']) && $order['OrderDate'] == $OrderDate){
									$orderData = $order['OrderDate'];
									$prevOrderStatus = $order['OrderStatus'];
									$orderInfo[$OrderIndex]['Order'][$key]['OrderStatus'] = $currOrderStatus;
									$orderInfo[$OrderIndex] = $this->arrangeCustomer($orderInfo[$OrderIndex]);
									$this->saveFile($filename, $orderInfo);

									//For reduce inventory [Start]----
									/*$OrderStoreINV = $store;
									if($prevOrderStatus != 'Shipped' && $currOrderStatus == 'Shipped' && $store != 'BodiShop') {
										$OrderItems = $order['OrderItems'];
										$this->reduceInv($OrderItems, $products, $OrderStoreINV);
									}
									else if($prevOrderStatus != 'Delivered' && $currOrderStatus == 'Delivered' && $store == 'BodiShop') {
										$OrderItems = $order['OrderItems'];
										$this->reduceInv($OrderItems, $products, $OrderStoreINV);
									}*/
									//For reduce inventory [End]----
								}
							}
						}
					}
				}
				else {
					$customerInfoDir = "../../bodiforbusiness/{$store}/";
					$rs = array('success' => true);
					$filename = $store. '/'. $file . '.json';
					$orderInfo = $this->loadFile($filename);
					if (!isset($orderInfo['Order'])) {
						$orderInfo['Order'] = array();
					}
					$is_order_found = false;
					//For Order json file-----
					foreach ($orderInfo['Order'] as $key => $order) {
						if ($order['OrderStatus'] == 'Cart') {
							$is_order_found = true;
							unlink($filename);
						}
					}
					//For customer file----
					if(!$is_order_found){
						$CustomerID = $file;
						$customerInfo = $this->loadFile($customerInfoDir.$CustomerID.'.json');
						foreach ($customerInfo['Order'] as $key => $order) {
							if ($order['OrderDate'] == $OrderDate) {
								$is_order_found = true;
								$prevOrderStatus = $order['OrderStatus'];
								$customerInfo['Order'][$key]['OrderStatus'] = $currOrderStatus;
								$customerInfo = $this->arrangeCustomer($customerInfo);
								$this->saveFile($customerInfoDir.$CustomerID.'.json', $customerInfo);
								//For reduce inventory [Start]----
								/*$OrderStoreINV = $store;
								if($prevOrderStatus != 'Shipped' && $currOrderStatus == 'Shipped' && $store != 'BodiShop') {
									$OrderItems = $order['OrderItems'];
									$this->reduceInv($OrderItems, $products, $OrderStoreINV);
								}
								else if($prevOrderStatus != 'Delivered' && $currOrderStatus == 'Delivered' && $store == 'BodiShop') {
									$OrderItems = $order['OrderItems'];
									$this->reduceInv($OrderItems, $products, $OrderStoreINV);
								}*/
								//For reduce inventory [End]----
							}
						}
						$this->updateLog(array('store'=>$store));
					}
				}
			}
			$rs = array('success' => true, 'Data' => $this->InvDataForCache);
		}
		return $rs;
	}
	public function getStoreListingASINId($product, $store='ebay') {
        $itemId = '';
        if(isset($product['StoreListingASIN']) && isset($product['StoreListingASIN'][$store]) && $product['StoreListingASIN'][$store]) {
            if (is_array($product['StoreListingASIN'][$store]) && isset($product['StoreListingASIN'][$store][0])) {
                $itemId = $product['StoreListingASIN'][$store][0];
            } else {
                $itemId = $product['StoreListingASIN'][$store];
            }
        }
        return $itemId;
    }
	public function createLog($customer) {
		$log = array(
	        "Phone" => "",
	        "CustomerName" => "",
	        "Email" => "",
	        "Zipcode" => "",
	        "Password" => "",
	        "OrderRetailStore" => "",
	        "OrderStatus" => "true"
		);
		if (isset($customer['Phone'])) {
			$log['Phone'] = $customer['Phone'];
		}
		if (isset($customer['CustomerName'])) {
			$log['CustomerName'] = $customer['CustomerName'];
		}
		if (isset($customer['Order']['OrderRetailStore'])) {
			$log['OrderRetailStore'] = $customer['Order']['OrderRetailStore'];
		}
		return $log;
	}
	public function addCustomerInfo($store, $customer) {
		$filename = "{$store}/{$customer['CustomerFile']}.json";
		$info = $this->loadFile("template.json");
		$info["Phone"] = isset($customer['Phone'])?$customer['Phone']:"";
		$info["CustomerName"] = $customer["CustomerName"];
		$info["Order"] = array();
		$this->saveFile($filename, $info);
	}
	public function addLog($customer) {
		$rs['success'] = true;
		$logfile = "customers-log.json";
		$loglist = $this->loadFile($logfile);
		foreach ($loglist as $key => $log) {
			if ($log['Phone'] == $customer['Phone']) {
				$rs['success'] = false;
				$rs['err'] = "Phone number {$customer['Phone']} is exist";
				return $rs;
			}
		}
		try {
			$customerLog = $this->createLog($customer);
			$loglist[] = $customerLog;
			$this->saveFile($logfile, $loglist);
			$this->addCustomerInfo($customer['Order']['OrderRetailStore'], $customer);
			return $rs;
		} catch (Exception $e) {
			$rs['success'] = false;
			$rs['err'] = "create log failed: {$e->getMessage()}";
			return $rs;
		}
	}
	public function save($logElement, $infoElement, $updateInfo) {
		$result = array();
		$result['success'] = false;
		if (!$logElement) {
			$result['success'] = false;
			$result['error'] = 'Log data is null or log data has no phone';
			return $result;
		}

		$isNew = strpos($logElement['OldPhone'], 'new-') !== false;
		$logData = $this->loadLog();
		if (!$logData || $isNew) {
			if (!$logData) {
				$logData = array();
			}

			$oldPhone = $logElement['OldPhone'];
			$logElement = $this->organizeCustomerLog($logElement);
			$customer_filename = $this->getCustomerFilename($logElement);

			$info = json_decode(file_get_contents($this->folderPath . 'template.json'), true);
			$info["Phone"] = $logElement['Phone'];
			$info["Email"] = $logElement['Email'];
			$info["CustomerName"] = $logElement["CustomerName"];
			$info = $this->updateCustomerInfoByData($info, $infoElement);

			$logData[] = $logElement;

			$saveLogSuccess = file_put_contents($this->logDataPath . '_temp', json_encode($logData, JSON_PRETTY_PRINT));
			if (isset($logElement['Phone']))
			$saveInfoSuccess = file_put_contents($this->folderPath . $customer_filename . '.json_temp', json_encode($info, JSON_PRETTY_PRINT));

			if ($saveLogSuccess && $saveInfoSuccess) {
				$moveLogSuccess = rename($this->logDataPath . '_temp', $this->logDataPath);
				$moveInfoSuccess = rename($this->folderPath . $customer_filename . '.json_temp', $this->folderPath . $customer_filename . '.json');

				$result['success'] = true;
				$result['OldPhone'] = $oldPhone;
				$result['Phone'] = $logElement['Phone'];
				$result['Email'] = $logElement['Email'];
				return $result;
			} else {
				$result['success'] = false;
				$result['error'] = 'Cannot save data';
				return $result;
			}
		} else {
			for($i = 0; $i < sizeof($logData); $i++) {
				$log = &$logData[$i];
				if ($log['Phone'] == $logElement['OldPhone'] && ((isset($log['Email'])?$log['Email']:'') == $logElement['OldEmail'])) {
					$oldPhone = $logElement['OldPhone'];
					$oldFilename = $this->getCustomerFilename($log);
					$info = $this->loadInfo($log);

					foreach($logElement as $key => $value) {
						$log[$key] = $value;
					}

					$log = $this->organizeCustomerLog($log);
					if (!$info) {
						$info = json_decode(file_get_contents($this->folderPath . 'template.json'), true);
						$info["Phone"] = $logElement['Phone'];
						$info["Email"] = $logElement['Email'];
						$info["CustomerName"] = $logElement["CustomerName"];
						$info = $this->updateCustomerInfoByData($info, $infoElement);
					} else {
						if ($updateInfo) {
							if (!$infoElement) {
								$result['success'] = false;
								$result['error'] = 'Info data is empty';
								return $result;
							} else {
								$this->updateCustomerInfoByData($info, $infoElement);
							}
						}
					}

					$info['Phone'] = $log['Phone'];
					$info['CustomerName'] = $log['CustomerName'];
					$saveLogSuccess = file_put_contents($this->logDataPath . '_temp', json_encode($logData, JSON_PRETTY_PRINT));
					$filename = $this->getCustomerFilename($log);
					$saveInfoSuccess = file_put_contents($this->folderPath . $filename . '.json_temp', json_encode($info, JSON_PRETTY_PRINT));

					if ($saveLogSuccess && $saveInfoSuccess) {
						$moveLogSuccess = rename($this->logDataPath . '_temp', $this->logDataPath);
						$moveInfoSuccess = rename($this->folderPath . $filename . '.json_temp', $this->folderPath . $filename . '.json');
					} else {
						$result['success'] = false;
						$result['error'] = 'Cannot save data';
						return $result;
					}

					$result['success'] = true;
					$result['OldPhone'] = $oldPhone;
					$result['Phone'] = $log['Phone'];
					$result['Email'] = $log['Email'];

					if ($result['OldPhone'] != $result['Phone']) {
						unlink($this->folderPath . $oldFilename . '.json');
					}

					return $result;

					break;
				}
			}
		}

		return $result;
	}
	public function delete($phone, $email) {
		$logData = $this->loadLog();

		if (!$logData || (!$phone && !$email)) {
			$result['success'] = false;
			$result['error'] = 'The customer does not exist';
			return $result;
		}

		for($i = 0; $i < sizeof($logData); $i++) {
			$log = &$logData[$i];
			if ($log['Phone'] == $phone && ((isset($log['Email'])?$log['Email']:'') == $email)) {
				$log['deleted'] = true;

				$saveLogSuccess = file_put_contents($this->logDataPath . '_temp', json_encode($logData, JSON_PRETTY_PRINT));
				if ($saveLogSuccess) {
					$moveLogSuccess = rename($this->logDataPath . '_temp', $this->logDataPath);
				} else {
					$result['success'] = false;
					$result['error'] = 'Cannot save data';
					return $result;
				}

				$result['success'] = true;
				$result['Phone'] = $phone;

				return $result;

				break;
			}
		}
	}
	private function updateCustomerInfoByData(&$info, $infoElement) {
		if (!empty($infoElement['CustomerName'])) {
			$info['CustomerName'] = $infoElement['CustomerName'];
		}
		if (!empty($infoElement['Email'])) {
			$info['Email'] = $infoElement['Email'];
		}
		if (!empty($infoElement['FarmName'])) {
			$info['FarmName'] = $infoElement['FarmName'];
		}
		if (!empty($infoElement['Addresses'])) {
			$info['Addresses'] = $infoElement['Addresses'];
		}
		if (!empty($infoElement['Cards'])) {
			$info['Cards'] = $infoElement['Cards'];
		}

		return $info;
	}
	private function organizeCustomerLog($customerLog) {
		$newCustomerLog = [];
		$topField = 'CustomerName';
		if ($customerLog['Phone'] != '') {
			$topField = 'Phone';
		} elseif ($customerLog['Email'] != '') {
			$topField = 'Email';
		}
		$newCustomerLog[$topField] = $customerLog[$topField];
		unset($customerLog[$topField]);
		unset($customerLog['OldPhone']);
		unset($customerLog['OldEmail']);
		foreach ($customerLog as $key => $value) {
			$newCustomerLog[$key] = $value;
		}
		return $newCustomerLog;
	}

	/**
	* Retail Store functions
	*/
	public function findPackage($format, $sizeData, $packages) {
        $format = str_replace(' ', '-', strtolower($format));
        $attribute = $sizeData['RetailSize'].$sizeData['RetailUnit'];
        $rs = array_filter($packages, function($package) use ($format, $attribute) {
            /*foreach ($package['Formats'] as $f) {
                if (strtolower($f['Format']) == $format && strtolower($f['Attribute']) == $attribute) {
                    return true;
                }
            }*/
            if(strtolower($package['PackageName']) == $attribute) {
                return true;
            }
            return false;
        });
        if (count($rs))
            return array_pop($rs);
        else
            return null;
    }
	public function reducePackage($format, $productSKU, $OrderAttributeKey, $sizeData) {
        $inventories = $this->inventory->loadPackageInventories();
        $packages = $this->inventory->loadJson($this->settingPath);
        $package = $this->findPackage($format, $sizeData, $packages['PackingFee']);
        if ($package) {
            foreach ($package['PackageOptions'] as $option) {
                $i = -1;
                $format = '';
                $inventoryItem = null;
                $k = -1;
                foreach ($inventories as $key => $inventory) {
                    $i = $this->findInventoryIndexByProduct($inventory['data'], $option);
                    if ($i >= 0) {
                        $k = $key;
                        $inventoryItem = $inventory['data'][$i];
                        $format = $option;
                        break;
                    }
                }
                if ($i >= 0) {
                    $inventoryItem = $this->reduceInventoryItem($inventoryItem, array('units_select' => 1, 'volume_quantity' => 1, 'unit' => 'item', 'productSKU' => $productSKU, 'OrderAttributeKey' => $OrderAttributeKey), $error);
                    $inventories[$k]['data'][$i] = $inventoryItem;
                }
                foreach ($inventories as $key => $inventory) {
                    $this->inventory->saveInventory($inventory['format'], $inventory['data']);
                }
            }
        }
    }
	public function array_intersect_key_recursive(array $array1, array $array2) {
        $array1 = array_intersect_key($array1, $array2);
        foreach ($array1 as $key => &$value) {
            if (is_array($value) && is_array($array2[$key])) {
                $value = $this->array_intersect_key_recursive($value, $array2[$key]);
            }
        }
        return $array1;
    }
	public function addupCapital($inventoryItem, $sizeData, $store, $stock) {
        $retail = new Retail();
        $capital = new Capital();
        $capitalData = $capital->createNewObject();
        $retailVal = $retail->calculateRetailUniversal($inventoryItem, $sizeData, 'bodiretailer');
        if($store == 'BODi') {
			$capitalData["CashBankSales"] += $stock*$retailVal;
		}
        else {
		if (isset($capitalData["CashHold{$store}"])) {
			$capitalData["CashHold{$store}"] += $stock*$retailVal;
		}
	}
        $capital->addup($capitalData);
    }

	public function updateMonthlySaleData($inventoryItem, $sizeData, $store, $stock, $OrderPrice=0) {
        $retail = new Retail();
        $updateSaleFileDataPath = __DIR__.'/../../Accounting/monthly-sales.json';
        $sort = array();
        $total_reduce_array = array();
        $total_sales_amount_array = array();
        $total_markeup_amount_array = array();

		//Amazon, Ebay Etsy BODi BodiShop Equine
		if($store=='BODi' || $store=='Equine') {
			$retailVal = $retail->calculateRetailUniversal($inventoryItem, $sizeData, 'bodi4life');
		}
		elseif($store=='BodiShop') {
			$retailVal = $retail->calculateRetailUniversal($inventoryItem, $sizeData, 'bodishop');
		}
		else {
			$retailVal = $retail->calculateRetailUniversal($inventoryItem, $sizeData, 'bodiretailer');
		}
        $markupAmount = $retail->calculateMarkupAmount($inventoryItem, $sizeData, $retailVal);

        $total_reduce_array[$store] = (isset($total_reduce_array[$store])?$total_reduce_array[$store]:0)+$stock;
        if($OrderPrice>0) {
			$total_sales_amount_array[$store] = (isset($total_sales_amount_array[$store])?$total_sales_amount_array[$store]:0) + $stock*$OrderPrice;
		}
		else {
        $total_sales_amount_array[$store] = (isset($total_sales_amount_array[$store])?$total_sales_amount_array[$store]:0) + $stock*$retailVal;
		}

        $total_markeup_amount_array[$store] = (isset($total_markeup_amount_array[$store])?$total_markeup_amount_array[$store]:0)+$stock*$markupAmount;
        date_default_timezone_set("America/New_York");
        $salesData = $this->inventory->loadJson($updateSaleFileDataPath);
        $json_update = 0;

        $date = date('Y-m-d');
        $month = date('m');
        $month_start_date = date('Y-m-01');
        $month_end_date = date('Y-m-t');
        $month_start_datetime = date('Y-m-01 00:00:01');
        $month_end_datetime = date('Y-m-t 23:59:59');
        foreach($salesData as $key => $part) {
            if ($this->isDateBetweenDates($part['Date'], $month_start_date, $month_end_date)) {
                if ($part['Date'] == $month_start_date) {
                    $salesData[$key] = $this->updateObjectFromData($part, $total_reduce_array, $total_sales_amount_array, $total_markeup_amount_array);
                    $json_update = 1;
                }
            }
        }
        if($json_update == 0) {
            $salesData[] = $this->createNewObjectFromData($month_start_date, $total_reduce_array, $total_sales_amount_array, $total_markeup_amount_array);
        }
        foreach ($salesData as $key => $part) {
            $sort[$key] = strtotime($part['Date']);
        }
        array_multisort($sort, SORT_DESC, $salesData);
        $success = file_put_contents($updateSaleFileDataPath . '_temp', json_encode($salesData, JSON_PRETTY_PRINT));
        if ($success) {
            $moveSuccess = rename($updateSaleFileDataPath . '_temp', $updateSaleFileDataPath);
        }
    }


	public function onlyUpdateSales($OrderItems, $products, $store){
		if(!empty($OrderItems) && !empty($products)) {
			foreach($OrderItems as $OrderItem) {
				$OrderProduct = trim($OrderItem['OrderProduct']);
				$OrderProductID = isset($OrderItem['OrderProductID'])?trim($OrderItem['OrderProductID']):'';
				$OrderProductSKU = isset($OrderItem['OrderProductSKU'])?trim($OrderItem['OrderProductSKU']):'';
				$OrderAttribute = trim($OrderItem['OrderAttribute']);
				$OrderQuantity = $OrderItem['OrderQuantity'];
				$OrderPrice = $OrderItem['OrderPrice'];
				if($OrderProduct!='' && $OrderQuantity > 0) {
					foreach($products as $product){
						$isOrderProductFound = false;
						$isProductSKUFound = false;
						$isProductIDFound = false;
						//Finf product by SKU
						if($OrderProductSKU!=''){
							if(isset($product['value']['itemData']['Retail'])) {
								foreach($product['value']['itemData']['Retail'] as $RKey => $Rval) {
									if($RKey == $OrderProductSKU){
										$isOrderProductFound = true;
										$isProductSKUFound = true;
										$OrderAttribute = $RKey;
										break;
									}
								}
							}
						}
						//Find Product by ItemId
						if(!$isOrderProductFound && $OrderProductID!=''){
							$itemId = $this->getStoreListingASINId($product['value']['itemData'], strtolower($store));
							if($OrderAttribute == '') {
								if($itemId == $OrderProductID){
									$isOrderProductFound = true;
									$isProductIDFound = true;
									if(isset($product['value']['itemData']['Retail'])) {
										foreach($product['value']['itemData']['Retail'] as $RKey => $Rval) {
											if($RKey!= ''){
												$OrderAttribute = $RKey;
												break;
											}
										}
									}
								}
							}
							else {
								if($itemId == $OrderProductID  && isset($product['value']['itemData']['Retail'][$OrderAttribute])){
									$isOrderProductFound = true;
								}
							}

						}
						//Find product by product name
						if(!$isOrderProductFound && trim($product['value']['product']) == $OrderProduct && isset($product['value']['itemData']['Retail'][$OrderAttribute])) {
							$isOrderProductFound = true;
						}
						if($isOrderProductFound) {
							$reduceData = array(
								'category' => $product['value']['inventory'],
								'diff' => $OrderQuantity,
								'store' => $store,
								'format' => $product['value']['inventory'],
								'product' => $product['value']['product'],
								'productID' => $OrderProductID,
								'productSKU' => $OrderProductSKU,
								'attribute' => $OrderAttribute,
								'updateData' => $product['value']['itemData']['Retail'][$OrderAttribute],
								'OrderPrice' => $OrderPrice,
								'noReduce' => true,
								'noUpdateSaleData' => false,
							);
							$this->onlyUpdateSale($reduceData); //call the Update Sales function of Retail/store-updates.php
						}
					}
				}
			}
		}
		return true;
	}
	public function onlyUpdateSale($stockData) {
// load data
        $inventoryData = array();
        $result = array('success' => true, 'data' => array());
        $inventoryName = $stockData['category'];
        $productName = isset($stockData['product'])?$stockData['product']:'';
        $productID = isset($stockData['productID'])?$stockData['productID']:'';
        $productSKU = isset($stockData['productSKU'])?$stockData['productSKU']:'';
        $OrderPrice = isset($stockData['OrderPrice']) && $stockData['OrderPrice']!= ''?$stockData['OrderPrice']:0;

        if($stockData['store'] == 'Bodi4life' || $stockData['store'] == 'Bodi2business') {
			$stockData['store'] = 'BODi';
		}
        $store = $storeOrg = $stockData['store'];
		if($storeOrg == 'Equine' || $storeOrg == 'BodiShop') {
			$store = 'BODi';
		}
        if (!isset($inventoryData[$inventoryName])) {
            $inventoryData[$inventoryName] = $this->inventory->loadInventory($inventoryName);
            if (!$inventoryData[$inventoryName]) {
                $result['success'] = false;
                $result['error'] = 'The inventory does not exist';
                return $result;
            }
        }
// search item
        $inventories = &$inventoryData[$inventoryName];
        if(strtolower($store)=='ebay' || strtolower($store)=='etsy') {
			$product = new Product($stockData['category'], $productName, $inventories, $productID, $productSKU, strtolower($store));
		}
        else {
			$product = new Product($stockData['category'], $productName, $inventories, $productID);
		}
        if ($product->data) {
            $inventoryItem = &$product->data;
        } else {
            $result['success'] = false;
            $result['error'] = 'inventoryItem not found';
            return $result;
        }
//get sizeData
        $sourceItem = $inventoryItem;
        $updateData = $stockData['updateData'];
        $size = $updateData['RetailSize'];
        $unit = $updateData['RetailUnit'];
        $sizeName = $size.$unit;

		$this->shouldReduceStock = (isset($stockData['noReduce']) && $stockData['noReduce'])?false:true;
        $this->shouldupdateSaleData = (isset($stockData['noUpdateSaleData']) && $stockData['noUpdateSaleData'])?false:true;
//check size exist
        if (isset($inventoryItem['Retail'][$sizeName])) {
            $sizeUpdate = &$inventoryItem['Retail'][$sizeName];
            $error = [];
            $diff = isset($stockData['diff'])?$stockData['diff']:1;
            if ($this->shouldReduceStock && isset($sizeUpdate[$store]['Stock']) && $sizeUpdate[$store]['Stock'] > 0) {
            	if(isset($sizeUpdate[$store]['Stock'])) {
                	$sizeUpdate[$store]['Stock'] -= $diff;
                }
                else {
					$sizeUpdate[$store]['Stock'] = 0;
				}
                $sizeUpdate[$store]['Stock'] = (string)$sizeUpdate[$store]['Stock'];
            }
            $inventoryItem = Product::checkStockChange($sourceItem, $inventoryItem);
            if(isset($sizeUpdate[$store]['Sold'])) {
            	if($sizeUpdate[$store]['Sold']!=''){
					$sizeUpdate[$store]['Sold'] += $diff;
				}
				else {
					$sizeUpdate[$store]['Sold'] = $diff;
				}
			}
            else {
				$sizeUpdate[$store]['Sold'] = $diff;
			}
			$sizeUpdate[$store]['Sold'] = (string)$sizeUpdate[$store]['Sold'];
            $updateData[$store]['Sold'] = $sizeUpdate[$store]['Sold'];
            if(!empty($inventoryItem['Retail'])){
				foreach($inventoryItem['Retail'] as $KeyR=>$ValR) {
					$inventoryItem['Retail'][$KeyR] = $this->inventoryTemplate->createRetailTemplate($inventoryItem['Retail'][$KeyR]);
            		$inventories[$product->index] = $product->getData();
				}
			}

            $result['data'] = array(
                'inventoryItem' => $inventoryItem,
                'sizeName' => $sizeName,
                'sizeData' => $sizeUpdate,
            );
            $inventoryItem['Format'] = $product->category;
            $this->updateMonthlySaleData($inventoryItem, $sizeUpdate, $storeOrg, $diff, $OrderPrice);
        } else {
            $result['success'] = false;
            $result['error'] = 'Size not found';
            return $result;
        }
/* new code for sales report update end */
        $result['success'] = true;
        return $result;
    }
	public function onlyUpdateMonthlySales($OrderPrice, $OrderProfit, $store){
		//echo "<br>store=$store";
		$retail = new Retail();
        $updateFileDataPath = __DIR__.'/../../Accounting/monthly-sales.json';
        $sort = array();
		$total_sales_amount_array = array();
        $total_markeup_amount_array = array();

		if($store == 'Bodi4life') {
			$store = 'BODi';
		}
		if($store == 'BodiFranchise') {
			$store = 'BodiShop';
		}

		$total_sales_amount_array[$store] = 0;
		if($OrderPrice>0) {
			$total_sales_amount_array[$store] = $OrderPrice;
		}
		$total_markeup_amount_array[$store] = $OrderProfit;

		date_default_timezone_set("America/New_York");
        $salesData = $this->inventory->loadJson($updateFileDataPath);
        $json_update = 0;

        $date = date('Y-m-d');
        $month = date('m');
        $month_start_date = date('Y-m-01');
        $month_end_date = date('Y-m-t');
        $month_start_datetime = date('Y-m-01 00:00:01');
        $month_end_datetime = date('Y-m-t 23:59:59');
        foreach($salesData as $key => $part) {
            if ($this->isDateBetweenDates($part['Date'], $month_start_date, $month_end_date)) {
                if ($part['Date'] == $month_start_date) {
                    $salesData[$key] = $this->updateObjectFromMonthlyData($part, $total_sales_amount_array, $total_markeup_amount_array);
                    $json_update = 1;
                }
            }
        }
        if($json_update == 0) {
            $salesData[] = $this->createNewObjectFromMonthlyData($month_start_date, $total_sales_amount_array, $total_markeup_amount_array);
        }
        foreach ($salesData as $key => $part) {
            $sort[$key] = strtotime($part['Date']);
        }
        array_multisort($sort, SORT_DESC, $salesData);
        $success = file_put_contents($updateFileDataPath . '_temp', json_encode($salesData, JSON_PRETTY_PRINT));
        if ($success) {
            $moveSuccess = rename($updateFileDataPath . '_temp', $updateFileDataPath);
        }
	}
	public function reduce($stockData) {
		// load data
        $inventoryData = array();
        $result = array('success' => true, 'data' => array());
        $inventoryName = $stockData['category'];
        $productName = isset($stockData['product'])?$stockData['product']:'';
        $productID = isset($stockData['productID'])?$stockData['productID']:'';
        $OrderAttributeKey = $productSKU = isset($stockData['productSKU'])?$stockData['productSKU']:'';
        //$OrderAttributeKey = isset($stockData['attribute'])?$stockData['attribute']:''; //Both are same
        $OrderPrice = isset($stockData['OrderPrice']) && $stockData['OrderPrice']!= ''?$stockData['OrderPrice']:0;

        $storeOrg = $stockData['store']; //Bodi2business

        if($stockData['store'] == 'Bodi4life' || $stockData['store'] == 'Bodi2business') {
			$stockData['store'] = 'BODi';
		}
        $store = $storeForMonthlySale = $stockData['store'];
		if($storeForMonthlySale == 'Equine' || $storeForMonthlySale == 'BodiShop') {
			$store = 'BODi';
		}

        if (!isset($inventoryData[$inventoryName])) {
            $inventoryData[$inventoryName] = $this->inventory->loadInventory($inventoryName);
            if (!$inventoryData[$inventoryName]) {
                $result['success'] = false;
                $result['error'] = 'The inventory does not exist';
                return $result;
            }
        }
// search item
        $inventories = &$inventoryData[$inventoryName];
        if(strtolower($store)=='ebay' || strtolower($store)=='etsy') {
			$product = new Product($stockData['category'], $productName, $inventories, $productID, $productSKU, strtolower($store));
		}
        else {
			$product = new Product($stockData['category'], $productName, $inventories, $productID, $productSKU);
		}
        if ($product->data) {
            $inventoryItem = &$product->data;
        } else {
            $result['success'] = false;
            $result['error'] = 'Inventory Item not found';
            return $result;
        }
//get sizeData
        $sourceItem = $inventoryItem;
        $updateData = $stockData['updateData'];
        $size = $updateData['RetailSize'];
        $unit = $updateData['RetailUnit'];
        $sizeName = $size.$unit;

        $this->shouldReduceStock = (isset($stockData['noReduce']) && $stockData['noReduce'])?false:true;
        $this->shouldupdateSaleData = (isset($stockData['noUpdateSaleData']) && $stockData['noUpdateSaleData'])?false:true;
//check size exist

        if (isset($inventoryItem['Retail'][$productSKU])) {
            $sizeUpdate = &$inventoryItem['Retail'][$productSKU];
            $error = [];
            $diff = isset($stockData['diff'])?$stockData['diff']:1;
            if ($this->shouldReduceStock && isset($sizeUpdate[$store]['Stock']) && $sizeUpdate[$store]['Stock'] > 0) {
            	if(isset($sizeUpdate[$store]['Stock'])) {
                	$sizeUpdate[$store]['Stock'] -= $diff;
                }
                else {
					$sizeUpdate[$store]['Stock'] = 0;
				}
                $sizeUpdate[$store]['Stock'] = (string)$sizeUpdate[$store]['Stock'];
            }
            //1. Reduce Inventory---
    		$inventoryItem = $this->reduceInventoryItem($inventoryItem, array('units_select' => $size, 'volume_quantity' => $diff, 'unit' => $unit, 'productSKU' => $productSKU, 'OrderAttributeKey' => $productSKU, 'store' => $storeOrg), $error);
            if ($inventoryItem === false) {
                $result['success'] = false;
                $result['error'] = end($error);
                return $result;
            }
            $inventoryItem = Product::checkStockChange($sourceItem, $inventoryItem);
            if(isset($sizeUpdate[$store]['Sold'])) {
            	if($sizeUpdate[$store]['Sold']!=''){
					$sizeUpdate[$store]['Sold'] += $diff;
				}
				else {
					$sizeUpdate[$store]['Sold'] = $diff;
				}
			}
            else {
				$sizeUpdate[$store]['Sold'] = $diff;
			}
            $sizeUpdate[$store]['Sold'] = (string)$sizeUpdate[$store]['Sold'];
            $updateData[$store]['Sold'] = $sizeUpdate[$store]['Sold'];
            // if($store != 'BodiStaff') {

            // 	$inventoryItem = $this->addProductSold($inventoryItem, $diff, $size, $unit, $productSKU, $storeOrg);
			// }
            if(!empty($inventoryItem['Retail'])){
				foreach($inventoryItem['Retail'] as $KeyR=>$ValR) {
					$inventoryItem['Retail'][$KeyR] = $this->inventoryTemplate->createRetailTemplate($inventoryItem['Retail'][$KeyR]);
            		$inventories[$product->index] = $product->getData();
				}
			}
            $result['data'] = array(
                'inventoryItem' => $inventoryItem,
                'sizeName' => $sizeName,
                'sizeData' => $sizeUpdate,
            );
            $inventoryItem['Format'] = $product->category;
            if($store != 'BodiStaff') {
				$this->addupCapital($inventoryItem, $sizeUpdate, $store, $diff);
				if ($this->shouldupdateSaleData){
					$this->updateMonthlySaleData($inventoryItem, $sizeUpdate, $storeForMonthlySale, $diff, $OrderPrice);
				}
			}
            $this->reducePackage($product->category, $productSKU, $OrderAttributeKey, $sizeUpdate);
        } else {
            $result['success'] = false;
            $result['error'] = 'Size not found';
            return $result;
        }
        // foreach ($inventoryData as $key => $inventory) {
        //     $this->inventory->saveInventory($key, $inventory);
        // }
/* new code for sales report update end */
        $result['success'] = true;
        return $result;
    }
	public function addProductSold($inventoryItem, $diff, $size, $unit, $productSKU=null, $store=null) {
		$retail = new Retail();
		$type = $retail->getStockRetailType($store);


		if($type!= '') {
			$_type = Retail::getSupplierType(strtolower($unit));
			$convertTo = $_type['StockUnit'];
	        $saleInGram = Conversion::convertStockValue($diff*$size, $unit, $convertTo);
	        $saleInGram = round($saleInGram, 2);

	        $productSoldField = 'ProductSoldWeekly'.$type;
            if(!isset($inventoryItem[$productSoldField])) {
                $inventoryItem[$productSoldField] = array();

            }
            $dateKey = $this->getDate();
            if (!isset($inventoryItem[$productSoldField][$dateKey])) {
                $inventoryItem[$productSoldField] = array($dateKey => 0) + $inventoryItem[$productSoldField];
            }
            $inventoryItem[$productSoldField][$dateKey] += $saleInGram;
            $inventoryItem[$productSoldField][$dateKey] = (string)ceil($inventoryItem[$productSoldField][$dateKey]);
            $inventoryItem = $this->limitProductSoldWeekly($inventoryItem, $type);

		}
        return $inventoryItem;
    }
	public function getProductSoldType($size, $unit) {
        $size = (int)$size;
        $unit = strtolower($unit);
        $type = false;
        if (in_array($size, array(1, 2, 4, 8, 12, 16)) && $unit == 'oz') {
            $type = 'OZ';
        } elseif (in_array($size, array(1)) && $unit == 'lb') {
            $type = 'OZ';
        } elseif (in_array($size, array(1, 2, 4, 8, 12, 16)) && $unit == 'floz') {
            $type = 'OZ';
        } elseif (in_array($size, array(2, 5, 10)) && $unit == 'lb') {
            $type = 'LB';
        } elseif (in_array($size, array(20, 25, 50, 100)) && $unit == 'lb') {
            $type = 'Wholesale';
        } elseif (in_array($unit, array('item', 'pack', 'box', 'roll', 'pair', 'bag', 'bottle', 'tube', 'pouch'))) {
            $type = 'Item';
        } elseif (in_array($unit, array('tea-bag'))) {
            $type = 'OZ';
        }
        return $type;
    }
    public function reduceInventoryItem($inventoryItem, $reduceProduct, &$errors = null) {
    	include_once(__DIR__.'/../../php/supplierform-updates.php');
    	$this->reduceInventoryItem = &$inventoryItem;
        $clientVolume =  (int) $reduceProduct['volume_quantity'];
        $clientUnitSize = (int) $reduceProduct['units_select'];
        $reduceUnit = $reduceProduct['unit']; //oz
        $reduceValue = $clientVolume * $clientUnitSize;
        $productSKU = $reduceProduct['productSKU'];
        $OrderAttributeKey = $reduceProduct['OrderAttributeKey'];
        $sequence = array('productSKU', 'Recipe', 'Bulk', 'Shop');
        $store = isset($reduceProduct['store'])?$reduceProduct['store']:'';
        if($store == 'Bodi2business') {
			$sequence = array('Recipe', 'Bulk');
		}

		//$sequence = array('Recipe', 'Bulk', 'Shop');
        $is_reduced = false;
		if(!$is_reduced) {
			foreach ($sequence as $column) {
	            if ($reduceValue <= 0)
	                break;

	            if($column == 'productSKU') {
					foreach($inventoryItem['Retail'] as $RetailKey => $RetailData){
		                if ($reduceValue <= 0)
		                    break;
	            		if($productSKU != '' && $productSKU == $RetailKey){
							if ($RetailData['StockRetailShop'] == '' || $RetailData['StockRetailShop'] <= 0)
		                    	break;

		                    $RetailDataToSave = $this->reduceFromRetail($inventoryItem['Retail'], $reduceValue, $reduceUnit, $clientUnitSize, $RetailKey, $column);
							if(!empty($RetailDataToSave)) {
								foreach($RetailDataToSave as $RetailDataToSaveKey => $RetailDataToSaveRow) {
									 $inventoryItem['Retail'][$RetailDataToSaveKey] = $this->inventoryTemplate->createRetailTemplate($RetailDataToSaveRow);
								}
							}
						}
	            	}
				}
	            else {
					foreach($inventoryItem['Retail'] as $RetailKey => $RetailData){
	            		if(strtolower($RetailData['StockLocation']) != strtolower($column)){
							continue;
						}
		                if ($reduceValue <= 0)
		                    break;
		                if ($RetailData['StockRetailShop'] == '' || $RetailData['StockRetailShop'] <= 0)
		                    continue;


						$RetailDataToSave = $this->reduceFromRetail($inventoryItem['Retail'], $reduceValue, $reduceUnit, $clientUnitSize, $RetailKey, $column);
						if(!empty($RetailDataToSave)) {
							foreach($RetailDataToSave as $RetailDataToSaveKey => $RetailDataToSaveRow) {
								 $inventoryItem['Retail'][$RetailDataToSaveKey] = $this->inventoryTemplate->createRetailTemplate($RetailDataToSaveRow);
							}
						}
	            	}
				}

	        }
	        //Reduce from Recipe with nigetive
	        //echo "<br>reduceValue2=$reduceValue";
	        //pr($inventoryItem['Retail']);
	        //die('STOP');
	        if ($reduceValue > 0) {
	        	foreach($inventoryItem['Retail'] as $RetailKey => $RetailData){
	        		if($RetailData['StockLocation'] == 'Recipe') {
						$RetailDataToSave = $this->reduceFromRetail($inventoryItem['Retail'], $reduceValue, $reduceUnit, $clientUnitSize, $RetailKey, 'Recipe');
						if(!empty($RetailDataToSave)) {
							foreach($RetailDataToSave as $RetailDataToSaveKey => $RetailDataToSaveRow) {
								 $inventoryItem['Retail'][$RetailDataToSaveKey] = $this->inventoryTemplate->createRetailTemplate($RetailDataToSaveRow);
							}
						}
			        	$is_reduced = true;
			        	break;
					}
	        	}
			}


		}
        return $inventoryItem;
    }
	private function reduceIncomingSupplier($supplier, &$reduce, $type = 'Ordered') {
        if($reduce['value'] <= 0)
            return $supplier;

        $reduceValue = Conversion::convertStockValue($reduce['value'], $reduce['unit'], $supplier['SupplierUnit']);
        if ($supplier[$type] === '') {
        	if(!isset($supplier['Stock'])) {
				$supplier['Stock'] = 0;
			}
            $supplier['Stock'] = (float)$supplier['Stock'] - $reduceValue;
            $reduceValue = 0;
        } elseif ($supplier[$type] > 0) {
            $diff = $supplier[$type] - abs($supplier['StockRecipe']);
            if ($reduceValue >= $diff) {
                $supplier['StockRecipe'] = -(round($supplier[$type]));
                $reduceValue-=$diff;
                $supplier['DateUsageEnd'] = date('Y-m-d');
            } else {
                $supplier['StockRecipe'] -= round($reduceValue);
                $reduceValue = 0;
            }
            $supplier['StockRecipe'] = ceil($supplier['StockRecipe']);
        } else {
            return $supplier;
        }
        $reduce['value'] = Conversion::convertStockValue($reduceValue, $supplier['SupplierUnit'], $reduce['unit']);
        $supplier['StockRetailLB'] = (string)ceil((float)$supplier['StockRetailLB']);
        if (isset($this->reduceInventoryItem))
            $this->resetCostPick($this->reduceInventoryItem);
        $supplier['CostPick'] = 'yes';
        return $supplier;
    }
    private function reduceFromRetail($RetailData, &$reduceValue, $reduceUnit, $clientUnitSize = '16', $key='', $column='')
    {
    	if(!isset($RetailData[$key]['RetailUnit'])){
			return $RetailData;
		}
    	$convertTo = 'Gr';
		if($RetailData[$key]['RetailUnit'] == 'mL' || $RetailData[$key]['RetailUnit'] == 'Li' || $RetailData[$key]['RetailUnit'] == 'FlOz') {
			$convertTo = 'mL';
		}
        $reduceValueGr = Conversion::convertStockValue($reduceValue, $reduceUnit, $convertTo);

        if (!isset($RetailData[$key]['StockRetailShop'])) {
			$RetailData[$key]['StockRetailShop'] = 0;
		}
		else if ($RetailData[$key]['StockRetailShop'] == '') {
			$RetailData[$key]['StockRetailShop'] = 0;
		}

        if ($RetailData[$key]['StockRetailShop'] > 0) {
            //$stock = (float)$RetailData[$key]['StockRetailShop'];
            $stock = $RetailData[$key]['StockRetailShop']!=''?ceil($RetailData[$key]['StockRetailShop']):0;
            $stockRemain = $stock - $reduceValueGr;
            if ($stockRemain >= 0) {
            	$reduceValueGr = 0;
            	$RetailData[$key]['StockRetailShop'] = $stockRemain;

            	//Transfer bag to Recipe
            	/*if($column != 'Recipe') {
            		//transfer only required open bag
					$bagSizeGr = Conversion::convertStockValue($RetailData[$key]['RetailSize'], $RetailData[$key]['RetailUnit'], $convertTo); //1000
					$numberFullBag = (int)($stockRemain/$bagSizeGr); //5092/1000
					$fullBag = $numberFullBag*$RetailData[$key]['RetailSize'];
					$fullBagGr = Conversion::convertStockValue($fullBag, $RetailData[$key]['RetailUnit'], $convertTo);
					$openBag = $stockRemain-$fullBagGr;

					if($openBag>0) {
						$isfound = false;
						foreach($RetailData as $RetailRowKey => $RetailRow) {
							if(isset($RetailRow['StockLocation']) && $RetailRow['StockLocation'] == 'Recipe') {
								$RetailData[$RetailRowKey]['StockRetailShop'] = round((int)$RetailData[$RetailRowKey]['StockRetailShop']+$openBag);
								$isfound=true;
							}
						}
						if(!$isfound) {
							$fullBagGr = $fullBagGr+$openBag;
						}
					}
					$RetailData[$key]['StockRetailShop'] = $fullBagGr;
					//-----------------
				}*/
            } else {
                $RetailData[$key]['StockRetailShop'] = 0;
                $reduceValueGr = $stockRemain* (-1);
            }
        	$reduceValue = Conversion::convertStockValue($reduceValueGr, $convertTo, $reduceUnit);
        }
        else {
	    	$stock = (float)$RetailData[$key]['StockRetailShop'];
	    	if($stock>=$reduceValueGr){
				$stockRemain = $stock - $reduceValueGr;
            	$RetailData[$key]['StockRetailShop'] = $stockRemain;
            	$reduceValue = 0;
			}
			else {
				$stockRemain = $reduceValueGr - $stock;
				$RetailData[$key]['StockRetailShop'] = 0;
				$reduceValueGr = $stockRemain;
				$reduceValue = Conversion::convertStockValue($reduceValueGr, $convertTo, $reduceUnit);
			}
		}
        $RetailData[$key]['StockRetailShop'] = $RetailData[$key]['StockRetailShop']!=''?(string)ceil($RetailData[$key]['StockRetailShop']):0;
        return $RetailData;
    }

    public function roundStock($supplier, $clientUnitSize) {
        if (isset($supplier['StockRetailOZ'])) {
            $retailoz = $supplier['StockRetailOZ'];
            $remain = $retailoz - (int)$retailoz;
            if ($remain > 0) {
            	$StockRecipe = (int)($supplier['StockRecipe']) + ($remain);
                $supplier['StockRetailOZ'] = (string)ceil($retailoz);
                $supplier['StockRecipe'] = (string)ceil($StockRecipe);
            }
        }
        return $supplier;

    }
    private function reduceSupplier($supplier, &$reduceValue, $reduceUnit, $clientUnitSize = '16', $key)
    {
    	$convertTo = 'Gr';
		if($supplier['StockUnit'] == 'mL' || $supplier['StockUnit'] == 'Li' || $supplier['StockUnit'] == 'FlOz') {
			$convertTo = 'mL';
		}
        $reduceValueGr = Conversion::convertStockValue($reduceValue, $reduceUnit, $convertTo);

        if (!isset($supplier[$key])) $supplier[$key] = 0;
        if ($supplier[$key] > 0) {
            $stock = (float)$supplier[$key];
            $stockRemain = $stock - $reduceValueGr;
            if ($stockRemain >= 0) {
                $supplier[$key] = $stockRemain;
                $reduceValueGr = 0;
            } else {
                $supplier[$key] = 0;
                $reduceValueGr = $stockRemain* (-1);
            }
        }
        $supplier[$key] = (string)ceil($supplier[$key]);
        $reduceValue = Conversion::convertStockValue($reduceValueGr, $convertTo, $reduceUnit);
        return $supplier;
    }
	private function findInventoryIndexByProduct($inventory, $product) {
        $index = -1;
        $found = false;
        foreach ($inventory as $ind => $item) {
            if (!isset($item['Product'])) {
                continue;
            }
            if (strtolower($item['Product']) == strtolower($product)) {
                $index = $ind;
                $found = true;
                break;
            }
        }
        return $index;
    }
	public function isDateBetweenDates($date, $startDate, $endDate) {
    	return $date >= $startDate && $date <= $endDate;
	}
	private function createNewObjectFromData($date, $total_reduce_array, $total_sales_amount_array, $total_markeup_amount_array) {
		$object = array();
		$object['Date'] = $date;
		$object['AmazonSalesAmount'] = isset($total_sales_amount_array['Amazon'])?(float)$total_sales_amount_array['Amazon']:0;
		$object['EbaySalesAmount'] = isset($total_sales_amount_array['Ebay'])?(float)$total_sales_amount_array['Ebay']:0;
		$object['EtsySalesAmount'] = isset($total_sales_amount_array['Etsy'])?(float)$total_sales_amount_array['Etsy']:0;
		$object['BodiSalesAmount'] = isset($total_sales_amount_array['BODi'])?(float)$total_sales_amount_array['BODi']:0;
		$object['ShopSalesAmount'] = isset($total_sales_amount_array['BodiShop'])?(float)$total_sales_amount_array['BodiShop']:0;
		$object['EquineSalesAmount'] = isset($total_sales_amount_array['Equine'])?(float)$total_sales_amount_array['Equine']:0;

		$TotalSalesAmount = $object['AmazonSalesAmount']+$object['EbaySalesAmount']+$object['EtsySalesAmount']+$object['BodiSalesAmount']+$object['ShopSalesAmount']+$object['EquineSalesAmount'];
		$object['TotalSalesAmount'] = $TotalSalesAmount;
		$object['TotalMarkupAmount'] = array_reduce($total_markeup_amount_array, function($a, $b) {
			return $a+$b;
		}, 0);
		return $object;
	}
	private function updateObjectFromData($data, $total_reduce_array, $total_sales_amount_array, $total_markeup_amount_array) {
		$data['AmazonSalesAmount'] += isset($total_sales_amount_array['Amazon'])?(float)$total_sales_amount_array['Amazon']:0;
		$data['EbaySalesAmount'] += isset($total_sales_amount_array['Ebay'])?(float)$total_sales_amount_array['Ebay']:0;
		$data['EtsySalesAmount'] += isset($total_sales_amount_array['Etsy'])?(float)$total_sales_amount_array['Etsy']:0;
		$data['BodiSalesAmount'] += isset($total_sales_amount_array['BODi'])?(float)$total_sales_amount_array['BODi']:0;
		$data['ShopSalesAmount'] += isset($total_sales_amount_array['BodiShop'])?(float)$total_sales_amount_array['BodiShop']:0;
        	$data['EquineSalesAmount'] += isset($total_sales_amount_array['Equine'])?(float)$total_sales_amount_array['Equine']:0;

		$TotalSalesAmount = $data['AmazonSalesAmount']+$data['EbaySalesAmount']+$data['EtsySalesAmount']+$data['BodiSalesAmount']+$data['ShopSalesAmount']+$data['EquineSalesAmount'];
		$data['TotalSalesAmount'] = $TotalSalesAmount;
		$TotalMarkupAmount = array_reduce($total_markeup_amount_array, function($a, $b) {
			return $a+$b;
		}, 0);
		$data['TotalMarkupAmount'] += (float)number_format($TotalMarkupAmount, 2, '.', '');

		return $data;
	}
	private function createNewObjectFromMonthlyData($date, $total_sales_amount_array, $total_markeup_amount_array) {
		$object = array();
		$object['Date'] = $date;
		$object['AmazonSalesAmount'] = isset($total_sales_amount_array['Amazon'])?(float)$total_sales_amount_array['Amazon']:0;
		$object['EbaySalesAmount'] = isset($total_sales_amount_array['Ebay'])?(float)$total_sales_amount_array['Ebay']:0;
		$object['EtsySalesAmount'] = isset($total_sales_amount_array['Etsy'])?(float)$total_sales_amount_array['Etsy']:0;
		$object['BodiSalesAmount'] = isset($total_sales_amount_array['BODi'])?(float)$total_sales_amount_array['BODi']:0;
		$object['Bodi2businessSalesAmount'] = isset($total_sales_amount_array['Bodi2business'])?(float)$total_sales_amount_array['Bodi2business']:0;
		$object['ShopSalesAmount'] = isset($total_sales_amount_array['BodiShop'])?(float)$total_sales_amount_array['BodiShop']:0;
		$object['EquineSalesAmount'] = isset($total_sales_amount_array['Equine'])?(float)$total_sales_amount_array['Equine']:0;

		$TotalSalesAmount = $object['AmazonSalesAmount']+$object['EbaySalesAmount']+$object['EtsySalesAmount']+$object['BodiSalesAmount']+$object['Bodi2businessSalesAmount']+$object['ShopSalesAmount']+$object['EquineSalesAmount'];
		$object['TotalSalesAmount'] = $TotalSalesAmount;
		$object['TotalMarkupAmount'] = array_reduce($total_markeup_amount_array, function($a, $b) {
			return $a+$b;
		}, 0);
		return $object;
	}
	private function updateObjectFromMonthlyData($data, $total_sales_amount_array, $total_markeup_amount_array) {
		$data['AmazonSalesAmount'] += isset($total_sales_amount_array['Amazon'])?(float)$total_sales_amount_array['Amazon']:0;
		$data['EbaySalesAmount'] += isset($total_sales_amount_array['Ebay'])?(float)$total_sales_amount_array['Ebay']:0;
		$data['EtsySalesAmount'] += isset($total_sales_amount_array['Etsy'])?(float)$total_sales_amount_array['Etsy']:0;
		$data['BodiSalesAmount'] += isset($total_sales_amount_array['BODi'])?(float)$total_sales_amount_array['BODi']:0;

		if(isset($data['Bodi2businessSalesAmount']))
			$data['Bodi2businessSalesAmount'] += isset($total_sales_amount_array['Bodi2business'])?(float)$total_sales_amount_array['Bodi2business']:0;
		else
			$data['Bodi2businessSalesAmount'] = isset($total_sales_amount_array['Bodi2business'])?(float)$total_sales_amount_array['Bodi2business']:0;

		$data['ShopSalesAmount'] += isset($total_sales_amount_array['BodiShop'])?(float)$total_sales_amount_array['BodiShop']:0;
        	$data['EquineSalesAmount'] += isset($total_sales_amount_array['Equine'])?(float)$total_sales_amount_array['Equine']:0;

		$TotalSalesAmount = $data['AmazonSalesAmount']+$data['EbaySalesAmount']+$data['EtsySalesAmount']+$data['BodiSalesAmount']+$data['Bodi2businessSalesAmount']+$data['ShopSalesAmount']+$data['EquineSalesAmount'];
		$data['TotalSalesAmount'] = $TotalSalesAmount;
		$TotalMarkupAmount = array_reduce($total_markeup_amount_array, function($a, $b) {
			return $a+$b;
		}, 0);
		$data['TotalMarkupAmount'] += (float)number_format($TotalMarkupAmount, 2, '.', '');

		return $data;
	}
	private function insert($arr, $key, $value, $after = null) {
        if (isset($arr[$key])) {
            $arr[$key] = $value;
            return $arr;
        }
        $insert = array();
        $insert[$key] = $value;
        if ($after)
            $i = array_search($after,array_keys($arr))+1;
        else
            $i = 0;
        return array_slice($arr, 0, $i, true) + $insert + array_slice($arr, $i, count($arr)-1, true);
    }
	private function getDate($base = null) {
        if ($base == null)
            $base = time();
        if (date('N', $base) == 7) {
            return date('Y-m-d', $base);
        } else {
            return date('Y-m-d', strtotime('next sunday', $base));
        }
    }
    private function checkDate($date, $format = 'Y-m-d') {
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) === $date;
    }
	private function limitProductSoldWeekly($inventoryItem, $type = '') {
        $productSoldField = 'ProductSoldWeekly'.$type;
        if (is_array($inventoryItem[$productSoldField]) && count($inventoryItem[$productSoldField])) {
            $inventoryItem[$productSoldField] = array_filter(
                $inventoryItem[$productSoldField],
                function ($date) {
                    $now= new DateTime();
                    $target = new DateTime($date);
                    if (!$target) {
                        return false;
                    }
                    $diff = (int)$now->diff($target)->format('%a');
                    return $diff < 365;
                },
                ARRAY_FILTER_USE_KEY
            );
        }
        return $inventoryItem;
    }
    private function compareSupplier($s1, $s2) {
        if ($s1['DateDelivery'] == '' && $s2['DateDelivery'] != '') {
            if (empty($s1['Purchase']) && empty($s1['Ordered']))
                return -1;
            return 1;
        }
        if ($s2['DateDelivery'] == '' && $s1['DateDelivery'] != '') {
            if (empty($s2['Purchase']) && empty($s2['Ordered']))
                return 1;
            return -1;
        }
        return strcmp($s1['DateDelivery'], $s2['DateDelivery']);
    }
	public function createRetailTemplate($retail) {
        $tpl = array();
        if (isset($retail["RetailUnit"]))
            $tpl["RetailUnit"] = (string)$retail["RetailUnit"];
        else
            $tpl["RetailUnit"] = '';
        if (isset($retail["RetailSize"]))
            $tpl["RetailSize"] = (string)$retail["RetailSize"];
        else
            $tpl["RetailSize"] = '';
        if (isset($retail["StockRetail"]))
            $tpl["StockRetail"] = (string)$retail["StockRetail"];
        else
            $tpl["StockRetail"] = '';
        if (isset($retail["SKU"]))
            $tpl["SKU"] = $retail["SKU"];
        else
            $tpl["SKU"] = '';
        if (isset($retail["ShipWeight"]))
            $tpl["ShipWeight"] = (string)$retail["ShipWeight"];
        else
            $tpl["ShipWeight"] = '';
        if (isset($retail["FeePacking"]))
            $tpl["FeePacking"] = (string)$retail["FeePacking"];
        else
            $tpl["FeePacking"] = '';
        if (isset($retail["FeeShipping"]))
            $tpl["FeeShipping"] = (string)$retail["FeeShipping"];
        else
            $tpl["FeeShipping"] = '';
        if (isset($retail["UnitPrice"]))
            $tpl["UnitPrice"] = (string)$retail["UnitPrice"];
        else
            $tpl["UnitPrice"] = '';
        if (isset($retail["Markup"]))
            $tpl["Markup"] = (string)$retail["Markup"];
        else
            $tpl["Markup"] = '';
        if (isset($retail["UploadPrice"]))
            $tpl["UploadPrice"] = $retail["UploadPrice"];
        else
            $tpl["UploadPrice"] = false;

        $tpl["UploadStock"] = true;
        return $tpl;
    }

    private function resetCostPick(&$inventoryItem) {
        foreach ($inventoryItem['Suppliers'] as &$supplier) {
            if (isset($supplier['CostPick']) && $supplier['CostPick'] != 'auto')
                $supplier['CostPick'] = 'no';
        }
    }
    public function updateLog($options=null) {
		$stores = array('Bodi2business', 'Equine');
		if(isset($options['stores']) && !empty($options['stores'])){
			$stores = $options['stores'];
		}
		else if(isset($options['store']) && $options['store'] != ''){
			$stores = array($options['store']);
		}
		$customerLogTemplate = json_decode(file_get_contents("../../bodiforbusiness/retail/_log-template.json"), true);
		foreach ($stores as $store) {
			if ($store == 'BodiFranchise') {
				continue;
			}
			$customerInfoDir = "../../bodiforbusiness/{$store}/";
			$fileNameArr = preg_grep("/.*\.json$/", scandir($customerInfoDir));

			$customerLogData = array();
			if(!empty($fileNameArr)) {
				foreach($fileNameArr as $fileNameTemp) {
					$fileName = str_replace('.json','',$fileNameTemp);
					if($fileName == '_log' || $fileName == 'contact-template') {
						continue;
					}
					$customerInfo = json_decode(file_get_contents($customerInfoDir.$fileName.'.json'), true);

					//For IP Address file---
					if($store == 'Bodi4life' || $store == 'Bodi2business' || $store == 'BodiFranchise' || $store == 'Equine' || $store == 'BodiStaff' || $store == 'Bodi4life/Cart' || $store == 'Bodi2business/Cart' || $store == 'Equine' || $store == 'BodiStaff/Cart') {
						if(isset($customerInfo['CustomerID']) && ($customerInfo['CustomerID'] == '' || $customerInfo['CustomerID'] == null)) {
							if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
								foreach ($customerInfo['Order'] as $order) {
									if (isset($order['OrderDate']) && $order['OrderDate'] != '') {
										$OrderDate = $order['OrderDate'];
										$shortOrderDate = date('Y-m-d', strtotime($OrderDate));
										if($shortOrderDate=='') {
											continue;
										}

										$orderIndex = '999';
										if(!empty($customerLogData)) {
											foreach($customerLogData as $customerLogKey => $customerLogRow){
												if($customerLogRow['CustomerID'] == $shortOrderDate) {
													$orderIndex = $customerLogKey;
													break;
												}
											}
										}
										if($orderIndex != '999') {
											if($OrderDate!='')
												$customerLogData[$orderIndex]['OrderStatus'][$OrderDate] = $fileName;
										}
										else {
											$tpl = $customerLogTemplate;
											$tpl['CustomerID'] = $shortOrderDate;
											$tpl['CustomerStatus'] = 'Good';
											$tpl['OrderStatus'] = array();
											if($OrderDate!='')
												$tpl['OrderStatus'][$OrderDate] = $fileName;
											$customerLogData[] = $tpl;
										}


									}
								}
							}

						}
						else {
							//For Customer file---
							$CustomerID = $fileName;

							$tpl = $customerLogTemplate;
							$tpl['CustomerID'] = $CustomerID;
							$tpl['CustomerName'] = isset($customerInfo['CustomerName']) ? $customerInfo['CustomerName'] : '';
							$tpl['Email'] = isset($customerInfo['Email']) ? $customerInfo['Email'] : '';
							$tpl['Phone'] = isset($customerInfo['Phone']) ? $customerInfo['Phone'] : '';
							$tpl['CustomerStatus'] = 'Good';
							$tpl['OrderStatus'] = array();
							if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
								foreach ($customerInfo['Order'] as $order) {
									if (isset($order['OrderDate']) && $order['OrderDate'] != '') {
										$tpl['OrderStatus'][$order['OrderDate']] = $order['OrderStatus'];
									}
								}
							}
							$customerLogData[] = $tpl;
						}
					}
					else if($store == 'BodiShop' || $store == 'Ebay' || $store == 'Etsy' || $store == 'Amazon') {
						$CustomerID = $fileName;
						if(!empty($customerInfo)) {
							$tpl = $customerLogTemplate;
							$tpl['CustomerID'] = $CustomerID;
							$tpl['CustomerStatus'] = 'Good';
							$tpl['OrderStatus'] = array();
							foreach ($customerInfo as $customer) {
								if(isset($customer['Order']) && !empty($customer['Order'])) {
									foreach ($customer['Order'] as $order) {
										if (!empty($order['OrderStatus'])) {
											$tpl['OrderStatus'][$order['OrderDate']] = $order['OrderStatus'];
										}
									}
								}
								$isfound = false;
								if(!empty($customerLogData)){
									foreach($customerLogData as $customerLogDataKey => $customerLogDataRow) {
										if($customerLogDataRow['CustomerID'] == $CustomerID) {
											$isfound = true;
											$tpl['OrderStatus'] = array_merge($customerLogDataRow['OrderStatus'], $tpl['OrderStatus']);
											$customerLogData[$customerLogDataKey] = $tpl;
											break;
										}
									}
								}
								if(!$isfound){
									$customerLogData[] = $tpl;
								}
							}

						}
					}
				}
			}
			if ($store !== 'BodiFranchise') {
				$this->inventory->saveJson($customerInfoDir.'_log.json', $customerLogData);
			}


			//For read IP address file---
			if($store == 'Bodi4life' || $store == 'Bodi2business' || $store == 'Equine') {
				$customerLogData = array();
				$customerInfoDir = "../../bodiforbusiness/{$store}/Cart/";
				$fileNameArr = preg_grep("/.*\.json$/", scandir($customerInfoDir));
				if(!empty($fileNameArr)) {
					foreach($fileNameArr as $fileNameTemp) {
						$fileName = str_replace('.json','',$fileNameTemp);
						if($fileName == '_log') {
							continue;
						}
						$customerInfo = json_decode(file_get_contents($customerInfoDir.$fileName.'.json'), true);

						$OrderDate = '';
						$shortOrderDate = '';
						if(isset($customerInfo['Order']) && !empty($customerInfo['Order'])) {
							foreach ($customerInfo['Order'] as $order) {
								if (isset($order['OrderDate']) && $order['OrderDate'] != '') {
									$OrderDate = $order['OrderDate'];
								}
								else {
									$lastModifiedOn = filemtime('../../bodiforbusiness/'.$store.'/Cart/'.$fileName.'.json');
									$OrderDate = date('Y-m-d H:i:s', $lastModifiedOn);
								}
								if($OrderDate=='') {
									continue;
								}
								$shortOrderDate = date('Y-m-d', strtotime($OrderDate));
							}
						}
						if($shortOrderDate=='') {
							continue;
						}
						$orderIndex = '';
						if(!empty($customerLogData)) {
							foreach($customerLogData as $customerLogKey => $customerLogRow){
								if($customerLogRow['CustomerID'] == $shortOrderDate) {
									$orderIndex = $customerLogKey;
									break;
								}
							}
						}

						if($orderIndex != '') {
							$customerLogData[$orderIndex]['OrderStatus'][$OrderDate] = $fileName;
						}
						else {
							$tpl = $customerLogTemplate;
							$tpl['CustomerID'] = $shortOrderDate;
							$tpl['CustomerName'] = '';
							$tpl['Email'] = '';
							$tpl['Phone'] = '';
							$tpl['CustomerStatus'] = 'Good';
							$tpl['OrderStatus'] = array();
							$tpl['OrderStatus'][$OrderDate] = $fileName;
							$customerLogData[] = $tpl;
						}
					}
				}
				$this->inventory->saveJson($customerInfoDir.'_log.json', $customerLogData);
			}
		}
	}
}
if (!function_exists('pr')) {
	function pr($var) {
		$template = php_sapi_name() !== 'cli' ? '<pre>%s</pre>' : "\n%s\n";
		printf($template, print_r($var, true));
	}
}