<?php
namespace App\Http\Controllers\Ecomtoacc\Ecomtodb\Amazon;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Helpers\Helper;
use App\Models\Master\Sellers;
use App\Models\Amazon\Azorder;
use App\Models\Amazon\Azorderlineitem;
use App\Models\Amazon\Azlastsync;
use App\Models\Amazon\Azsellers;
use App\Models\Amazon\Useractionlog;
use App\Models\Amazon\Azfeature;
use View;
use Log;
use Auth;
use DateTime;
use DateTimeZone;
use DB;
use redirect;

/*
ApiController contails all spapi api calls.
*/
class OrderController extends Controller
{       
    private $randomValue = 0;

    public function getOrdersFromAmazon(Request $request,$para = ''){

        set_time_limit(0);        

        $sellerid = Helper::encryptor('decrypt',$request->get('sellerid'));
        $sellerid = 15;
        $startDate = $request->get('startDate');
        $endDate = $request->get('endDate');
        $backdated = $request->get('backdated');

        $seller = Azsellers::find($sellerid);
        $connection_name = '';
        if(strpos($seller->module,'tl') !== false){
            $connection_name = env('DB_DATABASE_TALLY_MASTER').'.tally_connections';
        } 
            
        if($seller->sync_type == 'Summary'){
            if(strpos($seller->module,'tl') !== false)
            $setting_name = env('DB_DATABASE').'.tally_summary_setting';
        }
        else{
            if(strpos($seller->module,'tl') !== false)
            $setting_name = 'tally_sync_settings';
        }
        
        $sellerDetailsBunch = Azsellers::getSellerDetailsSp($sellerid,$connection_name,$setting_name,$seller->module);
        if(!empty($sellerDetailsBunch)){
            $data = true;
            foreach($sellerDetailsBunch as $sellerKey => $sellerDetails){
                
                $createdAfter = $this->getLastSyncDate($sellerDetails,$startDate);                 
                $maxResults = ($para == 'manualsync') ? config('ecomtoacc.amazon.manualSyncFetchOrderLimit') : '';                
                $fulfillmentChannels = ($sellerDetails['fulfillment_channel_sync'] != 'Both') ? $sellerDetails['fulfillment_channel_sync'] : '';             
                $orders = app('App\Http\Controllers\Ecomtoacc\Ecomtodb\Amazon\ApiController')->getAmazonOrders($sellerDetails, $createdAfter, $maxResults, $fulfillmentChannels, $endDate);                    
                
                if(!empty($orders)){                           
                    $data = $this->handleOrdersForDB($orders,$sellerDetails,$maxResults,$backdated);
                } else {
                    return false;
                }
            }

            $request1 = new \Illuminate\Http\Request();
            $request1->replace(['sellerid' => Helper::encryptor('encrypt',$sellerid)]);
            $lineItems = $this->getLineItemsOfItemSp($request1,'return');  

            if($para == '')
                echo "Success";
            else
                return $data;
        }       
    }

    public function updateOrdersFromAmazonSp(Request $request,$para = ''){
        set_time_limit(0);
        $sellerid = Helper::encryptor('decrypt',$request->get('sellerid')); 
        $sellerid=15;
        $orderId = !empty($request->get('order_id')) ? $request->get('order_id') : '';
        //$orderId = '403-0611091-0149161';
        $startDate = $request->get('startDate');
        $endDate = $request->get('endDate');
        
        //Log::info('SP: Update Order AZ to DB starts for seller id = '.$sellerid);

        $seller = Azsellers::find($sellerid);

        if($seller->sync_type == 'Summary'){
            $connection_name = '';
            if(strpos($seller->module,'tl') !== false){
                $connection_name = env('DB_DATABASE_TALLY_MASTER').'.tally_connections';
            } 

            if($seller->sync_type == 'Summary'){
                if(strpos($seller->module,'tl') !== false)
                $setting_name = env('DB_DATABASE').'.tally_summary_setting';
            }
            else{
                if(strpos($seller->module,'tl') !== false)
                $setting_name = 'tally_sync_settings';
            }
            

            $sellerDetailsBunch = Azsellers::getSellerDetailsSp($sellerid,$connection_name,$setting_name,$seller->module);        
            if(!empty($sellerDetailsBunch)){
                $data = true;
                foreach($sellerDetailsBunch as $sellerKey => $sellerDetails){  
                    if($orderId != ''){  // Get Data for single order
                        $orders = app('App\Http\Controllers\Ecomtoacc\Ecomtodb\Amazon\ApiController')->getSingleOrder($sellerDetails, $orderId);
                        
                    } else {             
                        //Log::info('SP: Update Order AZ to DB get data from api start for seller id = '.$sellerid);
                        
                        $updatedAfter = $this->getLastSyncDate($sellerDetails,$startDate,'update');                                                 
                        $fulfillmentChannels = ($sellerDetails['fulfillment_channel_sync'] != 'Both') ? $sellerDetails['fulfillment_channel_sync'] : '';                
                        $orders = app('App\Http\Controllers\Ecomtoacc\Ecomtodb\Amazon\ApiController')->getUpdatedAmazonOrders($sellerDetails, $updatedAfter, '', $fulfillmentChannels, $endDate);
                        //Helper::pr($orders,1);
                        //Log::info('SP: Update Order AZ to DB get data from api end for seller id = '.$sellerid);  
                    }

                    if(!empty($orders)){                           
                        $data = $this->handleOrdersForDB($orders,$sellerDetails,'','','update',$orderId);
                    } else {
                        return false;
                    }
                } 

                $request1 = new \Illuminate\Http\Request();
                $request1->replace(['sellerid' => Helper::encryptor('encrypt',$sellerid)]);
                $lineItems = $this->getLineItemsOfItemSp($request1,'return');
                
                if($para == '')
                    echo "Success";
                else
                    return $data;
            }       
        }
        
    }

    private function handleOrdersForDB($orders,$sellerDetails,$limit = '',$backdated = '', $type = '', $order_id = ''){        

        $LastPurchaseDate = '';  

        if(!empty($orders)){      
            if(empty($order_id))      
                $orderData = $orders->getOrders();
            else
                $orderData[0] = $orders; // For single order fetch

            if(!empty($orderData)){ 
               // Log::info('SP: Get Orders First Time : '.$sellerDetails['seller_id']);

                foreach ($orderData as $key => $value) {
                    if(strtotime($value['purchase_date']) >= strtotime($sellerDetails['sync_start_date']) || !empty($backdated) || !empty($order_id)){
                        $LastPurchaseDate = $this->storeOrdersInDB($sellerDetails,$value, $LastPurchaseDate,$type);                  
                    }
                }
            }    

            if($LastPurchaseDate != '' && $backdated == '' && $order_id == ''){
                $this->setLastSync($sellerDetails,$LastPurchaseDate,'Order',$type);    
            }    
            if(!empty($backdated))
                sleep(60);
            else
                return true; // Added condition temporary for skip next token logic

            if($limit == '' && $order_id == ''){ // Condition is for manual sync
                $nextToken = $orders->getNextToken();
                unset($orders); unset($orderData);
                if(!empty($nextToken)){
                    for ($i=1; $i < config('app.maxPagePerCall') ; $i++) {
                        if($nextToken != ''){
                           // Log::info('SP: Get Orders with nexttoken start for seller id = '.$sellerDetails['seller_id']);  
                                                        
                            $orders = app('App\Http\Controllers\Ecomtoacc\Ecomtodb\Amazon\ApiController')->getAmazonOrdersByNextToken($sellerDetails, $nextToken);                            
                            if(!empty($orders)){
                                $orderData = $orders->getOrders();
                                if(!empty($orderData)){
                                    //Log::info('SP: Get Orders with nexttoken: '.$sellerDetails['seller_id']);  

                                    foreach ($orderData as $key => $value) {
                                        if(strtotime($value['purchase_date']) >= strtotime($sellerDetails['sync_start_date']) || !empty($backdated)){
                                            $LastPurchaseDate = $this->storeOrdersInDB($sellerDetails,$value,$LastPurchaseDate,$type);                                       
                                        }
                                        $nextTokenData = $orders->getNextToken();
                                        $nextToken = !empty($nextTokenData) ? $nextTokenData : '';                                    
                                    }
                                    unset($orders); unset($orderData);
                                }
                            } else {
                                return false;
                            }
                        } else {
                            return false;
                        }
                        
                        if($LastPurchaseDate != '' && $backdated == ''){                               
                            $this->setLastSync($sellerDetails,$LastPurchaseDate,'Order',$type);    
                        } 
                        if(!empty($backdated))
                            sleep(60);
                    }   

                }
            }              
            return true;
        }
        return false;
    }

    public function storeOrdersInDB($sellerDetails,$value,$LastPurchaseDate,$type){  
        
        $orders = [];
        $orders['AmazonOrderId'] = $value['amazon_order_id'];            
        $orders['SellerOrderId'] = $value['seller_order_id'];            
        $orders['PurchaseDate'] = $value['purchase_date'];
        $orders['LastUpdateDate'] = $value['last_update_date'];
        $orders['OrderStatus'] = $value['order_status'];
        $orders['FulfillmentChannel'] = $value['fulfillment_channel'];
        $orders['SalesChannel'] = $value['sales_channel'];            
        $orders['ShipServiceLevel'] = $value['ship_service_level'];
        if(!empty($value['order_total'])){
            $orders['OrderTotal'] = [
                'Amount' => $value['order_total']['amount'],
                'CurrencyCode' => $value['order_total']['currency_code'],
            ];                                    
        }               
        $orders['NumberOfItemsShipped'] = $value['number_of_items_shipped'];
        $orders['NumberOfItemsUnshipped'] = $value['number_of_items_unshipped'];            
        $orders['PaymentMethod'] = $value['payment_method'];
        if(!empty($value['payment_method_details'])){
            $orders['PaymentMethodDetails']['PaymentMethodDetail'] = '';                                    
        }            
        $orders['MarketplaceId'] = $value['marketplace_id'];
        $orders['ShipmentServiceLevelCategory'] = $value['shipment_service_level_category'];            
        $orders['OrderType'] = $value['order_type'];
        $orders['EarliestShipDate'] = $value['earliest_ship_date'];
        $orders['LatestShipDate'] = $value['latest_ship_date'];
        $orders['EarliestDeliveryDate'] = $value['earliest_delivery_date'];
        $orders['LatestDeliveryDate'] = $value['latest_delivery_date'];
        $orders['IsBusinessOrder'] = $value['is_business_order'];
        $orders['IsPrime'] = $value['is_prime'];
        $orders['IsPremiumOrder'] = $value['is_premium_order'];            
        $orders['IsReplacementOrder'] = $value['is_replacement_order'];
        /*$orders[''] = $value['payment_execution_detail'];
        $orders[''] = $value['easy_ship_shipment_status'];
        $orders[''] = $value['cba_displayable_shipping_label'];
        $orders[''] = $value['is_global_express_enabled'];
        $orders[''] = $value['replaced_order_id'];
        $orders[''] = $value['order_channel'];
        $orders[''] = $value['promise_response_due_date'];
        $orders[''] = $value['is_estimated_ship_date_set'];
        $orders[''] = $value['is_sold_by_ab'];
        $orders[''] = $value['assigned_ship_from_location_address'];
        $orders[''] = $value['fulfillment_instruction'];*/
        //Helper::pr($orders,1);
        
        /*usleep(500000);
        $buyerDetails = app('App\Http\Controllers\Ecomtoacc\Ecomtodb\Amazon\ApiController')->getOrderBuyerDetails($sellerDetails, $value['amazon_order_id']);
        if(!empty($buyerDetails)){
            $orders['BuyerName'] = $buyerDetails->getBuyerName();
            $orders['BuyerEmail'] = $buyerDetails->getBuyerEmail();
            $orders['BuyerCountry'] = $buyerDetails->getBuyerCounty();
            $orders['BuyerTaxInfo'] = $buyerDetails->getBuyerTaxInfo();
        }*/
        
        //usleep(500000);
        sleep(1);
        $addressData = app('App\Http\Controllers\Ecomtoacc\Ecomtodb\Amazon\ApiController')->getOrderAddress($sellerDetails, $value['amazon_order_id']);
        $addressResponse = $this->convertShippingArray($addressData);
        
        if(!empty($addressResponse)){
            $orders['ShippingAddress'] = $addressResponse;
        }   
        
        $dbOrderObj = $this->storeOrderDataInDb($sellerDetails,$orders);
        
        if($type == 'update'){
            if(strtotime($value['last_update_date']) > strtotime($LastPurchaseDate))
                $LastPurchaseDate = $value['last_update_date'];
        } else {
            if(strtotime($value['purchase_date']) > strtotime($LastPurchaseDate))
                $LastPurchaseDate = $value['purchase_date'];
        }
        
        if($type == 'update' && !empty($dbOrderObj)){ 
            Azorder::where('id',$dbOrderObj->id)->update(array('line_items'=>'No'));    
        }            
            
        return $LastPurchaseDate;
    }

    public function getLineItemsOfItemSp(Request $request,$para = ''){ 

        $sellerid = Helper::encryptor('decrypt',$request->get('sellerid'));
        $sellerid= 15;
        $seller = Azsellers::find($sellerid);
        if($seller->sync_type == 'Summary'){
            
            $connection_name = '';
            if(strpos($seller->module,'tl') !== false){
                $connection_name = env('DB_DATABASE_TALLY_MASTER').'.tally_connections';
            } 

            if($seller->sync_type == 'Summary'){
                if(strpos($seller->module,'tl') !== false)
                $setting_name = env('DB_DATABASE').'.tally_summary_setting';
            }
            else{
                if(strpos($seller->module,'tl') !== false)
                $setting_name = 'tally_sync_settings';
            }
            
            $sellerDetailsBunch = Azsellers::getSellerWithMarketplace($sellerid,$connection_name,$setting_name,$seller->module);

            if(!empty($sellerDetailsBunch)){
                foreach($sellerDetailsBunch as $sellerKey => $sellerDetails){
                    $dbOrders = Azorder::where('line_items','No')->where('seller_id',$sellerDetails["seller_id"])->where('MarketplaceId',$sellerDetails['az_marketplace_id'])->limit(15)->get()->toArray();
                    
                    if(!empty($dbOrders)){                    
                        foreach ($dbOrders as $key => $order) {
                            Log::info('SP: Get Orders Lineitems start for seller id = '.$sellerDetails['seller_id']);  
                            usleep(50000);
                            $ordersLineitems = app('App\Http\Controllers\Ecomtoacc\Ecomtodb\Amazon\ApiController')->getOrdersLineItems($sellerDetails, $order['AmazonOrderId']);                                                
                            
                            $dbOrderLienitemObj = false;
                            if(!empty($ordersLineitems)){                                
                                Log::info('Line Items for - '.$order['AmazonOrderId']);
                                $allDbLineItems = Azorderlineitem::AzordergetLineItemsByOrder($sellerDetails['seller_id'],$order['AmazonOrderId'], $order['id']);
                                
                                $itemIds = array();
                                if(!empty($allDbLineItems)){
                                    $itemIds = array_column($allDbLineItems, 'OrderItemId');
                                }      
                                $lineItems = $ordersLineitems->getOrderItems();
                                          
                                if(!empty($lineItems)){
                                    foreach ($lineItems as $key => $value) { 
                                        $dbOrderLienitemObj = $this->saveLineItems($ordersLineitems->getAmazonOrderId(),$order,$value,$sellerDetails);
                                        unset($itemIds[array_search($value['order_item_id'], $itemIds)]);   
                                    }   
                                }else{                                    
                                    $actionlog=array();
                                    $actionlog=array(
                                              'seller_id'=>$sellerDetails["seller_id"],
                                              'error_code'=>'',
                                                'error_msg'=>'Lineitem Fetch Fail',
                                              'uniqueId'=>'',
                                              'data'=>array("action"=>"getLineItemsOfItemSp","data"=>json_encode($ordersLineitems))
                                              );
                                    app('App\Http\Controllers\Amazon\Azsellers\AzxosellersController')->AmazonActionlog($actionlog);         
                                                                                                                
                                }

                                if(!empty($itemIds)){
                                    foreach ($itemIds as $k => $v) {
                                        Azorderlineitem::where('OrderItemId',$v)->where('seller_id',$sellerid)->update(array('deleted_at'=>date('Y-m-d H:i:s')));
                                    }
                                }
                                
                                if($dbOrderLienitemObj){                                    
                                    Azorder::where('id',$order['id'])->update(array('line_items'=>'Yes'));
                                }                                
                            }                                                                        
                        }                        
                    }                
                }
                if($para != ''){
                    return true;
                }else{
                    echo 'success';
                    exit;
                }
            }
        }
        
    }

    public function saveLineItems($amazon_order_id,$order,$lineItem,$sellerDetails){
        
        $lineItemArr = [];
        $lineItemArr['OrderItemId'] = $lineItem['order_item_id'];
        $lineItemArr['QuantityOrdered'] = $lineItem['quantity_ordered'];
        $lineItemArr['Title'] = $lineItem['title'];
        $lineItemArr['SellerSKU'] = $lineItem['seller_sku'];
        $lineItemArr['ASIN'] = $lineItem['asin'];
        if(!empty($lineItem['item_price'])){
            $lineItemArr['ItemPrice'] = [
                'CurrencyCode' => $lineItem['item_price']['currency_code'],
                'Amount' => $lineItem['item_price']['amount']
            ];                
        }
        if(!empty($lineItem['item_tax'])){
            $lineItemArr['ItemTax'] = [
                'CurrencyCode' => $lineItem['item_tax']['currency_code'],
                'Amount' => $lineItem['item_tax']['amount']
            ];                
        }
        if(!empty($lineItem['promotion_discount'])){
            $lineItemArr['PromotionDiscount'] = [
                'CurrencyCode' => $lineItem['promotion_discount']['currency_code'],
                'Amount' => $lineItem['promotion_discount']['amount']
            ];                
        }
        if(!empty($lineItem['promotion_discount_tax'])){
            $lineItemArr['PromotionDiscountTax'] = [
                'CurrencyCode' => $lineItem['promotion_discount_tax']['currency_code'],
                'Amount' => $lineItem['promotion_discount_tax']['amount']
            ];                
        }
        //$lineItemArr['PromotionIds'] = $lineItem['promotion_ids'];
        if(!empty($lineItem['shipping_price'])){
            $lineItemArr['ShippingPrice']['Amount'] = $lineItem['shipping_price']['amount'];
        }
        if(!empty($lineItem['shipping_tax'])){
            $lineItemArr['ShippingTax']['Amount'] = $lineItem['shipping_tax']['amount'];
        }
        if(!empty($lineItem['shipping_discount'])){
            $lineItemArr['ShippingDiscount']['Amount'] = $lineItem['shipping_discount']['amount'];
        }
        if(!empty($lineItem['shipping_discount_tax'])){
            $lineItemArr['ShippingDiscountTax']['Amount'] = $lineItem['shipping_discount_tax']['amount'];
        }

        $lineItemArr['QuantityShipped'] = $lineItem['quantity_shipped'];
        if(!empty($lineItem['product_info'])){
            $lineItemArr['ProductInfo']['NumberOfItems'] = $lineItem['product_info']['number_of_items'];    
        }        
        $lineItemArr['PointsGranted'] = $lineItem['points_granted'];
        $lineItemArr['CODFeeAmount'] = $lineItem['cod_fee'];
        $lineItemArr['CODFeeDiscountAmount'] = $lineItem['cod_fee_discount'];
        $lineItemArr['IsGift'] = $lineItem['is_gift'];
        $lineItemArr['ConditionNote'] = $lineItem['condition_note'];
        $lineItemArr['ConditionId'] = $lineItem['condition_id'];
        $lineItemArr['ConditionSubtypeId'] = $lineItem['condition_subtype_id'];
        $lineItemArr['ScheduledDeliveryStartDate'] = $lineItem['scheduled_delivery_start_date'];
        $lineItemArr['ScheduledDeliveryEndDate'] = $lineItem['scheduled_delivery_end_date'];
        $lineItemArr['PriceDesignation'] = $lineItem['price_designation'];
        $lineItemArr['TaxCollection'] = $lineItem['tax_collection'];
        $lineItemArr['IsTransparency'] = $lineItem['is_transparency'];
        //$lineItem[''] = $lineItem['serial_number_required'];
        //$lineItem[''] = $lineItem['ioss_number'];
       // $lineItem[''] = $lineItem['deemed_reseller_category'];
        //Helper::pr($lineItemArr,1);
        return $this->storeOrderLineItemsDataInDb($amazon_order_id,$order,$lineItemArr,$sellerDetails);
    }

    public function convertShippingArray($addressResponse){
        $itemArray = [];
        if(!empty($addressResponse)){                        
            $itemArray['City'] = $addressResponse['city'];
            $itemArray['PostalCode'] = $addressResponse['postal_code'];
            $itemArray['isAddressSharingConfidential'] = false;
            $itemArray['StateOrRegion'] = $addressResponse['state_or_region'];
            $itemArray['CountryCode'] = $addressResponse['country_code'];
            $itemArray['Name'] = $addressResponse['name'];
            $itemArray['AddressLine1'] = $addressResponse['address_line1'];            
            $itemArray['AddressLine2'] = $addressResponse['address_line2'];            
            $itemArray['AddressLine3'] = $addressResponse['address_line3'];            
            $itemArray['County'] = $addressResponse['county'];            
            $itemArray['District'] = $addressResponse['district'];            
            $itemArray['Municipality'] = $addressResponse['municipality'];            
            $itemArray['Phone'] = $addressResponse['phone'];            
            $itemArray['AddressType'] = $addressResponse['address_type'];            
        }
        return $itemArray;
    }

    public function getLastSyncDate($sellerDetails,$startDate = '',$type = ''){        
        $lastSyncData = Azlastsync::getLastSync($sellerDetails['seller_id'],'Order',$sellerDetails['region']);                
        if($startDate != ''){
            $CreatedAfter = date("Y-m-d\TH:i:s\Z", strtotime($startDate));
        }else if($lastSyncData){
            if($type == 'update'){
                $CreatedAfter = !empty($lastSyncData['LastUpdateDate']) ? $lastSyncData['LastUpdateDate'] : $sellerDetails['sync_start_date'];                
                $CreatedAfter = date("Y-m-d\TH:i:s\Z", strtotime($CreatedAfter));
            } else {                
                $CreatedAfter = date("Y-m-d\TH:i:s\Z", strtotime($lastSyncData['LastPurchaseDate']));
            }
        }else{
            $CreatedAfter = date("Y-m-d\TH:i:s\Z", strtotime($sellerDetails['sync_start_date']));
        }        
        return $CreatedAfter;
    }

    public function setLastSync($sellerDetails,$LastPurchaseDate,$sync_type = 'Order', $type = ''){        
        $lastSyncData = Azlastsync::getLastSync($sellerDetails['seller_id'],$sync_type,$sellerDetails['region']);  
        
        if($lastSyncData){   
            if($type == 'update') {                     
                $lastSyncData->LastUpdateDate = date('Y-m-d H:i:s',strtotime('-1 second',strtotime($LastPurchaseDate)));
                $lastSyncData->save();
            } else {
                $lastSyncData->LastPurchaseDate = date('Y-m-d H:i:s',strtotime('-1 second',strtotime($LastPurchaseDate)));
                $lastSyncData->save();
            }
        }else{
            $lastSyncObj = new Azlastsync();
            $lastSyncObj->seller_id = $sellerDetails['seller_id'];
            $lastSyncObj->seller_marketplace_id = $sellerDetails['region'];
            $lastSyncObj->LastPurchaseDate = date('Y-m-d H:i:s',strtotime('-1 second',strtotime($LastPurchaseDate)));
            $lastSyncObj->LastUpdateDate = date('Y-m-d H:i:s',strtotime('-1 second',strtotime($LastPurchaseDate)));
            $lastSyncObj->sync_type = $sync_type;
            $lastSyncObj->save();
        }
                
        return true;    
    }


    /* Convert Orders into Db format and store it in DB
        MP - 17/10/2019
    */
    public function storeOrderDataInDb($sellerDetails,$orderData){    

        $orderData = $this->xml2array($orderData);
        
        $checkDuplicate = Azorder::fetchOrderSingleData("AmazonOrderId",$orderData['AmazonOrderId'],$sellerDetails["seller_id"]);
        $timezone = isset(config('ecomtoacc.amazon.AWS_MARKETPLACE_ID_TIMEZONE')[$orderData['MarketplaceId']]) ? config('ecomtoacc.amazon.AWS_MARKETPLACE_ID_TIMEZONE')[$orderData['MarketplaceId']] : 'UTC';        
        if(empty($checkDuplicate)){
            $orderStoreObj = new Azorder();
            $orderStoreObj->seller_id = $sellerDetails['seller_id'];
            $orderStoreObj->AmazonOrderId = $orderData['AmazonOrderId'];

            if(!empty($orderData['PurchaseDate']))
            $orderStoreObj->PurchaseDate = (new DateTime($orderData['PurchaseDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['LastUpdateDate']))
            $orderStoreObj->LastUpdateDate = (new DateTime($orderData['LastUpdateDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['OrderType']))
            $orderStoreObj->OrderType = $orderData['OrderType'];

            if(!empty($orderData['OrderStatus']))
            $orderStoreObj->OrderStatus = $orderData['OrderStatus'];

            if(!empty($orderData['OrderTotal']))
            $orderStoreObj->Amount = $orderData['OrderTotal']['Amount'];

            if(!empty($orderData['OrderTotal']))
            $orderStoreObj->CurrencyCode = $orderData['OrderTotal']['CurrencyCode'];

            if(!empty($orderData['BuyerName']))
            $orderStoreObj->BuyerName = $orderData['BuyerName'];

            if(!empty($orderData['BuyerEmail']))
            $orderStoreObj->BuyerEmail = $orderData['BuyerEmail'];

            if(isset($orderData['BuyerCountry']) && !empty($orderData['BuyerCountry']))
            $orderStoreObj->BuyerCountry = $orderData['BuyerCountry'];

            if(!empty($orderData['BuyerTaxInfo']))
            $orderStoreObj->BuyerTaxInfo = json_encode($orderData['BuyerTaxInfo']);

            if(!empty($orderData['ShippingAddress']))
            $orderStoreObj->ShippingAddress = json_encode($orderData['ShippingAddress']);

            if(!empty($orderData['PaymentMethod']))
            $orderStoreObj->PaymentMethod = $orderData['PaymentMethod'];

            if(!empty($orderData['PaymentMethodDetails'])){
                if(is_array($orderData['PaymentMethodDetails']['PaymentMethodDetail']))
                $orderStoreObj->PaymentMethodDetails = json_encode($orderData['PaymentMethodDetails']['PaymentMethodDetail']);
                else
                $orderStoreObj->PaymentMethodDetails = $orderData['PaymentMethodDetails']['PaymentMethodDetail'];
            }

            if(!empty($orderData['NumberOfItemsUnshipped']))
            $orderStoreObj->NumberOfItemsUnshipped = $orderData['NumberOfItemsUnshipped'];

            if(!empty($orderData['LatestShipDate']))
            $orderStoreObj->LatestShipDate = (new DateTime($orderData['LatestShipDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['EarliestShipDate']))
            $orderStoreObj->EarliestShipDate = (new DateTime($orderData['EarliestShipDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['LatestDeliveryDate']))
            $orderStoreObj->LatestDeliveryDate = (new DateTime($orderData['LatestDeliveryDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['EarliestDeliveryDate']))
            $orderStoreObj->EarliestDeliveryDate = (new DateTime($orderData['EarliestDeliveryDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['PurchaseOrderNumber']))
            $orderStoreObj->PurchaseOrderNumber = $orderData['PurchaseOrderNumber'];

            if(!empty($orderData['NumberOfItemsShipped']))
            $orderStoreObj->NumberOfItemsShipped = $orderData['NumberOfItemsShipped'];

            if(!empty($orderData['IsReplacementOrder']))
            $orderStoreObj->IsReplacementOrder = $orderData['IsReplacementOrder'];

            if(!empty($orderData['IsBusinessOrder']))
            $orderStoreObj->IsBusinessOrder = $orderData['IsBusinessOrder'];

            if(!empty($orderData['IsPremiumOrder']))
            $orderStoreObj->IsPremiumOrder = $orderData['IsPremiumOrder'];

            if(!empty($orderData['ShipServiceLevel']))
            $orderStoreObj->ShipServiceLevel = $orderData['ShipServiceLevel'];

            if(!empty($orderData['SalesChannel']))
            $orderStoreObj->SalesChannel = $orderData['SalesChannel'];

            if(!empty($orderData['ShippedByAmazonTFM']))
            $orderStoreObj->ShippedByAmazonTFM = $orderData['ShippedByAmazonTFM'];

            if(!empty($orderData['MarketplaceId']))
            $orderStoreObj->MarketplaceId = $orderData['MarketplaceId'];

            if(!empty($orderData['FulfillmentChannel']))
            $orderStoreObj->FulfillmentChannel = $orderData['FulfillmentChannel'];

            if(!empty($orderData['IsPrime']))
            $orderStoreObj->IsPrime = $orderData['IsPrime'];

            if(!empty($orderData['ShipmentServiceLevelCategory']))
            $orderStoreObj->ShipmentServiceLevelCategory = $orderData['ShipmentServiceLevelCategory'];

            if(!empty($orderData['SellerOrderId']))
            $orderStoreObj->SellerOrderId = $orderData['SellerOrderId'];

            /*if(!empty($orderData['OrderStatus']) && $orderData['OrderStatus'] == 'Canceled')
                $orderStoreObj->sync_status_flg = 'SNR';    
            
            if($orderStoreObj->Amount == NULL)
                $orderStoreObj->sync_status_flg = 'SNR';*/
            
            if(empty($orderStoreObj->xo_id)){
                $snr_status = $this->checkSNRStatus($sellerDetails['seller_id'], $orderData);
                if($snr_status == true){
                    $orderStoreObj->sync_status_flg = 'SNR';       
                } else if($orderStoreObj->sync_status_flg == 'SNR') {
                    $orderStoreObj->sync_status_flg = 'New';                                
                }
            }

            $orderStoreObj->save();
            
            return $orderStoreObj;

        }else{  

            if(!empty($orderData['PurchaseDate']))
            $checkDuplicate->PurchaseDate = (new DateTime($orderData['PurchaseDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['LastUpdateDate']))
            $checkDuplicate->LastUpdateDate = (new DateTime($orderData['LastUpdateDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['OrderType']))
            $checkDuplicate->OrderType = $orderData['OrderType'];

            if(!empty($orderData['OrderStatus']))
            $checkDuplicate->OrderStatus = $orderData['OrderStatus'];

            if(!empty($orderData['OrderTotal']))
            $checkDuplicate->Amount = $orderData['OrderTotal']['Amount'];

            if(!empty($orderData['OrderTotal']))
            $checkDuplicate->CurrencyCode = $orderData['OrderTotal']['CurrencyCode'];

            if(!empty($orderData['BuyerName']))
            $checkDuplicate->BuyerName = $orderData['BuyerName'];

            if(!empty($orderData['BuyerEmail']))
            $checkDuplicate->BuyerEmail = $orderData['BuyerEmail'];

            if(!empty($orderData['BuyerTaxInfo']))
            $checkDuplicate->BuyerTaxInfo = json_encode($orderData['BuyerTaxInfo']);

            if(!empty($orderData['ShippingAddress']))
            $checkDuplicate->ShippingAddress = json_encode($orderData['ShippingAddress']);

            if(!empty($orderData['PaymentMethod']))
            $checkDuplicate->PaymentMethod = $orderData['PaymentMethod'];

            if(!empty($orderData['PaymentMethodDetails'])){
                if(is_array($orderData['PaymentMethodDetails']['PaymentMethodDetail']))
                $checkDuplicate->PaymentMethodDetails = json_encode($orderData['PaymentMethodDetails']['PaymentMethodDetail']);
                else
                $checkDuplicate->PaymentMethodDetails = $orderData['PaymentMethodDetails']['PaymentMethodDetail'];
            }

            if(!empty($orderData['NumberOfItemsUnshipped']))
            $checkDuplicate->NumberOfItemsUnshipped = $orderData['NumberOfItemsUnshipped'];

            if(!empty($orderData['LatestShipDate']))
            $checkDuplicate->LatestShipDate = (new DateTime($orderData['LatestShipDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['EarliestShipDate']))
            $checkDuplicate->EarliestShipDate = (new DateTime($orderData['EarliestShipDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['LatestDeliveryDate']))
            $checkDuplicate->LatestDeliveryDate = (new DateTime($orderData['LatestDeliveryDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['EarliestDeliveryDate']))
            $checkDuplicate->EarliestDeliveryDate = (new DateTime($orderData['EarliestDeliveryDate']))->setTimezone(new DateTimeZone($timezone))->format('Y-m-d H:i:s');

            if(!empty($orderData['PurchaseOrderNumber']))
            $checkDuplicate->PurchaseOrderNumber = $orderData['PurchaseOrderNumber'];

            if(!empty($orderData['NumberOfItemsShipped']))
            $checkDuplicate->NumberOfItemsShipped = $orderData['NumberOfItemsShipped'];

            if(!empty($orderData['IsReplacementOrder']))
            $checkDuplicate->IsReplacementOrder = $orderData['IsReplacementOrder'];

            if(!empty($orderData['IsBusinessOrder']))
            $checkDuplicate->IsBusinessOrder = $orderData['IsBusinessOrder'];

            if(!empty($orderData['IsPremiumOrder']))
            $checkDuplicate->IsPremiumOrder = $orderData['IsPremiumOrder'];

            if(!empty($orderData['ShipServiceLevel']))
            $checkDuplicate->ShipServiceLevel = $orderData['ShipServiceLevel'];

            if(!empty($orderData['SalesChannel']))
            $checkDuplicate->SalesChannel = $orderData['SalesChannel'];

            if(!empty($orderData['ShippedByAmazonTFM']))
            $checkDuplicate->ShippedByAmazonTFM = $orderData['ShippedByAmazonTFM'];

            if(!empty($orderData['MarketplaceId']))
            $checkDuplicate->MarketplaceId = $orderData['MarketplaceId'];

            if(!empty($orderData['FulfillmentChannel']))
            $checkDuplicate->FulfillmentChannel = $orderData['FulfillmentChannel'];

            if(!empty($orderData['IsPrime']))
            $checkDuplicate->IsPrime = $orderData['IsPrime'];

            if(!empty($orderData['ShipmentServiceLevelCategory']))
            $checkDuplicate->ShipmentServiceLevelCategory = $orderData['ShipmentServiceLevelCategory'];

            if(!empty($orderData['SellerOrderId']))
            $checkDuplicate->SellerOrderId = $orderData['SellerOrderId'];
            
            if($checkDuplicate->sync_flg != 'U'){
                $checkDuplicate->sync_flg = 'N';
            }
            
            /*if($checkDuplicate->sync_status_flg == 'SNR')
            $checkDuplicate->sync_status_flg = 'New';*/

            if(empty($checkDuplicate->xo_id)){
                $snr_status = $this->checkSNRStatus($sellerDetails['seller_id'], $orderData);
                if($snr_status == true){
                    $checkDuplicate->sync_status_flg = 'SNR';       
                } else if($checkDuplicate->sync_status_flg == 'SNR') {
                    $checkDuplicate->sync_status_flg = 'New';            
                }
            }
            
            $checkDuplicate->save();

            return $checkDuplicate;
        }
    }

    /* Convert Order's Line Itmes into Db format and store it in DB
        MP - 17/10/2019
    */
    public function storeOrderLineItemsDataInDb($AmazonOrderId,$dbOrderObj,$orderData,$sellerDetails){       
        
        $checkDuplicate = Azorderlineitem::where('OrderItemId',$orderData['OrderItemId'])->where("seller_id",$sellerDetails["seller_id"])->where('AmazonOrderId',$AmazonOrderId)->first();
        
        if(empty($checkDuplicate)){
            
            $orderLineItemStoreObj = new Azorderlineitem();
            $orderLineItemStoreObj->az_order_id = $dbOrderObj['id'];
            $orderLineItemStoreObj->AmazonOrderId = $AmazonOrderId;
            $orderLineItemStoreObj->seller_id = $sellerDetails["seller_id"];

            if(!empty($orderData['OrderItemId']))
            $orderLineItemStoreObj->OrderItemId = $orderData['OrderItemId'];

            if(!empty($orderData['QuantityOrdered']))
            $orderLineItemStoreObj->QuantityOrdered = $orderData['QuantityOrdered'];

            if(!empty($orderData['Title']))
            $orderLineItemStoreObj->Title = $orderData['Title'];

            if(!empty($orderData['SellerSKU']))
            $orderLineItemStoreObj->SellerSKU = $orderData['SellerSKU'];

            if(!empty($orderData['ASIN']))
            $orderLineItemStoreObj->ASIN = $orderData['ASIN'];

            if(!empty($orderData['ItemPrice']))
            $orderLineItemStoreObj->ItemPriceAmount = $orderData['ItemPrice']['Amount'];

            if(!empty($orderData['ItemTax']))
            $orderLineItemStoreObj->ItemTaxAmount = $orderData['ItemTax']['Amount'];

            if(!empty($orderData['PromotionDiscount']))
            $orderLineItemStoreObj->PromotionDiscountAmount = $orderData['PromotionDiscount']['Amount'];

            if(!empty($orderData['PromotionDiscountTax']))
            $orderLineItemStoreObj->PromotionDiscountTaxAmount   = $orderData['PromotionDiscountTax']['Amount'];

            if(!empty($orderData['ShippingPrice']))
            $orderLineItemStoreObj->ShippingPriceAmount = $orderData['ShippingPrice']['Amount'];

            if(!empty($orderData['ShippingDiscount']))
            $orderLineItemStoreObj->ShippingDiscountAmount = $orderData['ShippingDiscount']['Amount'];

            if(!empty($orderData['ShippingTax']))
            $orderLineItemStoreObj->ShippingTaxAmount = $orderData['ShippingTax']['Amount'];

            if(!empty($orderData['ShippingDiscountTax']))
            $orderLineItemStoreObj->ShippingDiscountTaxAmount = $orderData['ShippingDiscountTax']['Amount'];

            if(!empty($orderData['QuantityShipped']))
            $orderLineItemStoreObj->QuantityShipped = $orderData['QuantityShipped'];

            if(!empty($orderData['PointsGranted']))
            $orderLineItemStoreObj->PointsGranted = $orderData['PointsGranted'];

            if(!empty($orderData['IsTransparency']))
            $orderLineItemStoreObj->IsTransparency = $orderData['IsTransparency'];

            if(!empty($orderData['ConditionId']))
            $orderLineItemStoreObj->ConditionId = $orderData['ConditionId'];

            if(!empty($orderData['ConditionSubtypeId']))
            $orderLineItemStoreObj->ConditionSubtypeId = $orderData['ConditionSubtypeId'];

            if(!empty($orderData['ConditionNote']))
            $orderLineItemStoreObj->ConditionNote = $orderData['ConditionNote'];

            if(!empty($orderData['IsGift']))
            $orderLineItemStoreObj->IsGift = $orderData['IsGift'];

            if(!empty($orderData['BuyerCustomizedInfo']))
            $orderLineItemStoreObj->BuyerCustomizedInfo = $orderData['BuyerCustomizedInfo'];

            if(!empty($orderData['ScheduledDeliveryStartDate']))
            $orderLineItemStoreObj->ScheduledDeliveryStartDate = $orderData['ScheduledDeliveryStartDate'];

            if(!empty($orderData['ScheduledDeliveryEndDate']))
            $orderLineItemStoreObj->ScheduledDeliveryEndDate = $orderData['ScheduledDeliveryEndDate'];

            if(!empty($orderData['ProductInfo']))
            $orderLineItemStoreObj->ProductInfo = json_encode($orderData['ProductInfo']);

            if(!empty($orderData['CODFeeAmount']))
            $orderLineItemStoreObj->CODFeeAmount = $orderData['CODFeeAmount'];

            if(!empty($orderData['CODFeeDiscountAmount']))
            $orderLineItemStoreObj->CODFeeDiscountAmount = $orderData['CODFeeDiscountAmount'];

            if(!empty($orderData['GiftMessageText']))
            $orderLineItemStoreObj->GiftMessageText = $orderData['GiftMessageText'];

            if(!empty($orderData['GiftWrapPriceAmount']))
            $orderLineItemStoreObj->GiftWrapPriceAmount = $orderData['GiftWrapPriceAmount'];

            if(!empty($orderData['GiftWrapLevel']))
            $orderLineItemStoreObj->GiftWrapLevel = $orderData['GiftWrapLevel'];

            if(!empty($orderData['PriceDesignation']))
            $orderLineItemStoreObj->PriceDesignation = $orderData['PriceDesignation'];

            if(!empty($orderData['TaxCollection']))
            $orderLineItemStoreObj->TaxCollection = json_encode($orderData['TaxCollection']);

            if(!empty($orderData['PromotionIds']))
            $orderLineItemStoreObj->PromotionIds = json_encode($orderData['PromotionIds']);
        
            $orderLineItemStoreObj->save();

            return $orderLineItemStoreObj;

        }else{  
            $updateInvoice = false;
            $checkDuplicate->az_order_id = $dbOrderObj['id'];
            $checkDuplicate->AmazonOrderId = $AmazonOrderId;
            $checkDuplicate->seller_id = $sellerDetails["seller_id"];

            if(!empty($orderData['OrderItemId']))
            $checkDuplicate->OrderItemId = $orderData['OrderItemId'];

            if(!empty($orderData['QuantityOrdered']))
            $checkDuplicate->QuantityOrdered = $orderData['QuantityOrdered'];

            if(!empty($orderData['Title']))
            $checkDuplicate->Title = $orderData['Title'];

            if(!empty($orderData['SellerSKU']))
            $checkDuplicate->SellerSKU = $orderData['SellerSKU'];

            if(!empty($orderData['ASIN']))
            $checkDuplicate->ASIN = $orderData['ASIN'];

            if(!empty($orderData['ItemPrice'])){
                if($checkDuplicate->ItemPriceAmount != $orderData['ItemPrice']['Amount']){
                    $updateInvoice = true;
                }
                $checkDuplicate->ItemPriceAmount = $orderData['ItemPrice']['Amount'];
            }

            if(!empty($orderData['ItemTax'])){
                if($checkDuplicate->ItemTaxAmount != $orderData['ItemTax']['Amount']){
                    $updateInvoice = true;
                }
                $checkDuplicate->ItemTaxAmount = $orderData['ItemTax']['Amount'];
            }

            if(!empty($orderData['PromotionDiscount']))
            $checkDuplicate->PromotionDiscountAmount = $orderData['PromotionDiscount']['Amount'];

            if(!empty($orderData['PromotionDiscountTax']))
            $checkDuplicate->PromotionDiscountTaxAmount   = $orderData['PromotionDiscountTax']['Amount'];

            if(!empty($orderData['ShippingPrice'])){
                if($checkDuplicate->ShippingPriceAmount != $orderData['ShippingPrice']['Amount']){
                    $updateInvoice = true;
                }
                $checkDuplicate->ShippingPriceAmount = $orderData['ShippingPrice']['Amount'];
            }

            if(!empty($orderData['ShippingDiscount']))
            $checkDuplicate->ShippingDiscountAmount = $orderData['ShippingDiscount']['Amount'];

            if(!empty($orderData['ShippingTax']))
            $checkDuplicate->ShippingTaxAmount = $orderData['ShippingTax']['Amount'];

            if(!empty($orderData['ShippingDiscountTax']))
            $checkDuplicate->ShippingDiscountTaxAmount = $orderData['ShippingDiscountTax']['Amount'];

            if(!empty($orderData['QuantityShipped']))
            $checkDuplicate->QuantityShipped = $orderData['QuantityShipped'];

            if(!empty($orderData['PointsGranted']))
            $checkDuplicate->PointsGranted = $orderData['PointsGranted'];

            if(!empty($orderData['IsTransparency']))
            $checkDuplicate->IsTransparency = $orderData['IsTransparency'];

            if(!empty($orderData['ConditionId']))
            $checkDuplicate->ConditionId = $orderData['ConditionId'];

            if(!empty($orderData['ConditionSubtypeId']))
            $checkDuplicate->ConditionSubtypeId = $orderData['ConditionSubtypeId'];

            if(!empty($orderData['ConditionNote']))
            $checkDuplicate->ConditionNote = $orderData['ConditionNote'];

            if(!empty($orderData['IsGift']))
            $checkDuplicate->IsGift = $orderData['IsGift'];

            if(!empty($orderData['BuyerCustomizedInfo']))
            $checkDuplicate->BuyerCustomizedInfo = $orderData['BuyerCustomizedInfo'];

            if(!empty($orderData['ScheduledDeliveryStartDate']))
            $checkDuplicate->ScheduledDeliveryStartDate = $orderData['ScheduledDeliveryStartDate'];

            if(!empty($orderData['ScheduledDeliveryEndDate']))
            $checkDuplicate->ScheduledDeliveryEndDate = $orderData['ScheduledDeliveryEndDate'];

            if(!empty($orderData['ProductInfo']))
            $checkDuplicate->ProductInfo = json_encode($orderData['ProductInfo']);

            if(!empty($orderData['CODFeeAmount']))
            $checkDuplicate->CODFeeAmount = $orderData['CODFeeAmount'];

            if(!empty($orderData['CODFeeDiscountAmount']))
            $checkDuplicate->CODFeeDiscountAmount = $orderData['CODFeeDiscountAmount'];

            if(!empty($orderData['GiftMessageText']))
            $checkDuplicate->GiftMessageText = $orderData['GiftMessageText'];

            if(!empty($orderData['GiftWrapPriceAmount']))
            $checkDuplicate->GiftWrapPriceAmount = $orderData['GiftWrapPriceAmount'];

            if(!empty($orderData['GiftWrapLevel']))
            $checkDuplicate->GiftWrapLevel = $orderData['GiftWrapLevel'];

            if(!empty($orderData['PriceDesignation']))
            $checkDuplicate->PriceDesignation = $orderData['PriceDesignation'];

            if(!empty($orderData['TaxCollection']))
            $checkDuplicate->TaxCollection = json_encode($orderData['TaxCollection']);

            if(!empty($orderData['PromotionIds']))
            $checkDuplicate->PromotionIds = json_encode($orderData['PromotionIds']);
        
            $checkDuplicate->save(); 

            if($updateInvoice == true){                
                $orderObj = Azorder::where('id',$dbOrderObj['id'])->first();
                if(!empty($orderObj)){
                    if(!empty($orderObj->xo_id)){
                        $orderObj->sync_flg = 'U';
                        $orderObj->save();

                    } else if(empty($orderObj->xo_id) && ($orderObj->sync_status_flg == 'Pending' || $orderObj->sync_status_flg == 'SNR')){
                        $orderObj->sync_status_flg = 'New';
                        $orderObj->save();
                    }
                }
            }
            return $checkDuplicate;
        }
    }

    public function checkSNRStatus($seller_id,$orderData){
        if(!empty($orderData['OrderStatus']) && $orderData['OrderStatus'] == 'Canceled')
          return true;

        if(!empty($orderData['OrderTotal'])){
          if(empty($orderData['OrderTotal']['Amount']))
            return true;
        } else {
            return true;
        }

        $sellerFeature = Azfeature::getFeatures($seller_id,'ORDERIGNORE');        
        if(!empty($sellerFeature)){
            $featureDetails = json_decode($sellerFeature['details'],true);            
            if(!empty($featureDetails)){
                $orderData = json_decode(json_encode($orderData),true);
                $azOrderDot = array_dot($orderData);                
                foreach ($featureDetails as $featureKey => $featureValue) {
                    $dbOrderValue = isset($azOrderDot[$featureKey]) ? $azOrderDot[$featureKey] : '';                    
                    if($featureValue == $dbOrderValue){
                        return true;
                    }
                }
                return false;                
            }
        }else{
            return false;
        }
    }

    /*
        Auto sync orders cron
    */
    public function autoSyncOrdersFromAmazonAll(){
        
        $this->randomValue = rand(1111111111,9999999999);

        $sellerData = Azsellers::getAutoSellerDetails();
        $this->cronActionLog('', 'Amazon', 'Auto cron for fetch orders for all sellers - START', $this->randomValue);
        if(!empty($sellerData)){
            foreach ($sellerData as $key => $value) {
                $request = new \Illuminate\Http\Request();
                $sellerid = Helper::encryptor('encrypt',$value->sellerId);
                $request->replace(['sellerid' => $sellerid]);
                
                $this->cronActionLog($value->sellerId, 'Amazon', 'Fetch orders for seller', $this->randomValue);
                $this->getOrdersFromAmazonSp($request,'All');
                
            }
        }
        $this->cronActionLog('', 'Amazon', 'Auto cron for fetch orders for all sellers - END', $this->randomValue);
    }   

    public function autoSyncUpdateOrdersFromAmazonAll(){

        $this->randomValue = rand(1111111111,9999999999);

        $sellerData = Azsellers::getAutoSellerDetails();
        $this->cronActionLog('', 'Amazon', 'Auto cron for update orders for all sellers - START', $this->randomValue);        
        if(!empty($sellerData)){
            foreach ($sellerData as $key => $value) {
                $request = new \Illuminate\Http\Request();
                $sellerid = Helper::encryptor('encrypt',$value->sellerId);
                $request->replace(['sellerid' => $sellerid]);
                
                $this->cronActionLog($value->sellerId, 'Amazon', 'Update orders for seller', $this->randomValue);
                $this->updateOrdersFromAmazonSp($request,'All');
                
            }
        }
        $this->cronActionLog('', 'Amazon', 'Auto cron for update orders for all sellers - END', $this->randomValue);
    }
}