<?php

namespace App\Http\Controllers;


use App\Helpers\AppHelper;
use App\Http\Controllers\Controller;
use App\ListingVariant;
use App\Order;
use App\StoreCronJob;
use App\CronJob;
use App\ShopifyStore;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use PHPShopify;
use \DTS\eBaySDK\Trading\Services;
use \DTS\eBaySDK\Trading\Types;
use Carbon\Carbon;
// use App\Helpers\mail2user;

class OrderController extends Controller
{
    public $shopifyStore = null;
    public function __construct(Request $request)
    {
    }
    public function fulfillmentUpdateWebhook(Request $request)
    {
        $response = array();
        return response()->json($response, 200);
    }
    public function cancelOrderWebhook(Request $request)
    {
        $response = array();
        return response()->json($response, 200);
    }
    public function orderFulfilledWebhook(Request $request)
    {
        $response = array();
        return response()->json($response, 200);
    }
    public function deleteOrderWebhook(Request $request)
    {
        $response = array();
        return response()->json($response, 200);
    }
    public function index(Request $request)
    {
        $shopifyStore = AppHelper::getShopifyStore($request);
        if ($shopifyStore) {
            $per_page = 10;
            $sort_by = ($request->input("sort_by")) ? $request->input("sort_by") : "order_date";
            $sort_order = ($request->input("sort_order")) ? $request->input("sort_order") : "desc";
            $order_id = $request->input("orderid");
            $order_date = $request->input("orderdate");
            //$tags = $request->input("tags");
            $status = $request->input("status");
            $conditions = array();
            if ($order_id) {
                $conditions[] = array("order_id", "like", "%" . $order_id . "%");
            }

            if ($order_date) {
                $conditions[] = array("order_date", "like", "%" . $order_date . "%");
            }

            //if($sku) $conditions[] = array("shopify_product_data","like",'%:"'.$sku.'"%');
            if ($status) {
                $conditions[] = array("status", "=", $status);
            }

            $conditions[] = array("type", "!=", "shopify");
            $orders = array();
            if ($conditions) {
                $orders = $shopifyStore->orders()->where($conditions)->orderBy($sort_by, $sort_order)->paginate($per_page);
            } else {
                $orders = $shopifyStore->orders()->orderBy($sort_by, $sort_order)->paginate($per_page);
            }
            Log::info("orders " . json_encode($orders));
            if ($orders->count() > 0) {
                foreach ($orders as $okey => $order) {
                    $orders[$okey]->items = AppHelper::decryptData($order->items);
                    $orders[$okey]->order_data = AppHelper::decryptData($order->order_data);
                }
            }
            return response()->json($orders, 200);
        }
        return response()->json(['status' => 'error', 'msg' => "invalid request"], 403);
    }

    public function processshopifyorders()
    {
        
        $cronJob = CronJob::where('type', 'shopify_sync')->first();
        if ($cronJob && ($cronJob->flag == 1 || $cronJob->do_stop == 1)) {
            return response()->json(['status' => 'error', 'msg' => "cron already running"], 406);
        } else {
            $cronJob->flag = 1;
            $cronJob->started_at = date("Y-m-d H:i:s");
            $cronJob->ended_at = NULL;
            $cronJob->last_updated_at = date("Y-m-d H:i:s");
            $cronJob->save();
        }
        
        
        Log::channel('shopifyordersync')->info("entered in processshopifystoremethod method");
        $ebay_environment = config('ebay.environment');
        // $shopifyStores = ShopifyStore::where('status', 'active')->where('id', '1366')->get();
        // Conditions for importing orders
        $importconditions[] = array("inventory_sync", "=", 1);
        // Retrieving active Shopify stores with associated eBay accounts and matching import conditions
        $shopifyStores = ShopifyStore::with('ebayAccounts')->where('status', "active")->where('plan_id', '>', 1)->where('id',1245)->whereHas('ebayAccounts', function ($query) use ($importconditions) {$query->where($importconditions);})->get();
       
       
       
        // $shopifyStores = ShopifyStore::with('ebayAccounts')->where('status', "active")->where('plan_id', '>', 1)->where('id', '1366')->whereHas('ebayAccounts', function ($query) use ($importconditions) {$query->where($importconditions);})->get();
        // $shopifyStores = ShopifyStore::with('ebayAccounts')->where('status', "active")->whereHas('ebayAccounts', function ($query) use ($importconditions) {$query->where($importconditions);})->get();
        
        $userId = $shopifyStores->first()->user_id;
        $shopify_id = $shopifyStores->first()->id;
        $shopify_store_id = $shopifyStores->first()->shopify_store_id;
        
        echo "shopify store id". $shopify_id; echo "<br><br>";
        
        echo "shopify user  id". $userId; echo "<br><br>";
         
        echo "shopify     shopify_store_id id". $shopify_store_id; echo "<br><br>";

        Log::channel('shopifyordersync')->info("shopify id -> ". $shopify_id);
        Log::channel('shopifyordersync')->info("shopifyStores user id -> ". $userId);
        Log::channel('shopifyordersync')->info("shopify_store_id -> ". $shopify_store_id);
        Log::channel('shopifyordersync')->info("shopifyStores count order data ->". $shopifyStores->count());
          //die();

        if ($shopifyStores->count() > 0) {
            // Looping through each Shopify store
             Log::channel('shopifyordersync')->info("inside shopifyStores count" );
            foreach ($shopifyStores as $shopifyStore) {
                
                $shopify_store_id = $shopifyStore->id; // Getting the ID of the current Shopify store
                 Log::channel('shopifyordersync')->info("looping for store id $shopify_store_id" );
                $store_database_name = config('config.store_db_prefix') . $shopify_store_id; // Constructing the database name
                AppHelper::setConnection($store_database_name); // Setting the database connection
                // PHPShopify\ShopifySDK::config(array('ShopUrl' => $shopifyStore->shopify_url, 'AccessToken' => $shopifyStore->access_token, 'ApiVersion' => config('shopify.api_version'))); // Configuring Shopify SDK

                $config = array('ShopUrl' => $shopifyStore->shopify_url, 'AccessToken' => $shopifyStore->access_token, 'ApiVersion' => config('shopify.api_version'));
                $shopifyClient = new PHPShopify\ShopifySDK($config);
                //print_r($shopifyClient->ApiDeprecations() );
               // exit(0);
                Log::channel('shopifyordersync')->info("get shopifyClient");
                // TODO:: define globally shopifyOrders
                $shopifyOrders = []; // Declaring $shopifyOrders globally
                try {
                    Log::channel('shopifyordersync')->info("enter in try method and fetch shopify store account hereee"); // Logging an informational message

                    // Fetching orders from Shopify
                    if ($shopifyStore) {
                        // $currentTime = date("YYYY-MM-DD", strtotime('-1 days')); // Corrected time format

                        $currentDateTime = Carbon::now();
                        $twentyFourHoursAgo = $currentDateTime->subHours(48)->toDateTimeString();

                        Log::channel('shopifyordersync')->info("current time is : " . json_encode($twentyFourHoursAgo));

                        $sofilter = [
                            "limit" => 250,
                            "status" => "open",
                            "created_at_min" => $twentyFourHoursAgo,
                            "api_version"   => config('shopify.api_version'),
                             "fields" => "id,line_items,name,total_price,created_at"
                        ];                        
                    
                        print_r($shopifyClient->getAdminUrl()); echo "<br><br>";
                   
                    
                    
                        $orderResource = $shopifyClient->Order()->get($sofilter);
                        $shopifyOrders = $orderResource;
                        Log::channel('shopifyordersync')->info("shopifyOrders data: " . json_encode($shopifyOrders));
                        
                        print_r("hhhhhhhhhhhhhhhh->".json_encode($sofilter,true)); echo "<br><br>";
                        
                        print_r("ggggggggggggggg->".json_encode($shopifyOrders,true)); echo "<br><br>";
                    }
                    
                   
                    // Processing fetched Shopify orders
                    Log::channel('shopifyordersync')->info("fetch shopify store account hereee");

                    foreach ($shopifyOrders as $shOrder) {
                        
                        
                        
                        $order_id = $shOrder["id"]; // Getting the order ID
                        Log::channel('shopifyordersync')->info("fetch store order from shopify " . $order_id); // Logging an informational message
                        // Checking if the order exists in the database
                        $order = $shopifyStore->orders()->where('order_id', $order_id)->where('status', 'completed')->first();

                        if ($order) {
                            continue; // Skipping to the next iteration
                        }

                        Log::channel('shopifyordersync')->info("order starting to crate  and not found  in db  "); // Logging an informational message
                        $order_date_str = $shOrder["created_at"]; // Getting the order creation date
                        $order_date = date("Y-m-d H:i:s", strtotime($order_date_str)); // Formatting the order date
                        // Constructing order data
                        $orderData = array();
                        $orderData["order_id"] = $order_id;
                        $orderData["type"] = "shopify";
                        $orderData["source"] = "shopify";
                        $orderData["order_date_str"] = $order_date_str;
                        $orderData["order_date"] = $order_date;
                        $orderData["status"] = "pending";
                        $orderData["items"] = json_encode($shOrder["line_items"], JSON_INVALID_UTF8_IGNORE);
                        $orderData["order_data"] = json_encode($shOrder, JSON_INVALID_UTF8_IGNORE);
                        $orderData["inventory_sync"] = 1;
                        $orderData["order_sync"] = 1;
                        $orderData["store_id"] = $shopifyStore->id;
                        $orderData["user_id"] = $shopifyStore->user_id;
                        // Creating the order
                        $shOrderObj = $shopifyStore->orders()->create($orderData);

                        Log::channel('shopifyordersync')->info("order created successfully ");
                        Log::channel('shopifyordersync')->info("fetch order data here ". json_encode($shOrderObj));

                        if ($shOrderObj) {
                            // Processing line items of the order
                            foreach ($shOrder["line_items"] as $line_item) {
                                try {
                                    Log::channel('shopifyordersync')->info("fetching line_items from orders and trying to check in variants table"); // Logging an informational message
                                    // Retrieving variant data

                                    $pvariant = $shopifyStore->variants()
                                    ->with('listingVariant')
                                    ->where('shopify_variant_id', $line_item['variant_id'])
                                    ->first();

                                    $pvariant = $shopifyStore->variants()->with('listingVariant')->where('shopify_variant_id', $line_item['variant_id'])->first();

                                    if ($pvariant) {
                                        // If $pvariant has data
                                        Log::channel('shopifyordersync')->info("data found in pvariant");                                        
                                        Log::channel('shopifyordersync')->info("111111111111111111111111111".json_encode($pvariant));
                                     
                                        $order_qty = $line_item["quantity"];
                                        $pv_quantity = $pvariant->quantity;
                                        $new_quantity = $pv_quantity - $order_qty;

                                        Log::channel('shopifyordersync')->info("order_qty quantity is ". $order_qty);
                                        Log::channel('shopifyordersync')->info("product variant quantity is ". $pv_quantity);
                                        Log::channel('shopifyordersync')->info("new quantity found ". $new_quantity);

                                        if($pvariant->listingVariant){
                                            Log::channel('shopifyordersync')->info("enter in product variant listing"); // Logging an informational message
                                            $ebayAccount = $shopifyStore->ebayAccounts[0];
                                            $token = $ebayAccount->access_token;
                                            $siteId = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
                                            $lvdata_data = $pvariant->listingVariant;
                                            $ebay_item_id = $pvariant->listingVariant->ebay_item_id;
                                            $quantity = ($new_quantity > 0) ? $new_quantity : 0;
                                            $line_item_variant_id =  $line_item['variant_id'];
                                            $sku = $pvariant->listingVariant->sku;
                                            $listingvariantdata = $pvariant->listingVariant->listing_variant_data;
                                            $get_listing_variant_data = $listingvariantdata;
                                            $decode_listing_variant_data = json_decode($get_listing_variant_data, true);
    
                                            Log::channel('shopifyordersync')->info("ebayAccount id is ". $ebayAccount);
                                            Log::channel('shopifyordersync')->info("siteId is ". $siteId);
                                            Log::channel('shopifyordersync')->info("ebay_item_id is ". $ebay_item_id);
                                            Log::channel('shopifyordersync')->info("line_item_variant_id is ". $line_item_variant_id);
                                            Log::channel('shopifyordersync')->info("sku is ". $sku);
                                            Log::channel('shopifyordersync')->info("decode_listing_variant_data is ". $listingvariantdata);
    
    
                                            $ebay_environment = config('ebay.environment');
    
                                            $ebConfig = array('production' =>
                                            array('credentials' => array(
                                            'devId' =>  config('ebay.' . $ebay_environment . 'devid'),
                                            'appId' => config('ebay.' . $ebay_environment . 'appid'),
                                            'certId' =>config('ebay.' . $ebay_environment . 'certid')),
                                            ));
    
                                            $service = new Services\TradingService([
                                                'credentials' => $ebConfig['production']['credentials'],
                                                'sandbox' => false,
                                                'siteId' => $siteId,
                                            ]);
    
                                            // check listing variant sku is equalto line item variant id
                                            if ($pvariant->listingVariant->sku == $line_item_variant_id) {
                                                Log::channel('shopifyordersync')->info("shopify variant id found in listing varirant db sku field"); // Logging an informational message
    
                                                // print_r($decode_listing_variant_data['VariationSpecifics'][0]['NameValueList']);
                                                $VariationSpecifics = $decode_listing_variant_data['VariationSpecifics'];
    
                                                // check if VariationSpecifics data is available
                                                if($VariationSpecifics){
                                                    Log::channel('shopifyordersync')->info("enter in multiple variant product"); // Logging an informational message
                                                    $options = array();
                                                    for ($x = 0; count($decode_listing_variant_data['VariationSpecifics'][0]['NameValueList']) > $x; $x++) {
                                                        $options[$decode_listing_variant_data['VariationSpecifics'][0]['NameValueList'][$x]['Name']] =  $decode_listing_variant_data['VariationSpecifics'][0]['NameValueList'][$x]['Value'][0];
                                                    }
    
                                                    Log::channel('shopifyordersync')->info("options data is -> ". json_encode($options));
    
                                                    $request = new Types\ReviseFixedPriceItemRequestType();
                                                    $request->RequesterCredentials = new Types\CustomSecurityHeaderType();
                                                    $request->RequesterCredentials->eBayAuthToken = $token;
    
                                                    $itemType = new Types\ItemType();
                                                    $itemType->ItemID = $ebay_item_id;
    
                                                    $variationsType = new Types\VariationsType();
                                                    $variationType = new Types\VariationType();
                                                    $variationType->Quantity = $quantity;
    
                                                    $variationSpecificsSetType = new Types\NameValueListArrayType();
                                                    $variationSpecificsSetType->NameValueList = array();
                                                    foreach ($options as $k => $v) {
                                                        $nameValueListType = new Types\NameValueListType();
                                                        $nameValueListType->Name = $k;
                                                        $nameValueListType->Value = array($v);
                                                        $variationSpecificsSetType->NameValueList[] = $nameValueListType;
                                                    }
    
                                                    $variationType->VariationSpecifics = array($variationSpecificsSetType);
                                                    $variationsType->Variation = array($variationType);
                                                    $itemType->Variations = $variationsType;
                                                    $request->Item = $itemType;
                                                    $response = $service->reviseFixedPriceItem($request);
                                                    // Log::channel('shopifyordersync')->info("Response - " . serialize($response), "INFO");
    
                                                    if ($response->Ack !== 'Failure') {
                                                        Log::channel('shopifyordersync')->info("Quantity on eBay updated successfully - ",$ebay_item_id);
                                                        ///duplidate qty on product variant table
                                                        $pvariant->quantity =  $quantity;
                                                        $pvariant->save();
                                                        
                                                        $shOrderObj->status = 'completed';
                                                       $shOrderObj->save(); // quantity update in  database
                                                       Log::channel('shopifyordersync')->info("quantity update in  database successful"); // Logging an informational message
    
                                                    } else {
                                                      
                                                        $errmsg = [];
                                                        if (isset($response->Errors)) {
                                                            foreach ($response->Errors as $error) {
                                                                $errmsg[] = $error->LongMessage;
                                                            }
                                                        }
                                                        Log::channel('shopifyordersync')->info("Error in updating quantity on eBay - " . $ebay_item_id . " Error - " . implode(", ", $errmsg), ["ERROR"]);
    
                                                    }
    
                                                    
    
                                                } else {
                                                    Log::channel('shopifyordersync')->info("enter in single variant"); // Logging an informational message
    
                                                    $inventoryStatus = new Types\InventoryStatusType();
    
                                                    if (trim($sku)) {
                                                        $inventoryStatus->SKU = trim($sku);
                                                    }
    
                                                    $inventoryStatus->ItemID = $ebay_item_id;
                                                    $inventoryStatus->Quantity = ($quantity < 0) ? 0 : $quantity;
                                                    $inventoryStatusArray = array();
                                                    $inventoryStatusArray[] = $inventoryStatus;
    
                                                    $ebayRequest = new Types\ReviseInventoryStatusRequestType();
                                                    $ebayRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
                                                    $ebayRequest->RequesterCredentials->eBayAuthToken = $token;
                                                    $ebayRequest->InventoryStatus = $inventoryStatusArray;
                                                    $ebayResponse = $service->reviseInventoryStatus($ebayRequest);
                                                    $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
    
                                                    if (isset($ebayResponse["Ack"]) && $ebayResponse["Ack"] != 'Failure') {
    
                                                        $listingVariant->last_inventory_synced = $quantity;
                                                        $listingVariant->last_inventory_synced_at = now()->toDateTimeString();
                                                        Log::channel('shopifyordersync')->info("update the quantity in liosting vbariant");
                                                        $listingVariant->save();
                                                        $listingVariant->listing->last_inventory_synced_at = $listingVariant->last_inventory_synced_at;
                                                        $listingVariant->listing->save();
                                                        $pvariant->quantity = $quantity;
                                                        Log::channel('shopifyordersync')->info("update the quantity in product vbariant");
                                                        $pvariant->save();
                                                        //TODO: order table completed.
                                                        
                                                        $shOrderObj->status = 'completed';
                                                        $shOrderObj->save(); // quantity update in  database
                                                        Log::channel('shopifyordersync')->info("quantity update in  database successful"); // Logging an informational message
                                                    }
    
                                                }
    
                                            } else if($pvariant->listingVariant->custom_sku == $line_item_variant_id) {
    
                                                Log::channel('shopifyordersync')->info("custom_sku -> shopify variant id found in listing varirant db custom_sku field");
    
                                                $VariationSpecifics = $decode_listing_variant_data['VariationSpecifics'];
    
                                                if($VariationSpecifics){
                                                    Log::channel('shopifyordersync')->info("custom_sku -> enter in multiple variant product");
    
                                                    $options = array();
                                                    for ($x = 0; count($decode_listing_variant_data['VariationSpecifics'][0]['NameValueList']) > $x; $x++) {
                                                        $options[$decode_listing_variant_data['VariationSpecifics'][0]['NameValueList'][$x]['Name']] =  $decode_listing_variant_data['VariationSpecifics'][0]['NameValueList'][$x]['Value'][0];
                                                    }
    
                                                    Log::channel('shopifyordersync')->info("custom_sku -> options data is -> ". json_encode($options));
    
                                                    $request = new Types\ReviseFixedPriceItemRequestType();
                                                    $request->RequesterCredentials = new Types\CustomSecurityHeaderType();
                                                    $request->RequesterCredentials->eBayAuthToken = $token;
    
                                                    $itemType = new Types\ItemType();
                                                    $itemType->ItemID = $ebay_item_id;
    
                                                    $variationsType = new Types\VariationsType();
                                                    $variationType = new Types\VariationType();
                                                    $variationType->Quantity = $quantity;
    
                                                    $variationSpecificsSetType = new Types\NameValueListArrayType();
                                                    $variationSpecificsSetType->NameValueList = array();
                                                    foreach ($options as $k => $v) {
                                                        $nameValueListType = new Types\NameValueListType();
                                                        $nameValueListType->Name = $k;
                                                        $nameValueListType->Value = array($v);
                                                        $variationSpecificsSetType->NameValueList[] = $nameValueListType;
                                                    }
    
                                                    $variationType->VariationSpecifics = array($variationSpecificsSetType);
                                                    $variationsType->Variation = array($variationType);
                                                    $itemType->Variations = $variationsType;
                                                    $request->Item = $itemType;
                                                    $response = $service->reviseFixedPriceItem($request);
                                                    if ($response->Ack !== 'Failure') {
                                                        Log::channel('shopifyordersync')->info("custom_sku -> Quantity on eBay updated successfully - ",$ebay_item_id);
                                                        ///duplidate qty on product variant table
                                                        $pvariant->quantity =  $quantity;
                                                        $pvariant->save();
                                                        
                                                        $shOrderObj->status = 'completed';
                                                        $shOrderObj->save(); // quantity update in  database
                                                        Log::channel('shopifyordersync')->info("quantity update in  database successful"); // Logging an informational message
    
                                                    } else {
                                                        $errmsg = [];
                                                        if (isset($response->Errors)) {
                                                            foreach ($response->Errors as $error) {
                                                                $errmsg[] = $error->LongMessage;
                                                            }
                                                        }
                                                        Log::channel('shopifyordersync')->info("custom_sku -> Error in updating quantity on eBay - " . $ebay_item_id . " Error - " . implode(", ", $errmsg), ["ERROR"]);
    
                                                    }
                                                   
                                                } else {
                                                    Log::channel('shopifyordersync')->info("custom_sku -> enter in single variant");
    
                                                    $inventoryStatus = new Types\InventoryStatusType();
    
                                                    if (trim($sku)) {
                                                        $inventoryStatus->SKU = trim($sku);
                                                    }
    
                                                    $inventoryStatus->ItemID = $ebay_item_id;
                                                    $inventoryStatus->Quantity = ($quantity < 0) ? 0 : $quantity;
                                                    $inventoryStatusArray = array();
                                                    $inventoryStatusArray[] = $inventoryStatus;
    
                                                    $ebayRequest = new Types\ReviseInventoryStatusRequestType();
                                                    $ebayRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
                                                    $ebayRequest->RequesterCredentials->eBayAuthToken = $token;
                                                    $ebayRequest->InventoryStatus = $inventoryStatusArray;
                                                    $ebayResponse = $ebayService->reviseInventoryStatus($ebayRequest);
                                                    $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
    
                                                    if (isset($ebayResponse["Ack"]) && $ebayResponse["Ack"] != 'Failure') {
                                                        $listingVariant->last_inventory_synced = $quantity;
                                                        $listingVariant->last_inventory_synced_at = now()->toDateTimeString();
                                                        Log::channel('shopifyordersync')->info("custom_sku -> update the quantity in listing vbariant");
                                                        $listingVariant->save();
                                                        $listingVariant->listing->last_inventory_synced_at = $listingVariant->last_inventory_synced_at;
                                                        $listingVariant->listing->save();
                                                        $pvariant->quantity = $quantity;
                                                        Log::channel('shopifyordersync')->info("custom_sku -> update the quantity in product vbariant");
                                                        $pvariant->save();
                                                        //TODO: order table completed.
                                                        $shOrderObj->status = 'completed';
                                                        $shOrderObj->save(); // quantity update in  database
                                                        Log::channel('shopifyordersync')->info("quantity update in  database successful"); // Logging an informational message
                                                    }
                                                }
                                            }
                                        } else {
                                        Log::channel('shopifyordersync')->info("data not found in product variant listing");
                                            // $new_quantity = ($new_quantity > 0) ? $new_quantity : 0;
                                            // $pvariant->quantity = $new_quantity;
                                            // $pvariant->save();
                                        }
                                    } else {
                                        // If $pvariant is empty (no data found)
                                        Log::channel('shopifyordersync')->info("no data found in pvariant");
                                    }
                                }
                                catch (\Exception $e) {
                                    report($e); // Reporting exception
                                    $errors[] = $e->getMessage(); // Storing error message
                                }
                                // break;
                            }
                            sleep(1);
                            
                        } else {                            
                            echo "in else";
                        }
                        // break;
                    }
                }
                catch (\Exception $e) {
                    report($e); // Reporting exception
                    $errors[] = $e->getMessage(); // Storing error message
                }
            }
                   $cronJob->flag = 0;
        $cronJob->ended_at = date("Y-m-d H:i:s");
        $cronJob->last_updated_at = date("Y-m-d H:i:s");
        $cronJob->save();
            return response()->json(['status' => 'success', 'msg' => "shopify order sync success"], 200);
        }
          
   
    }
    
    public function ebayordersync()
    {
        echo "hiiiiiiiii";
        Log::channel('ebayordersync')->info("entered in ImportEbayProducts method");
        $shopifyStores = ShopifyStore::where('status', "active")->where('id', "1331")->get();
        Log::channel('ebayordersync')->info("entered in ImportEbayProducts method");
        Log::info("enter in ebayordersync and file is working in first step");
        if ($shopifyStores->count() > 0) {
            Log::channel('ebayordersync')->info("entered in ImportEbayProducts method");
            Log::info("shopify store found and continue ");
            foreach ($shopifyStores as $shopifyStore) {
                Log::channel('ebayordersync')->info("entered in ImportEbayProducts method");
                Log::info("here is shopifystore for this account");
                $shopify_store_id = $shopifyStore->id;
                Log::channel('ebayordersync')->info("entered in ImportEbayProducts method");
                Log::info("here is shopify store" . $shopifyStore->id);
                //done
                $store_database_name = config('config.store_db_prefix') . $shopify_store_id;
                AppHelper::setConnection($store_database_name);
                Log::channel('ebayordersync')->info("entered in ImportEbayProducts method");
                Log::info("connection setup successfull");
                try {
                    Log::channel('ebayordersync')->info("entered in ImportEbayProducts method");
                    Log::info("connecting to ebay");
                    $ebay_environment = config('ebay.environment');
                    $ebayCredentials = array(
                        'credentials' => [
                            'devId' => config('ebay.' . $ebay_environment . 'devid'),
                            'appId' => config('ebay.' . $ebay_environment . 'appid'),
                            'certId' => config('ebay.' . $ebay_environment . 'certid'),
                        ],
                        'authToken' => '',
                        'oauthUserToken' => '',
                        'ruName' => config('ebay.' . $ebay_environment . 'RuName'),
                    );
                    Log::channel('ebayordersync')->info("entered in ImportEbayProducts method");
                    Log::info("connection successfulll from ebay ");
                    $ebayAccounts = $shopifyStore->ebayAccounts()->where("is_valid", 1)->get();
                    if ($ebayAccounts->count() > 0) {
                        Log::channel('ebayordersync')->info("connection successfulll and ebay account found");
                        //  Log::info("connection successfulll and ebay account found ");
                        foreach ($ebayAccounts as $ebayAccount) {
                            //Log::info($ebayAccount);
                            try {
                                $inventrysync = $ebayAccount->inventory_sync;
                                $created_after = date('Y-m-d', strtotime('-1 days'));
                                $siteId = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
                                $authToken = $ebayAccount->access_token;
                                $ebayService = new Services\TradingService([
                                    'credentials' => $ebayCredentials['credentials'],
                                    'sandbox' => ($ebay_environment == "sandbox") ? true : false,
                                    'siteId' => $siteId,
                                ]);
                                Log::channel('ebayordersync')->info("trying to fetch ebay order");
                                //      Log::info("trying to fetch ebay order ");
                                $channelLineItems = array();
                                $ebayRequest = new Types\GetOrdersRequestType();
                                $ebayRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
                                $ebayRequest->RequesterCredentials->eBayAuthToken = $authToken;
                                $ebayRequest->OrderRole = "Seller";
                                if ($created_after) {
                                    $ebayRequest->CreateTimeFrom = new \DateTime($created_after);
                                }

                                $createTimeTo = date("Y-m-d", strtotime('+1 day', strtotime(date("Y-m-d"))));
                                $ebayRequest->CreateTimeTo = new \DateTime($createTimeTo);
                                $paginationType = new Types\PaginationType();
                                $paginationType->PageNumber = 1;
                                $paginationType->EntriesPerPage = 200;
                                $ebayRequest->Pagination = $paginationType;
                                $ebayResponse = $ebayService->getOrders($ebayRequest);
                                $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
                                Log::channel('ebayordersync')->info("ebay response" . json_encode($ebayResponse));
                                print_r("ebay response" . json_encode($ebayResponse));
                                //     Log::info("ebay response".json_encode($ebayResponse));
                                sleep(2);
                                $newOrderCount = 0;
                                if ($ebayResponse["Ack"] !== 'Failure' && $ebayResponse["OrderArray"] && $ebayResponse["OrderArray"]["Order"]) {
                                    Log::channel('ebayordersync')->info("ebay response is succesfulll" . json_encode($ebayResponse["OrderArray"]["Order"]));
                                    //  Log::info("ebay response is succesfulll".json_encode($ebayResponse["OrderArray"]["Order"]));
                                    foreach ($ebayResponse["OrderArray"]["Order"] as $ebayOrder) {
                                        try {
                                            //
                                            $order_id = $ebayOrder["OrderID"];
                                            Log::channel('ebayordersync')->info("now fetching the orders for         " . $order_id);
                                            //     Log::info("now fetching the orders for         ".    $order_id);
                                            $order = $shopifyStore->orders()->where('order_id', $order_id)->where('type', 'ebay')->first();
                                            if ($order) {
                                                continue;
                                            }

                                            Log::channel('ebayordersync')->info("now fetching the orders not found in");
                                            //     Log::info("now fetching the orders not found in ");
                                            $paymentMethods = (isset($ebayOrder["PaymentMethods"])) ? json_encode($ebayOrder["PaymentMethods"]) : "";
                                            $order_status = "pending";
                                            if (isset($ebayOrder["PaymentMethods"]) && $ebayOrder["PaymentMethods"][0] != "COD") {
                                                $order_status = "paid";
                                            }

                                            $order_date_str = $ebayOrder["CreatedTime"];
                                            $order_date = date("Y-m-d H:i:s", strtotime($order_date_str));
                                            $items = $ebayOrder["TransactionArray"]['Transaction'];
                                            //    $channelLineItems[] = $items;
                                            if (!$items) {
                                                $errors[] = "error getting order items | order_id:" . $order_id;
                                                continue;
                                            }
                                            $order_sync = false;
                                            $linked_order_id = "";
                                            Log::info("log to check error");
                                            $orderData = array();
                                            $orderData["order_id"] = $order_id;
                                            $orderData["type"] = "ebay";
                                            $orderData["source"] = "ebay";
                                            $orderData["order_date_str"] = $order_date_str;
                                            $orderData["order_date"] = $order_date;
                                            $orderData["status"] = $order_status;
                                            $order_items = json_encode($items, JSON_INVALID_UTF8_IGNORE);
                                            $orderData["items"] = $order_items;
                                            $order_data = $ebayOrder;
                                            $order_data = json_encode($order_data, JSON_INVALID_UTF8_IGNORE);
                                            $orderData["order_data"] = $order_data;
                                            $orderData["account_id"] = $ebayAccount->id;
                                            $orderData["store_id"] = $shopifyStore->id;
                                            $orderData["user_id"] = $shopifyStore->user_id;
                                            $order = $shopifyStore->orders()->create($orderData);
                                           // Log::channel('ebayordersync')->info("order created successfully ");
                                            //    Log::info("order created successfully ");
                                            continue;
                                            //             if($order){
                                            //                 $inventrysync==true;
                                            //                 foreach($items as $item){
                                            //                     Log::channel('ebayordersync')->info("log to check error   last ".json_encode($item));
                                            //                   //  Log::info("log to check error   last ".json_encode($item));
                                            //                     $Itemid = $item["Item"]["ItemID"];
                                            //                      Log::channel('ebayordersync')->info($Itemid );
                                            //                 //      if(isset($item["Item"]["SKU"]) && $item["Item"]["SKU"] == ' ') continue;
                                            //                                                     // $sku = $item["Item"]["SKU"];
                                            //                                           $sku= 'eb_248_661a20465501b';
                                            //                     $quantity = (int) $item["QuantityPurchased"];
                                            //                     Log::channel('ebayordersync')->info("quantity is for this ".$quantity);
                                            //                     // Log::info("quantity is for this ".$quantity);
                                            //                     $listingVariant = $ebayAccount->listingVariants()->with('variant')->where('sku',$sku)->where('ebay_item_id',$Itemid)->first();
                                            //                 //     Log::info("now fetching the orders ");
                                            //                      Log::channel('ebayordersync')->info("now fetching the listing variants  ".$listingVariant);
                                            //                 //     Log::info("now fetching the listing variants  ".$listingVariant);
                                            //                     // die(0);
                                            //                     if($listingVariant && $listingVariant->variant){
                                            //                             Log::channel('ebayordersync')->info("quantity already presentin db  ".$listingVariant->variant->quantity);
                                            //                             $quantity=$listingVariant->variant->quantity - $quantity;
                                            //                             Log::channel('ebayordersync')->info("quantity after update in db ".$quantity);
                                            //                             if ($quantity <0){
                                            //                                 $quantity=0;
                                            //                             }
                                            //                         $listingVariant->variant->quantity =$quantity;
                                            //                         $listingVariant->variant->save();
                                            //                         $variant_id = $listingVariant->variant->id;
                                            //                         Log::channel('ebayordersync')->info("variant id ".    $variant_id );
                                            //                         $shopify_variant_id = $listingVariant->variant->shopify_variant_id;
                                            //                         Log::channel('ebayordersync')->info("shopify_variant_id ".    $shopify_variant_id );
                                            //                         $inventory_item_id=$listingVariant->variant->shopify_inventory_item_id;
                                            //                             Log::channel('ebayordersync')->info("inventory_item_id ".$inventory_item_id );
                                            //                             PHPShopify\ShopifySDK::config(array('ShopUrl' => $shopifyStore->shopify_url,'AccessToken' => $shopifyStore->access_token,'ApiVersion' => config('shopify.api_version')));
                                            //                         $shopifyClient = new PHPShopify\ShopifySDK;
                                            //                          Log::channel('ebayordersync')->info("now fetching the orders main shopifyyy");
                                            //                     $shopify_store_id = $shopifyStore->id;
                                            //         $store_database_name = config('config.store_db_prefix').$shopify_store_id;
                                            //         Log::channel('ebayordersync')->info("now fetching the orders main shopifyyy  in second last ");
                                            //                                                     AppHelper::setConnection($store_database_name);
                                            //                                                         Log::channel('ebayordersync')->info("now fetching the orders main shopifyyy  in second last connection set ");
                                            //                             $succCount = 0;
                                            //                             $locErrors = array();
                                            //                             $locations = ($shopifyStore->locations) ? explode(",",$shopifyStore->locations) : array();
                                            //                                 Log::channel('ebayordersync')->info("now fetching the orders main shopifyyy  in second last loactionssss ");
                                            //                             if($locations){
                                            //                                     Log::channel('ebayordersync')->info("location found ");
                                            //                                 foreach($locations as $location_id){
                                            //                                     try{
                                            //                                         Log::channel('ebayordersync')->info("location id .$location_id ");
                                            //                                         $sdata = array(
                                            //                                             "location_id" => $location_id,
                                            //                                             "inventory_item_id" => $inventory_item_id,
                                            //                                             "available" => $quantity
                                            //                                         );
                                            //                                          Log::channel('ebayordersync')->info("order for listing variants on shopify data ".json_encode($sdata));
                                            //                                     //    $shopifyClient->InventoryLevel()->set($sdata);
                                            //                                         sleep(1);
                                            //                                         $succCount++;
                                            //                                     Log::channel('ebayordersync')->info("order for listing variants on shopify data  updated sucessfully");
                                            //                                     }
                                            //                                     catch(\Exception $e){
                                            //                                         report($e);
                                            //                                         $errors[] = $e->getMessage();
                                            //                                         $locErrors[] = $e->getMessage();
                                            //                                     }
                                            //                                 }
                                            //                     }
                                            //                 }
                                            //             }
                                            //         }
                                        } catch (\Exception $e) {
                                            report($e);
                                            $errors[] = $e->getMessage();
                                        }
                                    }
                                }
                            } catch (\Exception $e) {
                                report($e);
                                $errors[] = $e->getMessage();
                            }
                        }
                    }
                } catch (\Exception $e) {
                    report($e);
                    $errors[] = $e->getMessage();
                }
            }
        }
    }
    
    public function ShopifyVidSync($pvariant,$ebayAccount,$quantity){
        echo 'hiteshmali ShopifyVidSync';
        //   echo 'imported using our app';
        die();
        //imported using our app
        // update eb on basis of sku
        $listingVariant = $pvariant->listingVariant;

        Log::channel('shopifyordersync')->info("here in listing variants condition inn  condituiipon agaia m");
        $ebay_item_id = $listingVariant->ebay_item_id;
        $quantity = ($quantity > 0) ? $quantity : 0;
        $siteId = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
        $ebay_token = $ebayAccount->access_token;
        $ebay_environment = config('ebay.environment');
        $ebayCredentials = array(
            'credentials' => [
                'devId' => config('ebay.' . $ebay_environment . 'devid'),
                'appId' => config('ebay.' . $ebay_environment . 'appid'),
                'certId' => config('ebay.' . $ebay_environment . 'certid'),
            ],
            'authToken' => '',
            'oauthUserToken' => '',
            'ruName' => config('ebay.' . $ebay_environment . 'RuName'),
        );
        $ebayService = new Services\TradingService([
            'credentials' => $ebayCredentials['credentials'],
            'sandbox' => ($ebay_environment == "sandbox_") ? true : false,
            'siteId' => $siteId,
        ]);
        $sku = $listingVariant->sku;
        try {
            $ebayItem = [];
            $ebayItemRequest = new Types\GetItemRequestType();
            $ebayItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
            $ebayItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
            $ebayItemRequest->ItemID = $ebay_item_id;
            $ebayItemRequest->IncludeItemSpecifics = true;
            $ebayItemResponse = $ebayService->getItem($ebayItemRequest);
            $ebayItemResponse = $ebayItemResponse->toArray();
            if (isset($ebayItemResponse["Item"]) && $ebayItemResponse["Item"]) {
                $ebayItem = $ebayItemResponse["Item"];
            }

            if (!$ebayItem) {
                // continue;
            }

            if ((isset($ebayItem["SKU"]))) {
                $sku = $ebayItem["SKU"];
            }

            $listing_format = ($ebayItem["ListingType"] == "FixedPriceItem") ? "fixed_price" : "auction";
            $variations = (isset($ebayItem["Variations"])) ? $ebayItem["Variations"] : array();
            $variations = (isset($variations["Variation"])) ? $variations["Variation"] : array();

            $ebayResponse = [];
            $ebayResponse = [];
            Log::channel('shopifyordersync')->info("update the quantityyy in try 1 ");
            if ($quantity == 0 && $listing_format == "auction") {
                Log::channel('shopifyordersync')->info("update the quantityyy in try quantity 0 case ");
                $endItemRequest = new Types\EndItemRequestType();
                $endItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
                $endItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
                $endItemRequest->ItemID = $ebay_item_id;
                //    $endItemRequest->EndingReason = "NotAvailable";
                //    $ebayResponse = $ebayService->endItem($endItemRequest);
                //    $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
            } else if ($listing_format == "auction") {
                Log::channel('shopifyordersync')->info("update the quantityyy in try nomal case ");
                $ebayRequest = new Types\ReviseItemRequestType();
                $ebayRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
                $ebayRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
                $ebayItem = new Types\ItemType();
                $ebayItem->ItemID = $ebay_item_id;
                $ebayItem->Quantity = 1;
                $ebayRequest->Item = $ebayItem;
                $ebayResponse = $ebayService->reviseItem($ebayRequest);
                $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
            } else {
                Log::channel('shopifyordersync')->info("update the quantityyy in try else case ");
                $inventoryStatus = new Types\InventoryStatusType();
                if (trim($sku)) {
                    $inventoryStatus->SKU = trim($sku);
                }

                //   if($sku contains "ebaylistingmapped"  || $sku contains "ebaylistingcreated"){

                //        $sku  = findeBaySKU($variations, )

                //   }

                $inventoryStatus->ItemID = $ebay_item_id;
                $inventoryStatus->Quantity = ($quantity < 0) ? 0 : $quantity;
                $inventoryStatusArray = array();
                $inventoryStatusArray[] = $inventoryStatus;
                $ebayRequest = new Types\ReviseInventoryStatusRequestType();
                $ebayRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
                $ebayRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
                $ebayRequest->InventoryStatus = $inventoryStatusArray;
                $ebayResponse = $ebayService->reviseInventoryStatus($ebayRequest);
                $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
                Log::channel('shopifyordersync')->info("update the quantityyy in try else case" . json_encode($ebayResponse));
                if (isset($ebayResponse["Ack"]) && $ebayResponse["Ack"] == 'Failure' && $ebayResponse["Errors"]) {
                    $errors = $ebayResponse["Errors"];
                    $shortMsg = strtolower($errors[0]["LongMessage"]);
                    if (strpos($shortMsg, 'valid number greater than 0') !== false || strpos($shortMsg, 'must have a quantity greater than 0') !== false) {
                        $endItemRequest = new Types\EndFixedPriceItemRequestType();
                        $endItemRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
                        $endItemRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
                        $endItemRequest->ItemID = $ebay_item_id;
                        $endItemRequest->EndingReason = "NotAvailable";
                        $ebayResponse = $ebayService->endFixedPriceItem($endItemRequest);
                        $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
                    }
                }
            }
            if (isset($ebayResponse["Ack"]) && $ebayResponse["Ack"] != 'Failure') {
                $listingVariant->last_inventory_synced = $quantity;
                $listingVariant->last_inventory_synced_at = now()->toDateTimeString();
                Log::channel('shopifyordersync')->info("update the quantity in liosting vbariant");
                $listingVariant->save();
                $listingVariant->listing->last_inventory_synced_at = $listingVariant->last_inventory_synced_at;
                $listingVariant->listing->save();
                $pvariant->quantity = $quantity;
                Log::channel('shopifyordersync')->info("update the quantity in product vbariant");
                $pvariant->save();
                //$pendingInvArray[] = $pendingInv;
            } else {
                $accountErrors[] = $ebayResponse;
            }
        } catch (\Exception $e) {
            report($e);
            $accountErrors[] = $e->getMessage();
        }
    }
    
    
    public function ebaysynctest(){
      
        // exit();
       $cronJob = CronJob::where('type', 'ebay_sync')->first();
        if ($cronJob && ($cronJob->flag == 1 || $cronJob->do_stop == 1)) {
            return response()->json(['status' => 'error', 'msg' => "cron already running"], 406);
        } else {
            $cronJob->flag = 1;
            $cronJob->started_at = date("Y-m-d H:i:s");
            $cronJob->ended_at = NULL;
            $cronJob->last_updated_at = date("Y-m-d H:i:s");
            $cronJob->save();
        }
      
        	 $importconditions[] = array("inventory_sync", "=", 1);
            $shopifyStores = ShopifyStore::with('ebayAccounts')->where('status', 'active')->where('plan_id','>',1)->whereHas('ebayAccounts', function ($query) use ($importconditions) {$query->where($importconditions); })->get();
      
    	if ($shopifyStores->count() > 0) {
        
		foreach ($shopifyStores as $shopifyStore) {
	
			$shopify_store_id = $shopifyStore->id;
           Log::channel('ebayordersync')->info("Here is the shopify store id ->".$shopify_store_id);
			$store_database_name = config('config.store_db_prefix') . $shopify_store_id;
			AppHelper::setConnection($store_database_name);
			
			echo "h111";

			try {
			
				$ebay_environment = config('ebay.environment');
				$ebayCredentials = array(
					'credentials' => [
						'devId' => config('ebay.' . $ebay_environment . 'devid'),
						'appId' => config('ebay.' . $ebay_environment . 'appid'),
						'certId' => config('ebay.' . $ebay_environment . 'certid'),
					],
					'authToken' => '',
					'oauthUserToken' => '',
					'ruName' => config('ebay.' . $ebay_environment . 'RuName')
				);
			
			
				$ebayAccount = $shopifyStore->ebayAccounts[0];
				//print_r($ebayAccount);
				echo $ebayAccount->access_token;
			  //Log::channel('ebayordersync')->info("ebay account id ->".$ebayAccount);
			
			try {
						    
						    $currentDateTime = new \DateTime('now', new \DateTimeZone('UTC'));
                            $startTimeTo = $currentDateTime->format('Y-m-d H:i:s');   
                            $currentDateTime->modify('-3  days');
                            $startTimeFrom = $currentDateTime->format('Y-m-d H:i:s');
							$inventrysync = $ebayAccount->inventory_sync;
							$siteId = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
							$authToken = $ebayAccount->access_token;
							
							$ebayService = new Services\TradingService([
								'credentials' => $ebayCredentials['credentials'],
								'sandbox' => ($ebay_environment == "sandbox") ? true : false,
								'siteId' => $siteId
							]);
					
							$channelLineItems = array();
							$ebayRequest = new Types\GetOrdersRequestType();
							$ebayRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
							$ebayRequest->RequesterCredentials->eBayAuthToken = $authToken;
							$ebayRequest->OrderRole = "Seller";
							$ebayRequest->CreateTimeFrom = new \DateTime($startTimeFrom);
                            $ebayRequest->CreateTimeTo = new \DateTime($startTimeTo);
							
							
							$paginationType = new Types\PaginationType();
							$paginationType->PageNumber = 1;
							$paginationType->EntriesPerPage = 200;
							$ebayRequest->Pagination = $paginationType;
							$ebayResponse = $ebayService->getOrders($ebayRequest);
							$ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
							
							echo "responsedfgdf";
				
		                   //	print_r($ebayRequest);
			
							sleep(2);
							$newOrderCount = 0;
						
							if ($ebayResponse["Ack"] !== 'Failure' && $ebayResponse["OrderArray"] && $ebayResponse["OrderArray"]["Order"]) {
		                    	Log::channel('ebayordersync')->info("ebay response is successful");
								foreach ($ebayResponse["OrderArray"]["Order"] as $ebayOrder) {
								    
        						    $cronJob2 = CronJob::where('type', 'ebay_sync')->first();
                                    if ($cronJob2 && $cronJob2->do_stop) break;
                                    $cronJob->last_updated_at = date("Y-m-d H:i:s");
                                    $cronJob->save();
								    
									try {
										//		  
										
										//	print_r( $ebayOrder);
											
										
										$order_id = $ebayOrder["OrderID"];
										Log::channel('ebayordersync')->info("store id is  $shopify_store_id for Order id is this ->".$order_id);
											
										$order = $shopifyStore->orders()->where('order_id', $order_id)->where('type', 'ebay')->first();
										if ($order) continue;
									   
									   	Log::channel('ebayordersync')->info("Order not found in order table in db ");
										$order_status = "pending";
										$order_date_str = $ebayOrder["CreatedTime"];
										$order_date = date("Y-m-d H:i:s", strtotime($order_date_str));
										$items = $ebayOrder["TransactionArray"]['Transaction'];
									
										if (!$items) {
											$errors[] = "error getting order items | order_id:" . $order_id;
											continue;
										}
										$order_sync = false;
										$linked_order_id = "";
										$orderData = array();
										$orderData["order_id"] = $order_id;
										$orderData["type"] = "ebay";
										$orderData["source"] = "ebay";
										$orderData["order_date_str"] = $order_date_str;
										$orderData["order_date"] = $order_date;
										$orderData["status"] = $order_status;
										$orderData["items"] = json_encode($items, JSON_INVALID_UTF8_IGNORE);
										$orderData["order_data"] = json_encode($ebayOrder, JSON_INVALID_UTF8_IGNORE);
										$orderData["account_id"] = $ebayAccount->id;
										$orderData["store_id"] = $shopifyStore->id;
										$orderData["user_id"] = $shopifyStore->user_id; 
										$order = $shopifyStore->orders()->create($orderData);   
									  	Log::channel('ebayordersync')->info("Order created in db for order id ->".$order_id);
									  
                                        //////////////////////////// Changes by prabhakar///////////////////////////////////////////***
								if ($order) {
									
											$inventrysync == true;
											
											foreach ($items as $item) {
                                     
												$ItemID = $item["Item"]["ItemID"];
												$quantity = (int) $item["QuantityPurchased"];
												Log::channel('ebayordersync')->info("searching order for ebay item id ->".$ItemID);
												$listingVariant  = $ebayAccount->listingVariants()->with('variant')->where('ebay_item_id', $ItemID)->first();
											
										    	if($listingVariant){
											    	Log::channel('ebayordersync')->info("order found in listing variant for store id $listingVariant->store_id and for ebay item id ->".$ItemID);
											    		
												if (!isset($item["Variation"])) { 
		     
		     	                              	Log::channel('ebayordersync')->info("Item is single variant ");
    												if($listingVariant->variant){
    												    	Log::channel('ebayordersync')->info("Item is published or linked from our app ");
    												    
    												      //  $variant_id = $listingVariant->variant_id;
    												    	$oldqty = $listingVariant->variant->quantity;
    														 $shopify_inventory_item_id = $listingVariant->variant->shopify_inventory_item_id ; 
    													
    														$shopifyupdateqnty = $this->shopifyinvupdate($shopifyStore,$quantity,$oldqty,$shopify_inventory_item_id);  //quantity  update in shopify
                                                           
                                                            if($shopifyupdateqnty['msg'] == 'success'){
                                                                
                                                                 Log::channel('ebayordersync')->info("here is the updated shopify qty-> ".$shopifyupdateqnty['quantity']);
                                                            
        														$listingVariant->variant->quantity = $shopifyupdateqnty['quantity'];
        												 		$listingVariant->variant->save();
        												 		
        												 		$order->status = "completed";
        												 		$order->save(); 
        												 		
        												 		 Log::channel('ebayordersync')->info("successfully updated in db for store id $listingVariant->store_id shopify variant id-> ".$listingVariant->variant->shopify_variant_id);
        												 		
        												 		 Log::channel('ebayordersync')->info("successfully updated order status in db for order id $order_id  for store id $listingVariant->store_id ");
        												 		
    												 		
    												         }
    												         elseif($shopifyupdateqnty['msg'] == 'error'){
    												             Log::channel('ebayordersync')->info("Error while updating on shopify for store id $listingVariant->store_id shopify variant id-> ".$listingVariant->variant->shopify_variant_id);
    												 		 continue;
    												         }
    		                                       	}else{
    		                                       	    Log::channel('ebayordersync')->info("Item is in listing variant ,Item is single variant but not in product variants table for ItemID ->".$ItemID);
    												    continue;
    												} 
    												
												    
												}
												else {
													//This item is multivariant
													Log::channel('ebayordersync')->info("Item is multivariant for item id ->".$ItemID);
											
														$Sku_eb = isset($item["Variation"]["SKU"]) ? $item["Variation"]["SKU"] : "";
												
													Log::channel('ebayordersync')->info("Here is the sku  ".$Sku_eb);
													
														$listingVariant = $ebayAccount->listingVariants()->with('variant')->where("sku",$Sku_eb)->first();
														Log::channel('ebayordersync')->info("listing value   ".json_encode($listingVariant,true));
														if($listingVariant && $listingVariant->variant){
														    Log::channel('ebayordersync')->info("item is publish from shopify to ebay from for store id $listingVariant->store_id and our app for sku->  ".$Sku_eb);
															//item is publish from shopify to ebay from our app
															$oldqty = $listingVariant->variant->quantity;
															$shopify_inventory_item_id = $listingVariant->variant->shopify_inventory_item_id ; 
															$shopifyupdateqnty = $this->shopifyinvupdate($shopifyStore,$quantity,$oldqty,$shopify_inventory_item_id);
															
															
															
															 if($shopifyupdateqnty['msg'] == 'success'){
                                                                
                                                                Log::channel('ebayordersync')->info("here is the updated shopify qty-> ".$shopifyupdateqnty['quantity']);
                                                                
        												 		$listingVariant->variant->quantity = $shopifyupdateqnty['quantity'];
    												 			$listingVariant->variant->save();
    												 			
        												 		$order->status = "completed";
        												 		$order->save(); 
        												 		
        												 		 Log::channel('ebayordersync')->info("successfully updated in db for shopify variant id-> ".$listingVariant->variant->shopify_variant_id);
        												 		
        												 		 Log::channel('ebayordersync')->info("successfully updated order status in db for order id $order_id  ");
        												 		
    												 		
    												         }
    												         elseif($shopifyupdateqnty['msg'] == 'error'){
    												             Log::channel('ebayordersync')->info("Error while updating on shopify for shopify variant id-> ".$listingVariant->variant->shopify_variant_id);
    												 		 continue;
    												         }
															
															
														}else{
														    
															$listingVariants = $ebayAccount->listingVariants()->where('ebay_item_id', $ItemID)->where('custom_sku','!=',"")->get();
														
															if($listingVariants){
															     Log::channel('ebayordersync')->info("Item is multivariant and custom sku found for item id->".$ItemID);
															   
															     $optionsarray = array();
												                	 $nameValueList = $item['Variation']['VariationSpecifics'][0];
                                                                   
                                                                      
												                  	 foreach ($nameValueList['NameValueList'] as $nameValues) {
													                   	$optionsarray[$nameValues['Name']] = $nameValues['Value'][0];
                                                                     }
													               
												                     	 $ordervariantshvid = $this->findVariant($listingVariants,$optionsarray,$ebayAccount,$shopifyStore);
															    
															   
																if($ordervariantshvid){
																     Log::channel('ebayordersync')->info("variant result found");
															 
                                                                       $customSku = $ordervariantshvid['custom_sku'];
                                                                       $variant_id = $ordervariantshvid['other_variable'];
															
																	   $product_var = $shopifyStore->variants()->where("shopify_variant_id",$customSku)->where('id',$variant_id)->first();
																		Log::channel('ebayordersync')->info("product_var result ".json_encode($product_var,true));
															
																		  //update the values on shopify
																		  $oldqty = $product_var->quantity;
																		  	Log::channel('ebayordersync')->info("here is the qty ".$oldqty);
																		  $shopify_inventory_item_id = $product_var->shopify_inventory_item_id ; 
																		  	Log::channel('ebayordersync')->info("here is the shopify_inventory_item_id".$shopify_inventory_item_id);
																		  	Log::channel('ebayordersync')->info("updating qty on shopify for shopify var id ".$customSku);
																		  $shopifyupdateqnty = $this->shopifyinvupdate($shopifyStore,$quantity,$oldqty,$shopify_inventory_item_id); 
																		 
																		 
																		  if($shopifyupdateqnty['msg'] == 'success'){
                                                                
                                                                                Log::channel('ebayordersync')->info("here is the updated shopify qty-> ".$shopifyupdateqnty['quantity']);
                                                                                
                        													    $product_var->quantity = $shopifyupdateqnty['quantity'];
                    														    $product_var->save();  
                        												 		
                        												 		$order->status = "completed";
                        												 		$order->save(); 
                        												 		
                        												 		 Log::channel('ebayordersync')->info("successfully updated in db for shopify variant id-> ".$product_var->shopify_variant_id);
                        												 		
                        												 		 Log::channel('ebayordersync')->info("successfully updated order status in db for order id $order_id  ");
                        												 		
    												 		
                    												         }
                    												         elseif($shopifyupdateqnty['msg'] == 'error'){
                    												             Log::channel('ebayordersync')->info("Error while updating on shopify for shopify variant id-> ".$product_var->shopify_variant_id);
                    												 		 continue;
                    												         }
																		
																}
																else{
																      Log::channel('ebayordersync')->info("unexpected case we shall get email notification to check");
																    //unexpected case we shall get email notification to check
																    continue;
																    
																}
															 
														    }
														    else{
														        Log::channel('ebayordersync')->info("item id $ItemID not found in listing on the basis of sku and custom_sku is also empty.It means this is users ebay listing but he never linked it or created on shopify for store id ");
														        
														    }
														}
													}
													
											}else{
											    Log::channel('ebayordersync')->info("Listing for item id $ItemID is not found listingvariants .");
											    continue;
											}		

										      	}
										     
												}
												

								 
											

					        	} catch (\Exception $e) {
							report($e);
							$errors[] = $e->getMessage();
						}
					}
				}
			} catch (\Exception $e) {
				report($e);
				$errors[] = $e->getMessage();
			}
        // 		}
        // 	}
        }
               catch (\Exception $e) {
							report($e);
							$errors[] = $e->getMessage();
						}
		}
	    }
	     $cronJob->flag = 0;
        $cronJob->ended_at = date("Y-m-d H:i:s");
        $cronJob->last_updated_at = date("Y-m-d H:i:s");
        $cronJob->save();
    }
    
    
    public function findVariant($listingVariants,$optionsarray,$ebayAccount,$shopifyStore){
         
      Log::channel('ebayordersync')->info("entered in find variant method for option array ".json_encode($optionsarray,true));
	  foreach ($listingVariants as $listingVariant) {
	  Log::channel('ebayordersync')->info("looping through listing variants ");
	  
		if($listingVariant->custom_sku != ""){}
			Log::channel('ebayordersync')->info("custom sku found for listing var id  ".$listingVariant->id);
		  $listing_variant_data = $listingVariant->listing_variant_data;
			$resultArray = array();
	   
	     
	     
	     $listing_variant_data_decode=json_decode($listing_variant_data,true);
		$VariationSpecifics = $listing_variant_data_decode['VariationSpecifics'][0];
			    
			    
				foreach ($VariationSpecifics['NameValueList'] as $nameValue) {
			      	 print_r($nameValue);
				     Log::channel('ebayordersync')->info("22222222 ".json_encode($nameValue,true));
				     	$resultArray[$nameValue['Name']] = $nameValue['Value'][0];
				
				
			}
		Log::channel('ebayordersync')->info("this is the result array ".json_encode($resultArray,true));
		
                 $diff = array_diff_assoc($optionsarray, $resultArray);

                  if (empty($diff)) {
                      Log::channel('ebayordersync')->info("The arrays are exactly the same for listing var id".$listingVariant->id);
                  echo "The arrays are exactly the same for ->".$listingVariant->custom_sku;
                  
                  return [
                     'custom_sku' => $listingVariant->custom_sku,
                      'other_variable' => $listingVariant->variant_id, 
                      ];
                  
				//  return $listingVariant->custom_sku;
                   }
				    else {
				         Log::channel('ebayordersync')->info("The arrays are different".$listingVariant->id);
                        echo "The arrays are different.";
				  
                    }

         
	    }
	}
    
	public function shopifyinvupdate($shopifyStore,$quantity,$oldqty,$shopify_inventory_item_id){
	    
        Log::channel('ebayordersync')->info("quantity updating in shopify ");
        Log::channel('ebayordersync')->info("here is the old quantity  ->".$oldqty);
        $quantity = $oldqty - $quantity;
        if ($quantity < 0) {
            $quantity = 0;
        }
        Log::channel('ebayordersync')->info("here is the new quantity-> ".$quantity);

        // PHPShopify\ShopifySDK::config(array('ShopUrl' => $shopifyStore->shopify_url, 'AccessToken' => $shopifyStore->access_token, 'ApiVersion' => config('shopify.api_version')));
        
        $config = array('ShopUrl' => $shopifyStore->shopify_url, 'AccessToken' => $shopifyStore->access_token, 'ApiVersion' => config('shopify.api_version'));
        $shopifyClient = new PHPShopify\ShopifySDK($config);

        $locations = ($shopifyStore->locations) ? explode(",", $shopifyStore->locations) : array();
        $errors =array();
        if ($locations) {
            
            foreach ($locations as $location_id) {
                try {
                    $sdata = array(
                        "location_id" => $location_id,
                        "inventory_item_id" => $shopify_inventory_item_id,
                        "available" => $quantity
                        
                    );
                    
                        Log::channel('ebayordersync')->info("updating on shopify ");
                    $shopifydata = $shopifyClient->InventoryLevel()->set($sdata);
                        Log::channel('ebayordersync')->info("shopify response is here ->".json_encode($shopifydata,true));
                    sleep(1);
                //	$succCount++;
                } catch (\Exception $e) {
                    report($e);
                    $errors[] = $e->getMessage();
                        Log::channel('ebayordersync')->info("errorrrrr on shopify ".$e->getMessage());
                    $locErrors[] = $e->getMessage();
                }
            }
        }
        

        if($errors){
            
            return [ 'msg' => 'error','error' => $errors[0]];
        }elseif($shopifydata){
            return ['msg' => 'success','quantity' => $quantity, ];
        }

    }


    public function UpdateSyncConfirm($data) {
 
        $fp = fopen("verifyDatahitesh.csv", "w");
            fputcsv($fp, array("ebayitemid", "shopifyvariantid" ,'orderqty','dbqty','qtytibeupdated'));
            foreach ($data as $record) {
                fputcsv($fp, $record);
            }
            fclose($fp);
    	return true;	
    }
    
    public function getordercsv()
    {
    }
}
