<?php

namespace App\Http\Controllers\Ecomtoacc\Shopify;

use App\Http\Controllers\Controller;
use App\Models\Shopify\Spycredential;
use App\Models\Shopify\Spyreportsetting;
use App\Models\Shopify\Spylastsync;
use App\Models\Shopify\Spysummaryorder;
use App\Models\Shopify\Spyorderlineitems;
use App\Models\Shopify\Spyordertransaction;
use App\Models\Shopify\Spysummaryrefund;
use App\Models\Shopify\Spysummaryfees;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use DateTime;
use DateTimeZone;
use Input;

class OrderController extends Controller
{
    private $randomValue = 0;

    public function fetchSpyOrders(Request $request)
    {
        $seller_id = $request->get('seller_id');
        $type = $request->get('type');
        $seller_id = (!empty($seller_id))? Helper::encryptor('decrypt', $seller_id) : "";
        $startdate = $request->get('startdate');
        $enddate = $request->get('enddate');
        $order_id = $request->get('order_id');
        $fetchBackDateData =false;
        if((!empty($startdate) && !empty($enddate))|| (!empty($order_id))){
            $fetchBackDateData =true;
        }
    
        $this->randomValue = rand(1111111111,9999999999);
        $spyStoreDatas = Spycredential::fetchValidSpyStores($seller_id);
        foreach ($spyStoreDatas as $key => $spyStoreData) {
            $this->cronActionLog($spyStoreData['id'], 'Shopify', 'Auto cron for fetch orders- START', $this->randomValue);
            
            $shop = $spyStoreData['store_domain'];
            $SpySettingData = Spyreportsetting::fetchReportSettingData('seller_id', $spyStoreData->id);
            if(!empty($SpySettingData)){
                if ($type == "update") {
                    $this->syncUpdateOrderData($shop, $spyStoreData, $SpySettingData);
                } else {
                    $this->syncSummaryOrderData($shop, $spyStoreData, $SpySettingData,$startdate, $enddate,$fetchBackDateData,$order_id);
                }
            }
            $this->cronActionLog($spyStoreData['id'], 'Shopify', 'Auto cron for fetch orders- END', $this->randomValue);
        }
        return 'success';

    }
   
    public function syncSummaryOrderData($shop,$spyConnected,$SpySettingData, $startDate="", $endDate="",$fetchBackDateData=false,$order_id="")
    {
        ini_set('max_execution_time', 0);
        if (!empty($spyConnected)) {

            $SpylastsyncData  = Spylastsync::fetchSpylastsyncorderDataById("sync_type", "Order", $spyConnected["id"],$spyConnected["module"]);
            
            $lastOrderId = $lastUpdatedOrder = $nextUrl = '';
            $orderType = 'create';
            do {
                $SpylastsyncData = Spylastsync::fetchSpylastsyncorderDataById("sync_type", "Order", $spyConnected["id"],$spyConnected["module"]);
                if(!empty($order_id)){
                    $orderResponse = $this->fetchOrderByIdFromShopify($spyConnected, $shop, $order_id);
                }else if ($startDate != '' && $endDate != '') {
                    $orderResponse = $this->fetchOldOrderFromShopify($spyConnected, $shop,$nextUrl, $startDate, $endDate);
                } else {
                    $orderResponse   = $this->fetchOrderFromShopify($spyConnected, $shop, $SpylastsyncData, $nextUrl,$SpySettingData);
                }
                $nextUrl         = $orderResponse['url'];
                $orderData       = $orderResponse['data'];
                
                if (!empty($orderData['orders'])) {
                    $insertFlg = true;
                    $financial_status=true;
                    foreach ($orderData['orders'] as $key => $value) {
                        $processed_at = (new DateTime($value['processed_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
                        if($orderType=="update"){
                            $financial_status=$value['financial_status'] != "voided";
                        }
                        if ((!empty($SpySettingData->sync_start_date) && date("Y-m-d", strtotime($processed_at)) >= $SpySettingData->sync_start_date && $financial_status) || ($fetchBackDateData)) {
                           //Log::info("Order Data ---".$value['id']."--store Id".$spyConnected["id"]);
                            if ($lastOrderId == '') {
                                $lastOrderId = $value['id'];
                            } elseif ($lastOrderId < $value['id']) {
                                $lastOrderId = $value['id'];
                            }

                            $created_at = (new DateTime($value['processed_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d');
                            if ($lastUpdatedOrder == '') {
                                $lastUpdatedOrder = $created_at;
                            } elseif ($lastUpdatedOrder < $created_at) {
                                $lastUpdatedOrder = $created_at;
                            }

                            if (empty($SpylastsyncData)) {
                                $insertFlg = true;
                            } else {
                                if (($value['id'] > $SpylastsyncData['latest_order_id']) || ($fetchBackDateData)) {
                                    $insertFlg = true;
                                } else {
                                    $insertFlg = false;
                                }

                            }
                          
                            if ($insertFlg) {
                                $spyStoreObj = $this->createUpdateOrderDataInDb($spyConnected, $value,$orderType,$SpySettingData,$fetchBackDateData);
                            } else {
                                // $spyUpdateDataStoreObj = $this->updateOrderDataInDb($spyConnected, $value, $SpySettingData);
                                // $checkDuplicate        = Spysummaryorder::fetchSpyOrderSingleData("order_id", $value['id'], $spyConnected["id"]);
                            }
                        }
                    }
                    if ((empty($SpylastsyncData)) && $fetchBackDateData ==false) {
                        if ($lastUpdatedOrder != '' && $lastOrderId != '') {
                            $Spylastsyncobj                  = new Spylastsync();
                            $Spylastsyncobj->seller_id        = $spyConnected["id"];
                            $Spylastsyncobj->module        = $spyConnected["module"];
                            //$Spylastsyncobj->last_updated_at = (!empty($SpySettingData->sync_start_date))?$SpySettingData->sync_start_date:"";
                            $Spylastsyncobj->last_updated_at =date("Y-m-d H:i:s");
                            $Spylastsyncobj->latest_order_id = $lastOrderId;
                            $Spylastsyncobj->sync_type       = "Order";

                            $Spylastsyncobj->save();
                        }
                    } else {
                        if ((!empty($lastUpdatedOrder) && !empty($lastOrderId)) && $fetchBackDateData ==false) {
                            Spylastsync::where("seller_id", $spyConnected["id"])->where('sync_type', 'Order')->update([
                                //"last_updated_at" => $lastUpdatedOrder,
                                "latest_order_id" => $lastOrderId,
                            ]);
                        }
                    }
                }
            } while ($nextUrl != '');
        }
    }

    public function syncUpdateOrderData($shop,$spyConnected,$SpySettingData)
    {
        ini_set('max_execution_time', 0);
       /*  $shop = encryptor('decrypt',$request->get('domain'));
        $shopenc = $request->get('domain');
        $spyConnected = $request->get('spyConnected'); */
        //$spyConnected = Xerocredential::checkXeroConnected('store_domain', $shop);
        if (!empty($spyConnected)) {
            $SpylastsyncData  = Spylastsync::fetchSpylastsyncorderDataById("sync_type", "Order", $spyConnected["id"],$spyConnected["module"]);
            
            if (!empty($SpylastsyncData)) {
                $lastUpdatedOrder = '';
                $nextUrl          = '';
                $orderType          = 'update';
                do {
                    $orderResponse = $this->fetchUpdateOrderFromShopify($spyConnected, $shop, $SpylastsyncData, $nextUrl);
                    $nextUrl       = $orderResponse['url'];
                    $orderData     = $orderResponse['data'];
                    if (!empty($orderData['orders'])) {

                        foreach ($orderData['orders'] as $key => $value) {
                            $updateFlg = true;
                            //if (!empty($SpySettingData->sync_start_date) && date("Y-m-d", strtotime($value['processed_at'])) >= $SpySettingData->sync_start_date) {

                                if ($value['id'] <= $SpylastsyncData['latest_order_id'] && $lastUpdatedOrder < date("Y-m-d H:i:s", strtotime($value['updated_at']))) {
                                    $lastUpdatedOrder = date("Y-m-d H:i:s", strtotime($value['updated_at']));
                                }
                             
                                if ($value['id'] > $SpylastsyncData['latest_order_id']) {
                                    $updateFlg = false;
                                }

                                if ($updateFlg) {
                                    //Log::info("Update Order Data ---" . $value['id'] . "-----" . $value['updated_at'] . "--store Id" . $spyConnected["id"]);
                                    $spyUpdateDataStoreObj = $this->createUpdateOrderDataInDb($spyConnected, $value,$orderType,$SpySettingData);

                                }
                            //}

                        }
                        Spylastsync::where("seller_id", $spyConnected["id"])->where('sync_type', 'Order')->update([
                            "last_updated_at" => $lastUpdatedOrder,
                        ]);
                    }
                } while ($nextUrl != '');
                //exit;
            }
        }
    }

    private function fetchOrderFromShopify($spyConnected, $shop, $SpylastsyncData, $nextUrl = '',$spySettingsData)
    {
        if ($nextUrl != '') {
            $shopUrl = $nextUrl;
        } else {
            if (empty($SpylastsyncData)) {

                if (!empty($spySettingsData) && !empty($spySettingsData->sync_start_date)) {
                    //$date    = date('Y-m-d', strtotime($spySettingsData->sync_start_date . ' - 2 days'));
                    $shopUrl = "https://" . $shop . "/admin/" . config('app.shopify_version') . "/orders.json?status=any&processed_at_min=" . $spySettingsData->sync_start_date . "&since_id=1&limit=" . config("app.orderPaginationLimit");
                } else {
                    $shopUrl = "https://" . $shop . "/admin/" . config('app.shopify_version') . "/orders.json?status=any&since_id=1&limit=" . config("app.orderPaginationLimit");
                }
            } else {
                $shopUrl = "https://" . $shop . "/admin/" . config('app.shopify_version') . "/orders.json?status=any&since_id=" . $SpylastsyncData['latest_order_id'] . "&limit=" . config("app.orderPaginationLimit");
            }
        }
       
        $result= app('App\Http\Controllers\Ecomtoacc\Shopify\ApiController')::shop_curl_request_call_header($shopUrl, $spyConnected['store_access_token']);
        
        $productResponse['url']  = $result['url'];
        $productResponse['data'] = json_decode($result['data'], true);
        return $productResponse;
    }
    private function fetchUpdateOrderFromShopify($spyConnected, $shop, $SpylastsyncData, $nextUrl = '')
    {
       
        $SpylastsyncData= str_replace(" ","T",$SpylastsyncData['last_updated_at']);
      
        if ($nextUrl != '') {
            $shopUrl = $nextUrl;
        } else {
            
            $shopUrl = "https://" . $shop . "/admin/" . config('app.shopify_version') . "/orders.json?status=any&updated_at_min=" . $SpylastsyncData . "&since_id=1&limit=" . config("app.orderPaginationLimit");
        }
        $result                  = app('App\Http\Controllers\Ecomtoacc\Shopify\ApiController')::shop_curl_request_call_header($shopUrl, $spyConnected['store_access_token']);
        $productResponse['url']  = $result['url'];
        $productResponse['data'] = json_decode($result['data'], true);
        return $productResponse;
    }

    public function createUpdateOrderDataInDb($spyConnected, $orderData,$orderType="",$SpySettingData,$fetchBackDateData=false)
    {
        $spyStoreObj = Spysummaryorder::fetchSpyOrderSingleData("order_id", $orderData['id'], $spyConnected["id"],$spyConnected["module"]);
        $saved=false;
        $sales_data =$cost_data= array();
            if (empty($spyStoreObj)) {
                $spyStoreObj = new Spysummaryorder();
            }
            if($orderType=="update"){
                $updated_at = (new DateTime($orderData['updated_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
                
                if (($spyStoreObj->order_updated_at == $updated_at)) {
                    //return false;
                }
            }
            
            $this->editOrderFormat($orderData);

            $spyStoreObj->order_id = $orderData['id'];
            $spyStoreObj->module = $spyConnected['module'];

            if (!empty($orderData['email'])) {
                $spyStoreObj->email = $orderData['email'];
            }

            if (!empty($orderData['created_at'])) {
                $spyStoreObj->order_created_at = (new DateTime($orderData['created_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
            }

            if (!empty($orderData['updated_at'])) {
                $spyStoreObj->order_updated_at = (new DateTime($orderData['updated_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
            }

            if (!empty($orderData['number'])) {
                $spyStoreObj->number = $orderData['number'];
            }

            if (!empty($orderData['gateway'])) {
                $spyStoreObj->gateway = $orderData['gateway'];
            }

            if (!empty($orderData['total_price'])) {
                $spyStoreObj->total_price = $orderData['total_price'];
            }
            if(isset($orderData['current_total_price']) && !empty($orderData['current_total_price'])){
                $spyStoreObj->current_total_price = $orderData['current_total_price'];
            }

            if (!empty($orderData['subtotal_price'])) {
                $spyStoreObj->subtotal_price = $orderData['subtotal_price'];
            }

            if (!empty($orderData['total_tax'])) {
                $spyStoreObj->total_tax = $orderData['total_tax'];
            }

            if (!empty($orderData['taxes_included'])) {
                $spyStoreObj->taxes_included = $orderData['taxes_included'];
            }

            if (!empty($orderData['currency'])) {
                $spyStoreObj->currency = $orderData['currency'];
            }

            if (!empty($orderData['financial_status'])) {
                $spyStoreObj->financial_status = $orderData['financial_status'];
            }

            if (!empty($orderData['total_discounts'])) {
                $spyStoreObj->total_discounts = $orderData['total_discounts'];
            }

            if (!empty($orderData['total_line_items_price'])) {
                $spyStoreObj->total_line_items_price = $orderData['total_line_items_price'];
            }

            if (!empty($orderData['name'])) {
                $spyStoreObj->name = $orderData['name'];
            }

            if (!empty($orderData['cancelled_at'])) {
                $spyStoreObj->cancelled_at = (new DateTime($orderData['cancelled_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
            }

            if (!empty($orderData['processed_at'])) {
                $spyStoreObj->processed_at = (new DateTime($orderData['processed_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
            }

            if (!empty($orderData['order_number'])) {
                $spyStoreObj->order_number = $orderData['order_number'];
            }

            if (!empty($orderData['payment_gateway_names'])) {
                $spyStoreObj->payment_gateway_names = json_encode($orderData['payment_gateway_names']);
            }

            if (!empty($orderData['source_name'])) {
                $spyStoreObj->source_name = $orderData['source_name'];
            }

            if (!empty($orderData['fulfillment_status'])) {
                $spyStoreObj->fulfillment_status = $orderData['fulfillment_status'];
            }

            if (!empty($orderData['presentment_currency'])) {
                $spyStoreObj->presentment_currency = $orderData['presentment_currency'];
            }

            if (!empty($orderData['reference'])) {
                $spyStoreObj->reference = $orderData['reference'];
            }

            if (!empty($orderData['location_id'])) {
                $spyStoreObj->location_id = $orderData['location_id'];
            }
            
            if (!empty($orderData['source_identifier'])) {
                $spyStoreObj->source_identifier = $orderData['source_identifier'];
            }
            
            if (!empty($orderData['processing_method'])) {
                $spyStoreObj->processing_method = $orderData['processing_method'];
            }
        
            $spyStoreObj->billing_country_code = (!empty($orderData['billing_address']['country_code']))?$orderData['billing_address']['country_code']:NULL;
            $spyStoreObj->billing_province_code = (!empty($orderData['billing_address']['province_code']))?$orderData['billing_address']['province_code']:NULL;
            $spyStoreObj->shipping_country_code = (!empty($orderData['shipping_address']['country_code']))?$orderData['shipping_address']['country_code']:NULL;
            $spyStoreObj->shipping_province_code = (!empty($orderData['shipping_address']['province_code']))?$orderData['shipping_address']['province_code']:NULL;

            if (!empty($orderData['tags'])) {
                $spyStoreObj->tags = $orderData['tags'];
            }

            $shippingtaxRate =$total_giftcard= 0;
            if (!empty($orderData['line_items'])) {
                foreach ($orderData['line_items'] as $key => $value) {
                    if($value['title'] != 'Tip'){
                        $discountAmt = 0;
                        $LineItemAmtValue = 0;
                        $taxRate = 0; 
                        $taxAmountLine = 0;
                        if ($value['gift_card'] != true) {

                            $LineItemAmtValue = $value['quantity'] * $value['price'];
                            foreach(@$value['discount_allocations'] as $discount)
                            {
                                if(isset($discount['amount']))
                                {
                                    $discountAmt +=  $discount['amount'];
                                }
                            }
                            
                            foreach ($value['tax_lines'] as $key1 => $value1) 
                            {
                                if($value1['price'] > 0 && $value['gift_card'] != true){
                                $taxAmountLine = $taxAmountLine + $value1['price'];
                                $taxRate = $taxRate + $value1['rate'];
                                }
                            }
                        }
                        
                        $taxRate = $taxRate*100;
                        $taxRate = (string)$taxRate;
                        if(is_null($orderData['taxes_included']) && $orderData['total_tax'] != 0)
                        {
                          $LineItemAmtValue = $LineItemAmtValue + $taxAmountLine;
                        }
                        if(isset($sales_data[$taxRate]) && !empty($sales_data[$taxRate]) && isset($sales_data[$taxRate]['order']) && !empty($sales_data[$taxRate]['order']) ){
                            $sales_data[$taxRate]['order']['amount'] += $LineItemAmtValue;
                            $sales_data[$taxRate]['order']['tax'] += $taxAmountLine;
                            $sales_data[$taxRate]['order']['discount'] += $discountAmt;
                        }
                        else{
                            $sales_data[$taxRate]['order']['amount'] = $LineItemAmtValue;
                            $sales_data[$taxRate]['order']['tax'] = $taxAmountLine;  
                            $sales_data[$taxRate]['order']['discount'] = $discountAmt;  
                        }
                        foreach ($value['duties'] as $dutieskey => $dutiesval) {
                            if(isset($sales_data[$taxRate]) && !empty($sales_data[$taxRate]) && isset($sales_data[$taxRate]['duties']) && !empty($sales_data[$taxRate]['duties']) ){
                                $sales_data[$taxRate]['duties']['amount'] += $dutiesval['price_set']['shop_money']['amount'];
                                if(!empty($dutiesval['tax_lines'])){
                                    foreach ($dutiesval['tax_lines'] as $dutiestaxval) {
                                        $sales_data[$taxRate]['duties']['tax'] += $dutiestaxval['price'];
                                    }
                                }
                            }
                            else{
                                $sales_data[$taxRate]['duties']['amount'] = $dutiesval['price_set']['shop_money']['amount'];
                                if(!empty($dutiesval['tax_lines'])){
                                    foreach ($dutiesval['tax_lines'] as $dutiestaxval) {
                                        $sales_data[$taxRate]['duties']['tax'] = $dutiestaxval['price'];  
                                    }
                                }
                            }
                        }
                        if ($value['gift_card'] == true) {
                            $total_giftcard += $value['price'];
                        }
                        if (isset($SpySettingData->cogs_enable) && $SpySettingData->cogs_enable=="Yes") {
                           //$cost_data= $this->storeAndGetCost($spyConnected,$SpySettingData,$value,$cost_data);
                        }
                    }
                }
            }
           
            $paymentData = $this->fetchPaymentsFromShopify($spyConnected,$orderData['id']);
            if(!empty($paymentData) && isset($paymentData['transactions'])){
                //fetch transaction
                if (!empty($orderData['payment_gateway_names']) && in_array("gift_card", $orderData['payment_gateway_names'])) {
                   $paymentTemp = $paymentData;
                    foreach ($paymentData['transactions'] as $key => $value) {
                        if($value['gateway'] == "gift_card"  && $value['status'] =='success' && ($value['kind'] =='capture' || $value['kind'] =='sale' || $value['kind'] =='refund') && $orderData['financial_status'] != 'refunded' && $orderData['financial_status'] != 'partially_refunded')
                        {
                            if(array_search($value['id'], array_column($paymentData['transactions'], 'parent_id')) !== false) {
                                $key1 =array_search($value['id'], array_column($paymentData['transactions'], 'parent_id'));
                                if($value['amount'] == $paymentData['transactions'][$key1]['amount']){
                                    unset($paymentTemp['transactions'][$key]);
                                    unset($paymentTemp['transactions'][$key1]);                  
                                }
                            }    
                        }
                    }
                    $paymentTemp = array_values($paymentTemp['transactions']);
                    if(!empty($paymentTemp)){
                        foreach ($paymentTemp as $key => $value) {
                            if($value['gateway'] == "gift_card" && $value['status'] == 'success' && ($value['kind'] =='capture' || $value['kind'] =='sale')){
                                if($orderData['currency']!=$value['currency']){
                                    $processed_at = date('Y-m-d', strtotime($value['processed_at']));
                                    $exchange_rate=getExchangeRateApi("",$processed_at,$value['currency'],$orderData['currency'],"");
                                    $total_giftcard-=(double)$value['amount']*(double)$exchange_rate;
                                }else{
                                    $total_giftcard -= $value['amount'];

                                }
                            }
                        }
                    }

                }
                $exchange_rate = NULL;
                if($orderData['currency'] != $orderData['presentment_currency']){
                    $paymentexchangerate = array();
                    foreach ($paymentData['transactions'] as $keypay => $valuepay) {
                        if($valuepay['status'] =='success' && ($valuepay['kind'] =='capture' || $valuepay['kind'] =='sale')){
                            $paymentexchangerate[] = $valuepay; 
                        }
                    }
                    if(!empty($paymentexchangerate)){
                        $paymentDot = Arr::dot($paymentexchangerate);
                        foreach ($paymentDot as $dotkey => $dotvalue) {
                            if(stripos($dotkey, "exchange_rate") !== false && ($orderData['gateway'] == 'shopify_payments' || $orderData['gateway'] == 'shopify_installments' || $orderData['gateway'] == 'shop_cash')){
                                $exchange_rate = $dotvalue;
                            }
                        }
                    }
                }
                $i=0;
                foreach ($paymentData['transactions'] as $key => $value) { 
                    
                    if($value['status'] =='success' && $value['gateway'] != "gift_card" && $value['kind']!="void" && $value['kind']!="authorization"){ 

                        if($i == 0){
                            $spyStoreObj->transaction_gateway = $value['gateway'];
                            $spyStoreObj->transaction_date = (new DateTime($value['processed_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
                            $spyStoreObj->transaction_id = $value['id'];
                        }       
                        $ordertransDate= (new DateTime($value['created_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d');
                        ////Log::info("Spyordertransaction Data ---" .$SpySettingData->sync_start_date . "-----" . $ordertransDate. "--store Id" . $spyConnected["id"]);

                        if (($SpySettingData->sync_start_date<=$ordertransDate) || ($fetchBackDateData))  {
                            $spypayObj = Spyordertransaction::fetchTransactionSingleData('transaction_id', $value['id'], $spyConnected['id'],$spyConnected["module"]);
                            if (empty($spypayObj)) {
                                $spypayObj = new Spyordertransaction();                        
                                $spypayObj->seller_id = $spyConnected['id'];
                            }
                            $spypayObj->module = $spyConnected['module'];
                            $spypayObj->order_id = $value['order_id'];
                            $spypayObj->transaction_id = $value['id'];
                            $spypayObj->kind = $value['kind'];
                            $spypayObj->gateway = $value['gateway'];
                            $spypayObj->status = $value['status'];
                            $spypayObj->transaction_created_at = (new DateTime($value['created_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
                            $spypayObj->amount = $value['amount'];
                            $spypayObj->currency = $value['currency'];
                            $spypayObj->exchange_rate = $exchange_rate;
                            $gateway_settings =(isset($SpySettingData->gateway_settings))? json_decode($SpySettingData->gateway_settings):[];
                            $checkGatewaySetings = array_column($gateway_settings, $value['gateway']);
                            
                            if(($value['gateway'] == "paypal" || $value['gateway'] == "stripe") ){ 
                                $spypayObj->reference = $value['authorization'];
                            }
                            $spypayObj->save();

                            if(($value['gateway'] == "paypal")){
                                $spyFeesObj = Spysummaryfees::addSpyFees($spypayObj->id,$value['id'], $spyConnected,$value);
                            }   
                            $i++;
                        }
                        
                    }
                }
                if(empty($spyStoreObj->transaction_gateway) && $orderData['gateway']=="gift_card"){
                    $spyStoreObj->transaction_gateway = $orderData['gateway'];
                    $spyStoreObj->transaction_date = (new DateTime($orderData['processed_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
                    $spyStoreObj->transaction_id = $orderData['id'];
                }  
            }


            if (!empty($orderData['shipping_lines'])) {
                $shippingAmount = 0;
                $shippingTax = 0;
                foreach ($orderData['shipping_lines'] as $key => $value) {
                    //$spyStoreObj->total_shipping += $value['price'];
                    $shippingAmount+= $value['price'];
                    $taxAmountLine = 0;
                    $shippingtaxRate = 0;
                    foreach ($value['tax_lines'] as $keytax => $valuetax) {
                        if($value['price'] > 0){
                            //$spyStoreObj->total_shipping_tax += $valuetax['price'];
                            $shippingTax+= $valuetax['price'];
                            $taxAmountLine = $taxAmountLine + $valuetax['price'];
                            $shippingtaxRate = $shippingtaxRate + $valuetax['rate'];
                            $spyStoreObj->total_tax = $spyStoreObj->total_tax - $valuetax['price'];
                        }
                    }
                    $shippingtaxRate = $shippingtaxRate*100;
                    $shippingtaxRate = (string)$shippingtaxRate;
                    $LineItemAmtValue = 0;
                    $LineItemAmtValue = $value['price'];
                    $discountAmt = 0;
                    foreach(@$value['discount_allocations'] as $discount)
                    {
                        if(isset($discount['amount']))
                        {
                            $discountAmt +=  $discount['amount'];
                        }
                    }
                    if(isset($sales_data[$shippingtaxRate]) && !empty($sales_data[$shippingtaxRate]) && isset($sales_data[$shippingtaxRate]['shipping']) ){
                        $sales_data[$shippingtaxRate]['shipping']['amount'] += $LineItemAmtValue;
                        $sales_data[$shippingtaxRate]['shipping']['tax'] += $taxAmountLine;
                        $sales_data[$shippingtaxRate]['shipping']['discount'] += $discountAmt;
                    }
                    else{
                        $sales_data[$shippingtaxRate]['shipping']['amount'] = $LineItemAmtValue;
                        $sales_data[$shippingtaxRate]['shipping']['tax'] = $taxAmountLine;  
                        $sales_data[$shippingtaxRate]['shipping']['discount'] = $discountAmt;  
                    }
                }
                $spyStoreObj->total_shipping = $shippingAmount;
                $spyStoreObj->total_shipping_tax = $shippingTax;

            }
            $spyStoreObj->total_giftcard = $total_giftcard;
            $spyStoreObj->sales_data = json_encode($sales_data);
            if(!empty($cost_data) && $cost_data !=0)
            $spyStoreObj->cost_data = json_encode($cost_data);

            if (!empty($orderData['app_id'])) {
                $spyStoreObj->app_id = $orderData['app_id'];
            }

            if (!empty($orderData['total_tip_received'])) {
                $spyStoreObj->total_tip_received = $orderData['total_tip_received'];
            }
            /*$checkOrderIgnore= Spysummaryorder::checkOrderIgnore($spyConnected,$orderData);
            
            if($checkOrderIgnore){
                $spyStoreObj->sync_flg ="D";
            }else{
                $spyStoreObj->sync_flg ="N";
            }*/
            $spyStoreObj->sync_flg ="N";
            $spyStoreObj->seller_id = $spyConnected["id"];
           
            if (($SpySettingData->sync_start_date <= $spyStoreObj->processed_at) || ($fetchBackDateData)) {
                $saved =$spyStoreObj->save();
            }
            $cogs_enable=isset($SpySettingData->cogs_enable)?$SpySettingData->cogs_enable:"";

            if ((!empty($orderData['refunds']) && !in_array('shopify_payments', $orderData['payment_gateway_names']) && !in_array('shopify_installments', $orderData['payment_gateway_names']) && !in_array('shop_cash', $orderData['payment_gateway_names'])) || $fetchBackDateData) {

               $this->storeRefundsDataInDb($spyConnected,$orderData,$orderData,$SpySettingData->sync_start_date,$orderType,$cogs_enable,$spyStoreObj->id,$fetchBackDateData,$SpySettingData);
            }
            if (!empty($orderData['line_items']) &&  $cogs_enable=="Yes") {
               $this->storeLineItemsInDb($spyConnected,$orderData,$spyStoreObj->id,$orderType);
            }
           
            return $spyStoreObj;
    }
    public function storeLineItemsInDb($spyConnected,$orderData,$id,$order_type=""){
    
        if (!empty($orderData['line_items'])) {
            foreach ($orderData['line_items'] as $key => $value) {
                if($order_type=="update"){

                    $spylineitems = Spylineitems::fetchLineItemsSingleData($value['id'], $spyConnected['id']);
                    if (empty($spylineitems)) {
                        $spylineitems = new Spylineitems(); 
                    }
                    $spylineitems->lineitem_id = $value['id'];
                    $spylineitems->order_id = $id;
                    $spylineitems->seller_id = $spyConnected['id'];
                    $spylineitems->spy_order_id = $orderData['id'];
                    $spylineitems->product_id = $value['product_id'];
                    $spylineitems->variant_id = $value['variant_id'];
                    $spylineitems->sku = $value['sku'];
                    $spylineitems->title = $value['title'];
                    $spylineitems->quantity = $value['quantity'];
                    $spylineitems->price = $value['price'];
                    $spylineitems->save();

                }else{
                    $spylineitems = Spylineitems::fetchLineItemsSingleData($value['id'], $spyConnected['id']);
                    if (empty($spylineitems)) {
                        $spylineitems = new Spylineitems();
                        $spylineitems->lineitem_id = $value['id'];
                        $spylineitems->order_id = $id;
                        $spylineitems->seller_id = $spyConnected['id'];
                        $spylineitems->spy_order_id = $orderData['id'];
                        $spylineitems->product_id = $value['product_id'];
                        $spylineitems->variant_id = $value['variant_id'];
                        $spylineitems->sku = $value['sku'];
                        $spylineitems->title = $value['title'];
                        $spylineitems->quantity = $value['quantity'];
                        $spylineitems->price = $value['price'];
                        $spylineitems->save(); 
                    }
                }

            }
        }
    }
    public function storeRefundLineItemsInDb($spyConnected,$orderData,$order_id,$refund_id,$order_type=""){
      
      
        if (isset($orderData['refund_line_items']) && !empty($orderData['refund_line_items'])) {
            foreach ($orderData['refund_line_items'] as $key => $value) {

                if($order_type=="update"){
                    $Spyrefundlineitems = Spyrefundlineitems::fetchLineItemsSingleData($value['id'], $spyConnected['id']);
                    if (empty($Spyrefundlineitems)) {
                        $Spyrefundlineitems = new Spyrefundlineitems();                        
                    }  
                    $Spyrefundlineitems->lineitem_id = $value['line_item_id'];
                    $Spyrefundlineitems->order_id = $order_id;
                    $Spyrefundlineitems->refund_id = $refund_id;
                    $Spyrefundlineitems->seller_id = $spyConnected['id'];
                    $Spyrefundlineitems->spy_refund_id =$orderData['id'];
                    $Spyrefundlineitems->product_id = $value['line_item']['product_id'];
                    $Spyrefundlineitems->variant_id = $value['line_item']['variant_id'];
                    $Spyrefundlineitems->sku = $value['line_item']['sku'];
                    $Spyrefundlineitems->title = $value['line_item']['title'];
                    $Spyrefundlineitems->quantity = $value['line_item']['quantity'];
                    $Spyrefundlineitems->price = $value['line_item']['price'];
                    $Spyrefundlineitems->save();
                }else{
                    $Spyrefundlineitems = Spyrefundlineitems::fetchLineItemsSingleData($value['id'], $spyConnected['id']);
                    if (empty($Spyrefundlineitems)) {
                        $Spyrefundlineitems = new Spyrefundlineitems();
                        $Spyrefundlineitems->lineitem_id = $value['line_item_id'];
                        $Spyrefundlineitems->order_id = $order_id;
                        $Spyrefundlineitems->refund_id = $refund_id;
                        $Spyrefundlineitems->seller_id = $spyConnected['id'];
                        $Spyrefundlineitems->spy_refund_id =$orderData['id'];
                        $Spyrefundlineitems->product_id = $value['line_item']['product_id'];
                        $Spyrefundlineitems->variant_id = $value['line_item']['variant_id'];
                        $Spyrefundlineitems->sku = $value['line_item']['sku'];
                        $Spyrefundlineitems->title = $value['line_item']['title'];
                        $Spyrefundlineitems->quantity = $value['line_item']['quantity'];
                        $Spyrefundlineitems->price = $value['line_item']['price'];
                        $Spyrefundlineitems->save();                      
                    }                        
                }
                
            }
        }
    }

    public function storeXerosummaryproductcostInDb($seller_id,$module,$product_id,$variant_id,$data){
        if(!empty($product_id)){

            $spylineitems = Xerosummaryproductcost::fetchLineItemsSingleData($seller_id,$module,$product_id, $variant_id);
            if (empty($spylineitems)) {
                $spylineitems = new Xerosummaryproductcost();                        
                $spylineitems->seller_id = $seller_id;
                $spylineitems->module = $module;
                $spylineitems->product_id = $product_id;
                $spylineitems->variant_id = $variant_id;
                $spylineitems->product_sku = $data['sku'];
                $spylineitems->product_name = $data['title'];
                $spylineitems->save();
            }
        }
    }
    public function editOrderFormat(&$orderData)
    {
        if (!empty($orderData['refunds'])) {
            foreach ($orderData['refunds'] as $key => $value) {
                if (empty($value['transactions']) && empty($value['order_adjustments']) && !empty($value['refund_line_items'])) {
                    foreach ($value['refund_line_items'] as $key1 => $value1) {
                        $no_restock = false;
                        // if($value1['restock_type'] == 'cancel'){
                        if (array_search($value1['line_item_id'], array_column($orderData['line_items'], 'id')) !== false) {
                            $lineItemKey = array_search($value1['line_item_id'], array_column($orderData['line_items'], 'id'));
                            $newqty      = $orderData['line_items'][$lineItemKey]['quantity'] - $value1['quantity'];
                            if ($value1['line_item']['total_discount'] && !empty($value1['line_item']['discount_allocations'])) {
                                foreach ($value1['line_item']['discount_allocations'] as $discountKey => $discountvalue) {
                                    $oneLineDiscount                                                                       = $discountvalue['amount'] / $orderData['line_items'][$lineItemKey]['quantity'];
                                    $newDiscount                                                                           = $oneLineDiscount * $newqty;
                                    $orderData['line_items'][$lineItemKey]['discount_allocations'][$discountKey]['amount'] = $newDiscount;
                                }
                            }
                            if ($value1['total_tax'] != 0 && !empty($value1['line_item']['tax_lines'])) {
                                foreach ($value1['line_item']['tax_lines'] as $taxKey => $taxvalue) {
                                    $oneLineTax                                                           = $taxvalue['price'] / $orderData['line_items'][$lineItemKey]['quantity'];
                                    $newTax                                                               = $oneLineTax * $newqty;
                                    $orderData['line_items'][$lineItemKey]['tax_lines'][$taxKey]['price'] = $newTax;
                                }
                            }
                            $orderData['line_items'][$lineItemKey]['quantity'] = $newqty;
                            if ($orderData['line_items'][$lineItemKey]['quantity'] == 0) {
                                if ($value1['restock_type'] == 'no_restock') {
                                    $no_restock                                        = true;
                                    $orderData['line_items'][$lineItemKey]['quantity'] = $value1['quantity'];
                                    $orderData['line_items'][$lineItemKey]['price']    = 0;
                                } else {
                                    unset($orderData['line_items'][$lineItemKey]);
                                }

                            }
                            if ($value1['restock_type'] == 'no_restock' && $no_restock == false) {
                                $line_items                         = $orderData['line_items'][$lineItemKey];
                                $line_items['quantity']             = $value1['quantity'];
                                $line_items['price']                = 0;
                                $line_items['discount_allocations'] = array();
                                $line_items['tax_lines']            = array();
                                array_push($orderData['line_items'], $line_items);
                            }
                            if ($orderData['total_tax'] != 0 && isset($value1['total_tax']) && !empty($value1['total_tax'])) {
                                $orderData['total_tax'] = $orderData['total_tax'] - $value1['total_tax'];
                            }

                            $orderData['line_items'] = array_values($orderData['line_items']);
                        }
                        // }
                    }
                    unset($orderData['refunds'][$key]);
                }
            }
        }
    }
    public function updateOrderDataInDb($spyConnected, $orderData, $settingData = array())
    {
        $spyStoreObj = Spysummaryorder::fetchSpyOrderSingleData("order_id", $orderData['id'], $spyConnected["id"]);
        //pr($spyStoreObj,1);
        if (!empty($spyStoreObj)) {
            $sales_data = array();
            $updated_at = (new DateTime($orderData['updated_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
            if ($spyStoreObj->order_updated_at != $updated_at) {

                $this->editOrderFormat($orderData);

            $spyStoreObj->order_id = $orderData['id'];

            if (!empty($orderData['email'])) {
                $spyStoreObj->email = $orderData['email'];
            }

            if (!empty($orderData['created_at'])) {
                $spyStoreObj->order_created_at = (new DateTime($orderData['created_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
            }

            if (!empty($orderData['updated_at'])) {
                $spyStoreObj->order_updated_at = (new DateTime($orderData['updated_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
            }

            if (!empty($orderData['number'])) {
                $spyStoreObj->number = $orderData['number'];
            }

            if (!empty($orderData['gateway'])) {
                $spyStoreObj->gateway = $orderData['gateway'];
            }

          if (!empty($orderData['total_price'])) {
                $spyStoreObj->total_price = $orderData['total_price'];
            }
            if(isset($orderData['current_total_price']) && !empty($orderData['current_total_price'])){
                $spyStoreObj->current_total_price = $orderData['current_total_price'];
            }

            if (!empty($orderData['subtotal_price'])) {
                $spyStoreObj->subtotal_price = $orderData['subtotal_price'];
            }

            if (!empty($orderData['total_tax'])) {
               
                $spyStoreObj->total_tax = $orderData['total_tax'];
            }

            if (!empty($orderData['taxes_included'])) {
                $spyStoreObj->taxes_included = $orderData['taxes_included'];
            }

            if (!empty($orderData['currency'])) {
                $spyStoreObj->currency = $orderData['currency'];
            }

            if (!empty($orderData['financial_status'])) {
                $spyStoreObj->financial_status = $orderData['financial_status'];
            }

            if (!empty($orderData['total_discounts'])) {
               
                $spyStoreObj->total_discounts = $orderData['total_discounts'];
               
            }

            if (!empty($orderData['total_line_items_price'])) {
                $spyStoreObj->total_line_items_price = $orderData['total_line_items_price'];
            }

            if (!empty($orderData['name'])) {
                $spyStoreObj->name = $orderData['name'];
            }

            if (!empty($orderData['cancelled_at'])) {
                $spyStoreObj->cancelled_at = (new DateTime($orderData['cancelled_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
            }

            if (!empty($orderData['processed_at'])) {
                $spyStoreObj->processed_at = (new DateTime($orderData['processed_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
            }

            if (!empty($orderData['order_number'])) {
                $spyStoreObj->order_number = $orderData['order_number'];
            }

            if (!empty($orderData['payment_gateway_names'])) {
                $spyStoreObj->payment_gateway_names = json_encode($orderData['payment_gateway_names']);
            }

            if (!empty($orderData['source_name'])) {
                $spyStoreObj->source_name = $orderData['source_name'];
            }

            if (!empty($orderData['fulfillment_status'])) {
                $spyStoreObj->fulfillment_status = $orderData['fulfillment_status'];
            }

            if (!empty($orderData['presentment_currency'])) {
                $spyStoreObj->presentment_currency = $orderData['presentment_currency'];
            }

            if (!empty($orderData['reference'])) {
                $spyStoreObj->reference = $orderData['reference'];
            }

            if (!empty($orderData['location_id'])) {
                $spyStoreObj->location_id = $orderData['location_id'];
            }
            
            if (!empty($orderData['source_identifier'])) {
                $spyStoreObj->source_identifier = $orderData['source_identifier'];
            }
            
            if (!empty($orderData['processing_method'])) {
                $spyStoreObj->processing_method = $orderData['processing_method'];
            }
            if (!empty($orderData['billing_address']) && !empty($orderData['billing_address']['province_code']) && !empty($orderData['billing_address']['country_code'])) {
                $spyStoreObj->billing_country_code = $orderData['country_code'];
                $spyStoreObj->billing_province_code = $orderData['province_code'];
            }
            if (!empty($orderData['shipping_address']) && !empty($orderData['shipping_address']['province_code']) && !empty($orderData['shipping_address']['country_code'])) {
                $spyStoreObj->shipping_country_code = $orderData['country_code'];
                $spyStoreObj->shipping_province_code = $orderData['province_code'];
            }

            if (!empty($orderData['tags'])) {
                $spyStoreObj->tags = $orderData['tags'];
            }

            if (!empty($orderData['line_items'])) {
                foreach ($orderData['line_items'] as $key => $value) {
                    $discountAmt = 0;
                    $LineItemAmtValue = $value['quantity'] * $value['price'];
                    foreach(@$value['discount_allocations'] as $discount)
                    {
                        if(isset($discount['amount']))
                        {
                            $discountAmt +=  $discount['amount'];
                        }
                    }
                    $taxAmountLine = 0;
		            $taxRate = 0;
                    foreach ($value['tax_lines'] as $key1 => $value1) 
                    {
                        if($value1['price'] > 0){
                          $taxAmountLine = $taxAmountLine + $value1['price'];
                          $taxRate = $taxRate + $value1['rate'];
                        }
                    }
                    if(is_null($orderData['taxes_included']) && $orderData['total_tax'] != 0)
                    {
                      $LineItemAmtValue = $LineItemAmtValue + $taxAmountLine;
                    }
                    if(isset($sales_data[$taxRate]) && !empty($sales_data[$taxRate])){
                        $sales_data[$taxRate]['order']['price'] += $LineItemAmtValue;
                        $sales_data[$taxRate]['order']['taxprice'] += $taxAmountLine;
                        $sales_data[$taxRate]['order']['discount'] += $discountAmt;
                    }
                    else{
                        $sales_data[$taxRate]['order']['price'] = $LineItemAmtValue;
                        $sales_data[$taxRate]['order']['taxprice'] = $taxAmountLine;  
                        $sales_data[$taxRate]['order']['discount'] = $discountAmt;  
                    }
                    foreach ($value['duties'] as $dutieskey => $dutiesval) {
                        if(isset($sales_data[$taxRate]) && !empty($sales_data[$taxRate]) && isset($sales_data[$taxRate]['duties']) && !empty($sales_data[$taxRate]['duties']) ){
                            $sales_data[$taxRate]['duties']['amount'] += $dutiesval['price_set']['shop_money']['amount'];
                            if(!empty($dutiesval['tax_lines'])){
                                foreach ($dutiesval['tax_lines'] as $dutiestaxval) {
                                    $sales_data[$taxRate]['duties']['tax'] += $dutiestaxval['price'];
                                }
                            }
                        }
                        else{
                            $sales_data[$taxRate]['duties']['amount'] = $dutiesval['price_set']['shop_money']['amount'];
                            if(!empty($dutiesval['tax_lines'])){
                                foreach ($dutiesval['tax_lines'] as $dutiestaxval) {
                                    $sales_data[$taxRate]['duties']['tax'] = $dutiestaxval['price'];  
                                }
                            }
                        }
                        if ($value['gift_card'] == true) {
                            $spyStoreObj->total_giftcard += $value['price'];
                        }
                    }
                    if ($value['gift_card'] == true) {
                        $spyStoreObj->total_giftcard += $value['price'];
                    }
                }
            }
            $paymentData = $this->fetchPaymentsFromShopify($spyConnected,$orderData['id']);
            if(!empty($paymentData)){
                if (!empty($orderData['payment_gateway_names']) && in_array("gift_card", $orderData['payment_gateway_names'])) {
                    //fetch transaction
                    $paymentTemp = $paymentData;
                    foreach ($paymentData['transactions'] as $key => $value) {
                        if($value['gateway'] == "gift_card"  && $value['status'] =='success' && ($value['kind'] =='capture' || $value['kind'] =='sale' || $value['kind'] =='refund') && $orderData['financial_status'] != 'refunded' && $orderData['financial_status'] != 'partially_refunded')
                        {
                            if(array_search($value['id'], array_column($paymentData['transactions'], 'parent_id')) !== false) {
                                $key1 =array_search($value['id'], array_column($paymentData['transactions'], 'parent_id'));
                                if($value['amount'] == $paymentData['transactions'][$key1]['amount']){
                                    unset($paymentTemp['transactions'][$key]);
                                    unset($paymentTemp['transactions'][$key1]);                  
                                }
                            }    
                        }
                    }
                    $paymentTemp = array_values($paymentTemp['transactions']);
                    if(!empty($paymentTemp)){
                        foreach ($paymentTemp as $key => $value) {
                            if($value['gateway'] == "gift_card" && $value['status'] == 'success' && ($value['kind'] =='capture' || $value['kind'] =='sale')){
                                $spyStoreObj->total_giftcard -= $value['amount'];
                            }
                        }
                    }

                }
                $exchange_rate = NULL;
                if($orderData['currency'] != $orderData['presentment_currency']){
                    $paymentexchangerate = array();
                    foreach ($paymentData['transactions'] as $keypay => $valuepay) {
                        if($valuepay['status'] =='success' && ($valuepay['kind'] =='capture' || $valuepay['kind'] =='sale')){
                            $paymentexchangerate[] = $valuepay; 
                        }
                    }
                    if(!empty($paymentexchangerate)){
                        $paymentDot = Arr::dot($paymentexchangerate);
                        foreach ($paymentDot as $dotkey => $dotvalue) {
                            if(stripos($dotkey, "exchange_rate") !== false && $orderData['gateway'] == 'shopify_payments'){
                                $exchange_rate = $dotvalue;
                            }
                        }
                    }
                }
                 foreach ($paymentData['transactions'] as $value) {                    
                    $spypayObj = Spyordertransaction::fetchTransactionSingleData('transaction_id', $value['id'], $spyConnected['id']);
                    if (empty($spypayObj)) {
                        $spypayObj = new Spyordertransaction();                        
                        $spypayObj->seller_id = $spyConnected['id'];
                    }
                    $spypayObj->order_id = $value['order_id'];
                    $spypayObj->transaction_id = $value['id'];
                    $spypayObj->kind = $value['kind'];
                    $spypayObj->gateway = $value['gateway'];
                    $spypayObj->status = $value['status'];
                    $spypayObj->transaction_created_at = (new DateTime($value['created_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
                    $spypayObj->amount = $value['amount'];
                    $spypayObj->currency = $value['currency'];
                    $spypayObj->exchange_rate = $exchange_rate;
                    $spypayObj->save();
                }
            }

            if (!empty($orderData['shipping_lines'])) {
                foreach ($orderData['shipping_lines'] as $key => $value) {
                    $spyStoreObj->total_shipping += $value['price'];
		    $taxAmountLine = 0;
		    $taxRate=0;
                    foreach ($value['tax_lines'] as $keytax => $valuetax) {
                        if($valuetax['price'] > 0){
                            $spyStoreObj->total_shipping_tax += $valuetax['price'];
                            $taxAmountLine = $taxAmountLine + $valuetax['price'];
                            $taxRate = $taxRate + $valuetax['rate'];
                            $spyStoreObj->total_tax = $spyStoreObj->total_tax - $valuetax['price'];
                        }
                    }
                    $LineItemAmtValue = $value['price'];
                    $discountAmt = 0;
                    foreach(@$value['discount_allocations'] as $discount)
                    {
                        if(isset($discount['amount']))
                        {
                            $discountAmt +=  $discount['amount'];
                        }
                    }
                    if(isset($sales_data[$taxRate]) && !empty($sales_data[$taxRate]) && isset($sales_data[$taxRate]['shipping']['price'])){
                        $sales_data[$taxRate]['shipping']['price'] += $LineItemAmtValue;
                        $sales_data[$taxRate]['shipping']['taxprice'] += $taxAmountLine;
                        $sales_data[$taxRate]['shipping']['discount'] += $discountAmt;
                    }
                    else{
                        $sales_data[$taxRate]['shipping']['price'] = $LineItemAmtValue;
                        $sales_data[$taxRate]['shipping']['taxprice'] = $taxAmountLine;  
                        $sales_data[$taxRate]['shipping']['discount'] = $discountAmt;  
                    }
                }
            }

            if (!empty($orderData['app_id'])) {
                $spyStoreObj->app_id = $orderData['app_id'];
            }

            if (!empty($orderData['total_tip_received'])) {
                $spyStoreObj->total_tip_received = $orderData['total_tip_received'];
            }

            $spyStoreObj->seller_id = $spyConnected["id"];
            $spyStoreObj->save();

            if (!empty($orderData['refunds']) && !in_array('shopify_payments', $orderData['payment_gateway_names'])) {
                foreach ($orderData['refunds'] as $key => $value) {
                    if (!empty($value['transactions'])) {
                        foreach ($value['transactions'] as $keyTrs => $valueTrs) {
                            if (isset($valueTrs['status']) && ($valueTrs['status'] == 'pending' || $valueTrs['status'] == 'failure' || $valueTrs['status'] == 'error')) {
                                unset($orderData['refunds'][$key]['transactions'][$keyTrs]);
                            }
                        }
                        if (empty($value['refund_line_items']) && empty($value['order_adjustments'])) {
                            unset($orderData['refunds'][$key]);
                        }
                    } else {
                        unset($orderData['refunds'][$key]);
                    }
                    if (empty($orderData['refunds'][$key]['transactions'])) {
                        unset($orderData['refunds'][$key]);
                    }
                }
                $refunds = array_values($orderData['refunds']);
                if (!empty($refunds) ) {
                    foreach ($refunds as $key => $value) {
                        $spyRefObj = Spysummaryrefund::fetchSpyRefundSingleData('refund_id', $value['id'], $spyConnected['id']);
                        if (empty($spyRefObj)) {
                            $spyRefObj                        = new Spysummaryrefund();
                            $spyRefObj->order_id              = $value['order_id'];
                            $spyRefObj->refund_id             = $value['id'];
                            if (isset($value['refund_line_items']) && !empty($value['refund_line_items'])) {
                                foreach ($value['refund_line_items'] as $keyLI => $valueLI) {
                                    $spyRefObj->total_refund += $valueLI['subtotal'];
                                    $spyRefObj->total_refund_tax += $valueLI['total_tax'];
                                }
                            }
                            if (!empty($orderData['payment_gateway_names']) ) {
                                if (isset($value['transactions']) && !empty($value['transactions'])) {
                                    foreach ($value['transactions'] as $keyTRS => $valueTRS) {
                                        if ($valueTRS['gateway'] == 'gift_card') {
                                             $spyRefObj->total_refund_giftcard += $valueTRS['amount'];
                                        }
                                        $spyRefObj->gateway = $valueTRS['gateway'];
                                        $trasData[$keyTRS]['order_id']       = $valueTRS['order_id'];
                                        $trasData[$keyTRS]['processed_at'] = (new DateTime($valueTRS['processed_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
                                        $trasData[$keyTRS]['kind']           = $valueTRS['kind'];
                                        $trasData[$keyTRS]['gateway']        = $valueTRS['gateway'];
                                        $trasData[$keyTRS]['status']         = $valueTRS['status'];
                                        $trasData[$keyTRS]['currency']       = $valueTRS['currency'];
                                        $trasData[$keyTRS]['amount']         = $valueTRS['amount'];
                                        $spyRefObj->transaction_details = json_encode($trasData);
                                    }
                                }
                            }
                            if (isset($value['order_adjustments']) && !empty($value['order_adjustments'])) {
                                foreach ($value['order_adjustments'] as $keyOA => $valueOA) {
                                    if ($valueOA['kind'] == 'refund_discrepancy') {
                                        $spyRefObj->total_refund_discrepancy += $amt;
                                        $spyRefObj->total_refund_discrepancy_tax += $txtAmt;
                                    }
                                    if ($valueOA['kind'] == 'shipping_refund') {
                                        $spyRefObj->total_refund_shipping += $valueOA['amount'] * (-1);
                                        $spyRefObj->total_refund_shipping_tax += $valueOA['tax'] * (-1);
                                    }
                                }

                            }
                            $spyRefObj->processed_at = (new DateTime($value['processed_at']))->setTimezone(new DateTimeZone($spyConnected['spy_timezone']))->format('Y-m-d H:i:s');
                            $spyRefObj->seller_id     = $spyConnected['id'];
                            $spyRefObj->save();
                        }

                    }
                }

            }

            return $spyStoreObj;
            } else {
                return $spyStoreObj;
            }
        } else {
            return false;
        }
    }
    public function fetchOrderSpyToDb(Request $request)
    {
        if (!empty($request->get('shop')) && !empty($request->get('orderDate'))) {

            $xrConnected = array();
            $xrConnected = Xerocredential::checkXeroConnected('store_domain', $request->get("shop"));
            if (!empty($xrConnected)) {
                //$SpySettingData = XeroSettings::fetchXeroSingleData("seller_id",$xrConnected["seller_id"]);
                $orderFirstDate = Spysummaryorder::where("seller_id", $xrConnected["seller_id"])
                    ->orderBy("processed_at", "ASC")
                    ->limit(1)
                    ->first();

                if (!empty($request->get('orderEndDate')) && $request->get('orderEndDate') != '') {
                    $lastDate = date('Y-m-d', strtotime($request->get('orderEndDate')));
                } else if (!empty($orderFirstDate)) {
                    $lastDate = date("Y-m-d", strtotime($orderFirstDate->processed_at));
                } else {
                    $lastDate = (new DateTime(date('Y-m-d')))->setTimezone(new DateTimeZone($xrConnected['spy_timezone']))->format('Y-m-d');
                }

                $firstStart = true;
                $LastId     = "";
                $nextUrl    = '';
                $orderType    = 'create';
                do {
                    $orderResponse = $this->fetchOldOrderFromShopify($xrConnected, $request->get("shop"), $nextUrl, $request->get('orderDate'), $lastDate);
                    $nextUrl       = $orderResponse['url'];
                    $orderData     = $orderResponse['data'];
                    if (!empty($orderData['orders'])) {
                        $insertFlg = true;

                        foreach ($orderData['orders'] as $key => $value) {
                            $firstStart = false;
                            $LastId     = $value['id'];

                            $processed_at = (new DateTime($value['processed_at']))->setTimezone(new DateTimeZone($xrConnected['spy_timezone']))->format('Y-m-d H:i:s');

                            if (date("Y-m-d", strtotime($processed_at)) >= $request->get('orderDate') && $value['financial_status'] != "voided") {
                                if ($request->get('random') == '1') {
                                    if (in_array($value['name'], config('ids.' . $xrConnected["seller_id"]))) {
                                        $this->cronActionLog($xrConnected["seller_id"], "fetchOrderSpyToDb Cron Old Order Data", $value['id']);
                                        //$value['back']=true;
                                        $spyStoreObj = $this->createUpdateOrderDataInDb($xrConnected, $value,$orderType,"");
                                    }
                                } else {
                                    $this->cronActionLog($xrConnected["seller_id"], "fetchOrderSpyToDb Cron Old Order Data", $value['id']);
                                    //$value['back']=true;
                                    $spyStoreObj = $this->createUpdateOrderDataInDb($xrConnected, $value,$orderType,"");
                                }
                            }
                        }
                    }
                } while ($nextUrl != '');
            }
        }
        echo "success";
        exit;
    }
    private function fetchOldOrderCountFromShopify($xrConnected, $shop, $lastDate, $spyOldDate, $count = null)
    {

        $shopUrl = "https://" . $shop . "/admin/" . config('app.shopify_version') . "/orders/count.json?status=any&processed_at_min=" . $spyOldDate . "&processed_at_max=" . $lastDate;

        $result        = app('App\Http\Controllers\Ecomtoacc\Shopify\ApiController')::shop_curl_request_call($shopUrl, $xrConnected['store_access_token']);
        $orderResponse = json_decode($result, true);
        if ($count != null) {
            return @$orderResponse['count'];
        } else {
            $numOfPagination = @$orderResponse['count'] / config("app.orderPaginationLimit");
            return ceil($numOfPagination);
        }
    }
    public function fetchOldOrderFromShopify($xrConnected, $shop, $nextUrl = '', $spyOldDate, $lastDate)
    {
        if ($nextUrl == '') {
            $shopUrl = "https://" . $shop . "/admin/" . config('app.shopify_version') . "/orders.json?status=any&processed_at_min=" . $spyOldDate . "&processed_at_max=" . $lastDate . "&since_id=1&limit=" . config("app.orderPaginationLimit");
        } else {
            $shopUrl = $nextUrl;
        }
        $result                  = app('App\Http\Controllers\Ecomtoacc\Shopify\ApiController')::shop_curl_request_call_header($shopUrl, $xrConnected['store_access_token']);
        $productResponse['url']  = $result['url'];
        $productResponse['data'] = json_decode($result['data'], true);
        return $productResponse;
    }
    private function fetchOrderByIdFromShopify($xrConnected, $shop, $order_id)
    {
        $shopUrl = "https://" . $shop . "/admin/" . config('app.shopify_version') . "/orders/".$order_id.".json?status=any";
        $result                  = app('App\Http\Controllers\Ecomtoacc\Shopify\ApiController')::shop_curl_request_call_header($shopUrl, $xrConnected['store_access_token']);
        $data = json_decode($result['data'], true);

        if(!empty($data['order'])){
            $productResponse['url']  = $result['url'];
            $productResponse['data']['orders'][] = $data['order'];
        }else{
            $productResponse['url']  ="";
            $productResponse['data'] ="";
        }
      
        return $productResponse;
    }

    public function calculateShopifyFee($summary){
        $summary = json_decode($summary,true);
        $feeAmoutn = $summary['charges_fee_amount'] + $summary['adjustments_fee_amount'] + $summary['refunds_fee_amount'] + $summary['reserved_funds_fee_amount'] + $summary['retried_payouts_fee_amount'];
        return $feeAmoutn;
    }
    public function fetchPaymentsFromShopify($spyConnected, $id)
    {
        $shopUrl = "https://" . $spyConnected['store_domain'] . "/admin/" . config('app.shopify_version') . "/orders/" . $id . "/transactions.json";
        $result  = app('App\Http\Controllers\Ecomtoacc\Shopify\ApiController')::shop_curl_request_call($shopUrl, $spyConnected['store_access_token']);
        $orderResponse = json_decode($result, true);
       
        return $orderResponse;
    }
    public function formatOrderData($orderData){
        $formatedData = array();
        $salesData = array();
        $formatedData['total_sale'] = 0;
        $formatedData['total_tax'] = 0;
        $formatedData['total_shipping'] = 0;
        $formatedData['total_shipping_tax'] = 0;
        $formatedData['total_tip_received'] = 0;
        $formatedData['total_discounts'] = 0;
        $formatedData['total_giftcard'] = 0;

        foreach ($orderData as $key => $value) {
            $formatedData['total_sale'] = $formatedData['total_sale'] + $value['total_line_items_price'];
            $formatedData['total_tax'] = $formatedData['total_tax'] + $value['total_tax'];
            $formatedData['total_shipping'] = $formatedData['total_shipping'] + $value['total_shipping'];
            $formatedData['total_shipping_tax'] = $formatedData['total_shipping_tax'] + $value['total_shipping_tax'];
            $formatedData['total_tip_received'] = $formatedData['total_tip_received'] + $value['total_tip_received'];
            $formatedData['total_discounts'] = $formatedData['total_discounts'] + $value['total_discounts'];
            $formatedData['total_giftcard'] = $formatedData['total_giftcard'] + $value['total_giftcard'];
            if(isset($value['sales_data']) && !empty($value['sales_data']) ){
                $data = json_decode($value['sales_data'],true);
                foreach ($data as $key1 => $value1) {
                    if(isset($value1['order'])){
                        (!isset($salesData[$key1]['order']['amount'])) ?
                            $salesData[$key1]['order']['amount'] = $value1['order']['amount'] :
                            $salesData[$key1]['order']['amount'] += $value1['order']['amount'];
                        (!isset($salesData[$key1]['order']['tax'])) ?
                            $salesData[$key1]['order']['tax'] = $value1['order']['tax'] :
                            $salesData[$key1]['order']['tax'] += $value1['order']['tax'];
                        (!isset($salesData[$key1]['order']['discount'])) ?
                            $salesData[$key1]['order']['discount'] = $value1['order']['discount'] :
                            $salesData[$key1]['order']['discount'] += $value1['order']['discount'];
                    }

                    if(isset($value1['shipping'])){
                        (!isset($salesData[$key1]['shipping']['amount'])) ?
                            $salesData[$key1]['shipping']['amount'] = $value1['shipping']['amount'] :
                            $salesData[$key1]['shipping']['amount'] += $value1['shipping']['amount'];
                        (!isset($salesData[$key1]['shipping']['tax'])) ?
                            $salesData[$key1]['shipping']['tax'] = $value1['shipping']['tax'] :
                            $salesData[$key1]['shipping']['tax'] += $value1['shipping']['tax'];
                        (!isset($salesData[$key1]['shipping']['discount'])) ?
                            $salesData[$key1]['shipping']['discount'] = $value1['shipping']['discount'] :
                            $salesData[$key1]['shipping']['discount'] += $value1['shipping']['discount'];
                    }
                }
            }
        }
        $formatedData['salesData'] = $salesData;
        return $formatedData;
    }
    public function formatRefundData($orderData){
        $formatedData = array();
        $salesData = array();
        $formatedData['total_refund'] = 0;
        $formatedData['total_refund_tax'] = 0;
        $formatedData['total_refund_shipping'] = 0;
        $formatedData['total_refund_shipping_tax'] = 0;
        $formatedData['total_refund_discrepancy'] = 0;
        $formatedData['total_refund_discrepancy_tax'] = 0;
        $formatedData['total_refund_giftcard'] = 0;

        foreach ($orderData as $key => $value) {
            $formatedData['total_refund'] = $formatedData['total_refund'] + $value['total_refund'];
            $formatedData['total_refund_tax'] = $formatedData['total_refund_tax'] + $value['total_refund_tax'];
            $formatedData['total_refund_shipping'] = $formatedData['total_refund_shipping'] + $value['total_refund_shipping'];
            $formatedData['total_refund_shipping_tax'] = $formatedData['total_refund_shipping_tax'] + $value['total_refund_shipping_tax'];
            $formatedData['total_refund_discrepancy'] = $formatedData['total_refund_discrepancy'] + $value['total_refund_discrepancy'];
            $formatedData['total_refund_discrepancy_tax'] = $formatedData['total_refund_discrepancy_tax'] + $value['total_refund_discrepancy_tax'];
            $formatedData['total_refund_giftcard'] = $formatedData['total_refund_giftcard'] + $value['total_refund_giftcard'];
            if(isset($value['sales_data']) && !empty($value['sales_data']) ){
                $data = json_decode($value['sales_data'],true);
                foreach ($data as $key1 => $value1) {
                    if(isset($value1['refund'])){
                        (!isset($salesData[$key1]['refund']['amount'])) ?
                            $salesData[$key1]['refund']['amount'] = $value1['refund']['amount'] :
                            $salesData[$key1]['refund']['amount'] += $value1['refund']['amount'];

                        (!isset($salesData[$key1]['refund']['tax'])) ?
                            $salesData[$key1]['refund']['tax'] = $value1['refund']['tax'] :
                            $salesData[$key1]['refund']['tax'] += $value1['refund']['tax'];
                    }

                    if(isset($value1['refund_discrepancy'])){
                        (!isset($salesData[$key1]['refund_discrepancy']['amount'])) ?
                            $salesData[$key1]['refund_discrepancy']['amount'] = $value1['refund_discrepancy']['amount'] :
                            $salesData[$key1]['refund_discrepancy']['amount'] += $value1['refund_discrepancy']['amount'];
                        
                        (!isset($salesData[$key1]['refund_discrepancy']['tax'])) ?
                            $salesData[$key1]['refund_discrepancy']['tax'] = $value1['refund_discrepancy']['tax'] :
                            $salesData[$key1]['refund_discrepancy']['tax'] += $value1['refund_discrepancy']['tax'];
                    }

                    if(isset($value1['refund_shipping'])){
                        (!isset($salesData[$key1]['refund_shipping']['amount'])) ?
                            $salesData[$key1]['refund_shipping']['amount'] = $value1['refund_shipping']['amount'] :
                            $salesData[$key1]['refund_shipping']['amount'] += $value1['refund_shipping']['amount'];

                        (!isset($salesData[$key1]['refund_shipping']['tax'])) ?
                            $salesData[$key1]['refund_shipping']['tax'] = $value1['refund_shipping']['tax'] :
                            $salesData[$key1]['refund_shipping']['tax'] += $value1['refund_shipping']['tax'];
                    }
                }
            }
        }
        $formatedData['salesData'] = $salesData;
        return $formatedData;
    }
    public function storeRefundsDataInDb($xeroConnected,$refundData,$orderData,$sync_start_date="",$orderType="",$cogs_enable="",$orderTbID="",$fetchBackDateData=false,$SpySettingData="")
    {
        if (!empty($refundData['refunds'])) {
            $sales_data = array();
            foreach ($refundData['refunds'] as $keyref => $valueref) {
                if (!empty($valueref['transactions'])) {
                    foreach ($valueref['transactions'] as $keyTrs => $valueTrs) {
                        if (isset($valueTrs['status']) && ($valueTrs['status'] == 'pending' || $valueTrs['status'] == 'failure' || $valueTrs['status'] == 'error')) {
                            unset($refundData['refunds'][$keyref]['transactions'][$keyTrs]);
                        }
                    }
                  
                } else {
                    unset($refundData['refunds'][$keyref]);
                }
                if (empty($refundData['refunds'][$keyref]['transactions'])) {
                    unset($refundData['refunds'][$keyref]);
                }
            }
            $refunds = array_values($refundData['refunds']);
            if (!empty($refunds)) {
                foreach ($refunds as $valueref) {
                    $totalAmt = 0;
                    $total_refund_giftcard=0;

                    $sales_data =$cost_data= array();
                    $refundtransDate = (new DateTime($valueref['processed_at']))->setTimezone(new DateTimeZone($xeroConnected['spy_timezone']))->format('Y-m-d');
                   
                   // //Log::info("Spysummaryrefund Data ---" .$sync_start_date. "-----" ."--store Id" . $refundtransDate);
                    
                    if (($sync_start_date <= $refundtransDate) || ($fetchBackDateData)) {
                        $this->formatRefundDisprancyToOneAmount($orderData,$valueref);
                        $spyRefObj = Spysummaryrefund::fetchSpyRefundSingleData('refund_id', $valueref['id'], $xeroConnected['id'],$xeroConnected['module']);

                            if (empty($spyRefObj)) {
                                $spyRefObj                        = new Spysummaryrefund();
                            }
                            $spyRefObj->order_id              = $valueref['order_id'];
                            $spyRefObj->refund_id             = $valueref['id'];
                            $spyRefObj->module = $xeroConnected['module'];
                            if (empty($valueref['refund_line_items']) && empty($valueref['order_adjustments'])) {
                                if (isset($valueref['transactions']) && !empty($valueref['transactions'])) {
                                    $trasData = array();
                                    $traamt = 0;
                                    $taxRate = 0;
                                    $taxRate = (string) $taxRate;
                                    foreach ($valueref['transactions'] as $keyTRS => $valueTRS) {
                                        $traamt += $valueTRS['amount'];
                                    }
                                    //$spyRefObj->total_refund_discrepancy = $traamt;
                                    $sales_data[$taxRate]['refund_discrepancy']['amount'] = $traamt;
                                    $sales_data[$taxRate]['refund_discrepancy']['tax'] = 0;
                                    $totalAmt += $traamt;
                                }
                            }
                            $spyRefObj->currency = $orderData['currency'];
                            if (isset($valueref['refund_line_items']) && !empty($valueref['refund_line_items'])) {
                                $total_refund=$total_refund_tax=0;
                                foreach ($valueref['refund_line_items'] as $keyLI => $valueLI) {
                                    if(isset($valueLI['line_item']['gift_card']) && $valueLI['line_item']['gift_card']==true){
                                        $total_refund_giftcard -= $valueLI['line_item']['price'];
                                    }else{

                                        $total_refund += $valueLI['subtotal'];
                                        $total_refund_tax += $valueLI['total_tax'];
                                        $totalAmt += $valueLI['subtotal'];
                                        if (!empty($orderData) && isset($orderData['taxes_included']) && is_null($orderData['taxes_included']))
                                        $totalAmt += $valueLI['total_tax'];
                                        $taxRate = 0;
                                        $taxAmountLine = 0;
                                        foreach ($valueLI['line_item']['tax_lines'] as $key1 => $value1) {
                                            if ($value1['price'] > 0) {
                                                $taxAmountLine += $value1['price'];
                                                $taxRate = $taxRate + $value1['rate'];
                                            }
                                        }
                                        $taxRate = $taxRate * 100;
                                        $taxRate = (string) $taxRate;
                                        if (isset($sales_data[$taxRate]) && !empty($sales_data[$taxRate]) && isset($sales_data[$taxRate]['refund'])) {
                                            $sales_data[$taxRate]['refund']['amount'] += $valueLI['subtotal'];
                                            $sales_data[$taxRate]['refund']['tax'] +=$valueLI['total_tax'];
                                        } else {
                                            $sales_data[$taxRate]['refund']['amount'] = $valueLI['subtotal'];
                                            $sales_data[$taxRate]['refund']['tax'] =$valueLI['total_tax'];
                                        }
                                    }
                               
                                }
                                $spyRefObj->total_refund = $total_refund;
                                $spyRefObj->total_refund_tax = $total_refund_tax;
                                if ($cogs_enable=="Yes") {
                                    $cost_data= $this->storeAndGetCost($xeroConnected,$SpySettingData,$valueLI['line_item'],$cost_data);
                                }
                                
                            }
                            if (isset($valueref['transactions']) && !empty($valueref['transactions'])) {
                                $trasData = array();
                                foreach ($valueref['transactions'] as $keyTRS => $valueTRS) {
                                    
                                    if ($valueTRS['gateway'] == 'gift_card') {
                                        $total_refund_giftcard += $valueTRS['amount'];
                                        $totalAmt -= $valueTRS['amount'];
                                    }
                                    if ($valueTRS['status'] == 'success') {
                                        $exchange_rate = NULL;
                                        $valueTRSDot = Arr::dot($valueTRS);
                                        foreach ($valueTRSDot as $dotkey => $dotvalue) {
                                            if (stripos($dotkey, "exchange_rate") !== false) {
                                                $exchange_rate = $dotvalue;
                                            }
                                        }
                                       $spyRefObj->refund_transaction_id = $valueTRS['id'];
                                       $trasData[$keyTRS]['id']       = $valueTRS['id'];
                                       $trasData[$keyTRS]['order_id']       = $valueTRS['order_id'];
                                       $trasData[$keyTRS]['processed_at'] = (new DateTime($valueTRS['processed_at']))->setTimezone(new DateTimeZone($xeroConnected['spy_timezone']))->format('Y-m-d H:i:s');
                                       $trasData[$keyTRS]['kind']           = $valueTRS['kind'];
                                       $trasData[$keyTRS]['gateway']        = $valueTRS['gateway'];
                                       $trasData[$keyTRS]['status']         = $valueTRS['status'];
                                       $trasData[$keyTRS]['currency']       = $valueTRS['currency'];
                                       $trasData[$keyTRS]['amount']         = $valueTRS['amount'];
                                       $trasData[$keyTRS]['exchange_rate']  = $exchange_rate;
                                    }
                                    $spyRefObj->gateway = $valueTRS['gateway'];
                                    $spyRefObj->presentment_currency = $valueTRS['currency'];
                                }
                                $spyRefObj->transaction_details = json_encode($trasData);
                            }
                            $spyRefObj->total_refund_giftcard = $total_refund_giftcard;
                            if (isset($valueref['order_adjustments']) && !empty($valueref['order_adjustments'])) {
                                $total_refund_discrepancy=$total_refund_discrepancy_tax=$total_refund_shipping=$total_refund_shipping_tax=0;
                                foreach ($valueref['order_adjustments'] as $keyOA => $valueOA) {
                                    $taxRate = 0;
                                    $amt = $valueOA['amount'] * (-1);
                                    $taxamt = $valueOA['tax_amount'] * (-1);
                                    $totalAmt += $amt;
                                    if (!empty($orderData) && isset($orderData['taxes_included']) && is_null($orderData['taxes_included']))
                                    $totalAmt += $taxamt;
                                    $taxRate = (string) abs($taxRate);
                                    if ($valueOA['kind'] == 'refund_discrepancy') {
                                        $total_refund_discrepancy += $amt;
                                        $total_refund_discrepancy_tax += $taxamt;
                                        if (isset($sales_data[$taxRate]) && !empty($sales_data[$taxRate]) && isset($sales_data[$taxRate]['refund_discrepancy'])) {
                                            $sales_data[$taxRate]['refund_discrepancy']['amount'] += $amt;
                                            $sales_data[$taxRate]['refund_discrepancy']['tax'] += $taxamt;
                                        } else {
                                            $sales_data[$taxRate]['refund_discrepancy']['amount'] = $amt;
                                            $sales_data[$taxRate]['refund_discrepancy']['tax'] = $taxamt;
                                        }
                                    }
                                    if ($valueOA['kind'] == 'shipping_refund') {
                                        if ($taxamt != 0
                                        ) {
                                            $taxRate = ($taxamt * 100) / $amt;
                                        }
                                        $taxRate = abs($taxRate);
                                        if ($taxRate != 0
                                        ) {
                                            if (!empty($settingsData['multi_tax_code'])) {
                                                $multitaxcodes = array_keys(json_decode($settingsData['multi_tax_code'], true));
                                                $taxRate = findNearest($taxRate, $multitaxcodes);
                                            } else {
                                                $taxRate = 0;
                                            }
                                        }
                                        $total_refund_shipping += $amt;
                                        $total_refund_shipping_tax += $taxamt;
                                        if (isset($sales_data[$taxRate]) && !empty($sales_data[$taxRate]) && isset($sales_data[$taxRate]['refund_shipping'])) {
                                            $sales_data[$taxRate]['refund_shipping']['amount'] += $amt;
                                            $sales_data[$taxRate]['refund_shipping']['tax'] += $taxamt;
                                        } else {
                                            $sales_data[$taxRate]['refund_shipping']['amount'] = $amt;
                                            $sales_data[$taxRate]['refund_shipping']['tax'] = $taxamt;
                                        }
                                    }
                                }
                                $spyRefObj->total_refund_shipping = $total_refund_shipping;
                                $spyRefObj->total_refund_shipping_tax = $total_refund_shipping_tax;
                                $spyRefObj->total_refund_discrepancy = $total_refund_discrepancy;
                                $spyRefObj->total_refund_discrepancy_tax = $total_refund_discrepancy_tax;
                            }else{
                                if (empty($valueref['refund_line_items']) && empty($valueref['order_adjustments'])) {
                                    $spyRefObj->total_refund_discrepancy = $totalAmt;
                                }
                            }
                            $spyRefObj->sales_data     = json_encode($sales_data);
                            if(!empty($cost_data) && $cost_data!=0)
                            $spyRefObj->cost_data     = json_encode($cost_data);
                            $spyRefObj->total_refund_amount = $totalAmt;
                            $spyRefObj->processed_at = (new DateTime($valueref['processed_at']))->setTimezone(new DateTimeZone($xeroConnected['spy_timezone']))->format('Y-m-d H:i:s');
                            $spyRefObj->seller_id     = $xeroConnected['id'];
                            if (!empty($orderData) && isset($orderData['taxes_included'])) {
                                $spyRefObj->taxes_included     = $orderData['taxes_included'];
                            }
                            $spyRefObj->save();
                            if($cogs_enable=="Yes")
                            $this->storeRefundLineItemsInDb($xeroConnected,$valueref,$orderTbID,$spyRefObj->id);

                    }                    

                }
            }
        }
    }
    private function fetchProductFromShopifyBypid($spyConnected,$SpySettingData,$orderData)
    {
        $shop=$spyConnected['store_domain'];
        $shopUrl = "https://" . $shop . "/admin/" . config('app.shopify_version') . "/products/".$orderData['product_id'].".json?status=draft,active&limit=" . config("app.productPaginationLimit");
        $result = app('App\Http\Controllers\Ecomtoacc\Shopify\ApiController')::shop_curl_request_call_header($shopUrl, $spyConnected['store_access_token']);
        $productResponse['url']  = $result['url'];
        $products = json_decode($result['data'], true);
        
        return $products['product'];
    }
    public function storeAndGetCost($spyConnected,$SpySettingData, $value,$cost_data)
    {
        list($xeroProduct, $cost_data) = Spylineitems::getCostfromXero($cost_data, $value['product_id'], $value['variant_id'], $value['sku'], $value['quantity'], $spyConnected['id'], $spyConnected['module']);
        if (empty($xeroProduct)) {
            //get variants by product id and get the cost from xero product table 
            $products =  $this->fetchProductFromShopifyBypid($spyConnected, $SpySettingData, $value);

            foreach ($products['variants'] as $key => $variants) {
                //store xero product cost
                app('App\Http\Controllers\Summary\ProductController')->storeProductDataInDb($spyConnected, $products, $variants, "order");
            }
            //get cost
            list($xeroProduct, $cost_data) = Spylineitems::getCostfromXero($cost_data, $value['product_id'], $value['variant_id'], $value['sku'], $value['quantity'], $spyConnected['id'], $spyConnected['module']);
        }
        return $cost_data;
    }
    
    public function formatRefundDisprancyToOneAmount($orderData,&$valueref)
    {
        $gatewayArray = array_map('strtolower', config('shopify.REFUNDGATEWAYINCLUDE'));
        if (in_array(strtolower($orderData['gateway']), $gatewayArray) && !empty($valueref['order_adjustments'])) {
            if (isset($valueref['transactions']) && !empty($valueref['transactions'])) {
                $amt = 0;
                foreach ($valueref['transactions'] as $tkey => $tvalue) {
                    $amt += $tvalue['amount'];
                }
            }

            $refunset = false;
            foreach ($valueref['order_adjustments'] as $keyref => $orderAdj) {
                $amt = number_format($amt, 4, ".", "");
                $refamt = abs($orderAdj['amount']);
                $refamt = number_format($refamt, 4, ".", "");
                $refamtTax = abs($orderAdj['tax_amount']);
                $refamtTax = number_format($refamtTax, 4, ".", "");
                if (!empty($valueref['refund_line_items'])) {
                    /// store id 809 order_id 4958396022978 refund array count 3 and same amount so this unset in this if
                    if ($orderAdj['kind'] == 'refund_discrepancy' && $amt == $refamt) {
                        unset($valueref['order_adjustments'][$keyref]);
                    }
                } else {
                    //seller_id:6529 ,order_id: 5163229053174 same transaction amount and refund sales amount+tax  same then unset refund discrepancy 
                    if ($orderAdj['kind'] == 'refund_discrepancy' && $amt==($refamt+$refamtTax)) {
                        unset($valueref['order_adjustments'][$keyref]);
                    }else if ($orderAdj['kind'] == 'refund_discrepancy' && $amt == $refamt && count($valueref['order_adjustments']) > 1 && ($orderAdj['amount'] > 0 || $refunset == true) ) {
                        unset($valueref['order_adjustments'][$keyref]);
                    } elseif ($amt == $refamt && count($valueref['order_adjustments']) > 1 && $orderAdj['kind'] == 'refund_discrepancy') {
                        $refunset = true;
                    }
                }
            }
        }
    }
}
