<?php

namespace App\Jobs;

use App\Helpers\AppHelper;
use App\ShopifyStore;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use \DTS\eBaySDK\Trading\Services;
use \DTS\eBaySDK\Trading\Types;

class Newpendinginvenoryupdate implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $store_id, $user_id, $account_id, $quantity, $price, $type, $sku, $ebay_item_id, $variant_id, $source, $compare_at_price;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($jobData)
    {
        $this->quantity = (int) $jobData["quantity"];
        $this->price = (int) $jobData["price"];
        $this->compare_at_price = (int) $jobData["compare_at_price"];
        $this->type = $jobData["type"];
        $this->sku = $jobData["sku"];
        $this->ebay_item_id = $jobData["ebay_item_id"];
        $this->source = $jobData["source"];
        $this->variant_id = (int) $jobData["variant_id"];
        $this->store_id = (int) $jobData["store_id"];
        $this->user_id = (int) $jobData["user_id"];
        $this->account_id = (int) $jobData["account_id"];
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {

            Log::info('entered in Newpendinginvenoryupdate job' . $this->store_id);
            $shopifyStores = ShopifyStore::where("status", "active")->where("id", $this->store_id)->get();
            //   print_r('shopifyStore found'.$shopifyStores);
            foreach ($shopifyStores as $shopifyStore) {
                Log::info('shopifyStore found');
                //      if($shopifyStore->user_id == 2) $ebay_environment = "sandbox";
                $ebay_environment = '';
                /// print_r('111111111111111');
                $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::info('33333111111111111111');
                $shopify_store_id = $shopifyStore->id;
                Log::info('ooo111111111111111');

                $store_database_name = config('config.store_db_prefix') . $shopify_store_id;
                AppHelper::setConnection($store_database_name, $shopifyStore[0]);

                $errors = array();

                try {
                    Log::info($this->store_id);
                    $ebayAccounts = $shopifyStore->ebayAccounts()->where("store_id", $this->store_id)->get();
                    Log::info('ebay account found' . $ebayAccounts);
                    if (count($ebayAccounts) > 0) {
                        Log::info('ebay count is greater than zero');
                        foreach ($ebayAccounts as $ebayAccount) {

                            Log::info('ebayAccount found in Newpendinginvenoryupdate job for account id ' . $ebayAccount->id);

                            $account_id = $ebayAccount->id;
                            Log::info('here is the ebay account id ' . $account_id);
                            $accountErrors = [];
                            $skusArray = [];
                            Log::info('type is ' . $this->type);
                            if ($this->type === "qty") {
                                try {
                                    Log::info('type is qty in Newpendinginvenoryupdate job');
                                    $listingVariant = $shopifyStore->listingVariants()->with('listing')->where("variant_id", $this->variant_id)->get();

                                    if ($listingVariant && $listingVariant[0]->listing) {
                                        $ebay_item_id = $listingVariant[0]->listing->ebay_item_id;
                                        Log::info('found in listingVariant in type-qty in Newpendinginvenoryupdate job for ebay item id ' . $ebay_item_id);
                                        // $quantity = ($pendingInv->quantity > 0) ? $pendingInv->quantity : 0;
                                        $quantity = $this->quantity;
                                        $siteId = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
                                        $ebay_token = $ebayAccount->access_token;
                                        $ebayService = new Services\TradingService([
                                            'credentials' => $ebayCredentials['credentials'],
                                            'sandbox' => ($ebay_environment == "sandbox_") ? true : false,
                                            'siteId' => $siteId,
                                        ]);
                                        $sku = $listingVariant[0]->sku;
                                        try {
                                            Log::info('getting ebay data where type is qty in Newpendinginvenoryupdate job for ebay item id ' . $ebay_item_id);
                                            $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);

                                            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 = [];
                                            if ($quantity == 0 && $listing_format == "auction") {
                                                Log::info('quantity is zero and listing_format is auction where type is qty in Newpendinginvenoryupdate job for ebay item id ' . $ebay_item_id);
                                                $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::info('listing_format is auction where type is qty in Newpendinginvenoryupdate job for ebay item id ' . $ebay_item_id);
                                                $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::info('listing_format is not auction and quantity is not zero where type is qty in
                                                         Newpendinginvenoryupdate job for ebay item id ' . $ebay_item_id);
                                                $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 = $ebay_token;
                                                $ebayRequest->InventoryStatus = $inventoryStatusArray;
                                                $ebayResponse = $ebayService->reviseInventoryStatus($ebayRequest);
                                                $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();

                                                if (isset($ebayResponse["Ack"]) && $ebayResponse["Ack"] == 'Failure' && $ebayResponse["Errors"]) {
                                                    Log::info('ebay response is failure where type is qty in Newpendinginvenoryupdate job for ebayitemid' . $ebay_item_id);
                                                    $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') {
                                                  Log::info('ebay response is success where type is qty in Newpendinginvenoryupdate job for ebayitemid' . $ebay_item_id);
                                                $listingVariant[0]->last_inventory_synced = $quantity;
                                                $listingVariant[0]->last_inventory_synced_at = now()->toDateTimeString();
                                                $listingVariant[0]->save();

                                                $listingVariant[0]->listing->last_inventory_synced_at = $listingVariant[0]->last_inventory_synced_at;
                                                $listingVariant[0]->listing->save();
                                                // $pendingInvArray[] = $pendingInv;
                                            } else {
                                                $accountErrors[] = $ebayResponse;
                                            }
                                        } catch (\Exception $e) {
                                            report($e);
                                            $accountErrors[] = $e->getMessage();
                                        }
                                    }
                                } catch (\Exception $e) {
                                    report($e);
                                    $accountErrors[] = $e->getMessage();
                                }

                            } elseif ($this->type === "price") {
                                try {
                                    Log::info('type is price in Newpendinginvenoryupdate job');
                                    $listingVariant = $shopifyStore->listingVariants()->with('listing')->where("variant_id", $this->variant_id)->get();

                                    if ($listingVariant && $listingVariant[0]->listing) {
                                        Log::info('found in lisitn variants and type is price in Newpendinginvenoryupdate job');
                                        $ebay_item_id = $listingVariant[0]->listing->ebay_item_id;
                                        // $quantity = ($pendingInv->quantity > 0) ? $pendingInv->quantity : 0;
                                        $price = $this->price;
                                        $compare_at_price = $this->compare_at_price;
                                        $siteId = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
                                        $ebay_token = $ebayAccount->access_token;
                                        $ebayService = new Services\TradingService([
                                            'credentials' => $ebayCredentials['credentials'],
                                            'sandbox' => ($ebay_environment == "sandbox_") ? true : false,
                                            'siteId' => $siteId,
                                        ]);
                                        $sku = $listingVariant[0]->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);

                                            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 = [];
                                            if ($listing_format == "auction") {
                                                Log::info('listing_format is auction and type is price in Newpendinginvenoryupdate job for ebay item id ' . $ebay_item_id);
                                                $ebayRequest = new Types\ReviseItemRequestType();
                                                $ebayRequest->RequesterCredentials = new Types\CustomSecurityHeaderType();
                                                $ebayRequest->RequesterCredentials->eBayAuthToken = $ebay_token;
                                                $ebayItem = new Types\ItemType();
                                                $ebayItem->ItemID = $ebay_item_id;
                                                $ebayItem->StartPrice = new Types\AmountType(['value' => (float) $price]);
                                                $ebayRequest->Item = $ebayItem;

                                                $ebayResponse = $ebayService->reviseItem($ebayRequest);
                                                $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
                                            } else {
                                                Log::info('listing_format is not auction and type is price in Newpendinginvenoryupdate job for ebay item id ' . $ebay_item_id);
                                                $inventoryStatus = new Types\InventoryStatusType();
                                                if ($sku) {
                                                    $inventoryStatus->SKU = $sku;
                                                }

                                                $inventoryStatus->ItemID = $ebay_item_id;
                                                $inventoryStatus->StartPrice = new Types\AmountType(['value' => (float) $price]);
                                                $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();

                                                if (isset($ebayResponse["Ack"]) && $ebayResponse["Ack"] != 'Failure') {
                                                    $listingVariant[0]->last_price_synced = $price;
                                                    $listingVariant[0]->last_pricing_synced_at = now()->toDateTimeString();
                                                    $listingVariant[0]->save();

                                                    $listingVariant[0]->listing->last_pricing_synced_at = $listingVariant[0]->last_pricing_synced_at;
                                                    $listingVariant[0]->listing->save();

                                                } else {
                                                    $accountErrors[] = $ebayResponse;
                                                }
                                            }

                                        } catch (\Exception $e) {
                                            report($e);
                                            $accountErrors[] = $e->getMessage();
                                        }
                                    }
                                } catch (\Exception $e) {
                                    report($e);
                                    $accountErrors[] = $e->getMessage();
                                }
                            } elseif ($this->type === "qty&price") {
                                try {
                                    Log::info('type is qty & price in Newpendinginvenoryupdate job');
                                    $listingVariant = $shopifyStore->listingVariants()->with('listing')->where("variant_id", $this->variant_id)->get();

                                    if ($listingVariant && $listingVariant[0]->listing) {
                                        Log::info('found in listing variants and type is price in Newpendinginvenoryupdate job');
                                        $ebay_item_id = $listingVariant[0]->listing->ebay_item_id;
                                        // $quantity = ($pendingInv->quantity > 0) ? $pendingInv->quantity : 0;
                                        $quantity = $this->quantity;
                                        $price = $this->price;
                                        $compare_at_price = $this->compare_at_price;
                                        $siteId = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
                                        $ebay_token = $ebayAccount->access_token;
                                        $ebayService = new Services\TradingService([
                                            'credentials' => $ebayCredentials['credentials'],
                                            'sandbox' => ($ebay_environment == "sandbox_") ? true : false,
                                            'siteId' => $siteId,
                                        ]);
                                        $sku = $listingVariant[0]->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);

                                            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 = [];
                                            if ($quantity == 0 && $listing_format == "auction") {
                                                Log::info('quantity is zero  and listing_format is auction and type is qty&price in Newpendinginvenoryupdate job for ebayitemid' . $ebay_item_id);
                                                $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::info('listing_format is auction and type is qty & price in Newpendinginvenoryupdate job for ebayitemid' . $ebay_item_id);
                                                $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;
                                                $ebayItem->StartPrice = new Types\AmountType(['value' => (float) $price]);
                                                $ebayRequest->Item = $ebayItem;
                                                $ebayResponse = $ebayService->reviseItem($ebayRequest);
                                                $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
                                            } else {
                                                Log::info('quantity is !zero  and listing_format is !auction and type is qty&price in Newpendinginvenoryupdate job for ebayitemid' . $ebay_item_id);
                                                $inventoryStatus = new Types\InventoryStatusType();
                                                if (trim($sku)) {
                                                    $inventoryStatus->SKU = trim($sku);
                                                }

                                                $inventoryStatus->ItemID = $ebay_item_id;
                                                $inventoryStatus->Quantity = ($quantity < 0) ? 0 : $quantity;
                                                $inventoryStatus->StartPrice = new Types\AmountType(['value' => (float) $price]);

                                                $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();

                                                if (isset($ebayResponse["Ack"]) && $ebayResponse["Ack"] == 'Failure' && $ebayResponse["Errors"]) {
                                                    Log::info('ebay response is failure and type is qty&price in Newpendinginvenoryupdate job for ebayitemid' . $ebay_item_id);
                                                    $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";
                                                        Log::info('Ending item where ebay response is failure and type is qty&price in Newpendinginvenoryupdate job for ebayitemid' . $ebay_item_id);
                                                        $ebayResponse = $ebayService->endFixedPriceItem($endItemRequest);
                                                        $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
                                                    }
                                                }
                                            }

                                            if (isset($ebayResponse["Ack"]) && $ebayResponse["Ack"] != 'Failure') {
                                                $listingVariant[0]->last_inventory_synced = $quantity;
                                                $listingVariant[0]->last_inventory_synced_at = now()->toDateTimeString();
                                                $listingVariant[0]->last_price_synced = $price;
                                                $listingVariant[0]->last_pricing_synced_at = now()->toDateTimeString();
                                                $listingVariant[0]->save();

                                                $listingVariant[0]->listing->last_inventory_synced_at = $listingVariant[0]->last_inventory_synced_at;
                                                $listingVariant[0]->listing->last_pricing_synced_at = $listingVariant[0]->last_pricing_synced_at;
                                                $listingVariant[0]->listing->save();
                                                // $pendingInvArray[] = $pendingInv;

                                                $listingVariant[0]->save();

                                                $listingVariant[0]->listing->save();

                                            } else {
                                                $accountErrors[] = $ebayResponse;
                                            }
                                        } catch (\Exception $e) {
                                            report($e);
                                            $accountErrors[] = $e->getMessage();
                                        }
                                    }
                                } catch (\Exception $e) {
                                    report($e);
                                    $accountErrors[] = $e->getMessage();
                                }
                            } elseif ($this->type === "order") {
                                try {
                                    Log::info('type is order in Newpendinginvenoryupdate job for ebay item id ' . $this->ebay_item_id);

                                    $listingVariant = $shopifyStore->listingVariants()->with('listing')->where("ebay_item_id", $this->ebay_item_id)->get();
                                    // print_r('listing variant found in db '.json_encode($listingVariant,true));
                                    if ($listingVariant && $listingVariant[0]->listing) {
                                        //print_r('listing variant found in db '.json_encode($listingVariant,true));
                                        Log::info('found in listing variants and type is order in Newpendinginvenoryupdate job');
                                        $ebay_item_id = $listingVariant[0]->listing->ebay_item_id;
                                        // $quantity = ($pendingInv->quantity > 0) ? $pendingInv->quantity : 0;
                                        $quantity = $this->quantity;
                                        echo "hiiiiiiiiiii" . $quantity;
                                         Log::info('hiiiiiiiiiii '.$quantity);
                                        $siteId = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
                                        $ebay_token = $ebayAccount->access_token;
                                        $ebayService = new Services\TradingService([
                                            'credentials' => $ebayCredentials['credentials'],
                                            'sandbox' => ($ebay_environment == "sandbox_") ? true : false,
                                            'siteId' => $siteId,
                                        ]);
                                        $sku = $listingVariant[0]->sku;
                                        Log::info('here is the sku ' . $sku);
                                        // print_r('here is the quantity '. $this->quantity );
                                        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();
                                             Log::info('here is the ebay response ' . json_encode($ebayItemResponse["Item"],true));
                                            //     print_r('here is the ebayqnty '.json_encode($ebayItemResponse["Item"],true));
                                            if (isset($ebayItemResponse["Item"]) && $ebayItemResponse["Item"]) {
                                                $ebayItem = $ebayItemResponse["Item"];
                                            }

                                            if (!$ebayItem);

                                            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();
 Log::info('here is the quantity from ebay  ' . json_encode($variations,true));
                                           // $ebayqnty = $ebayItem["Quantity"];
                                           $ebayqnty=0;
                                           foreach($variations as $Variation){
                                               Log::info('hhhhhhhhhhhhhhhhhh   ' . json_encode($Variation,true));
                                                //   Log::info('tttttttttt   ' . $sku);
                                               if($Variation["SKU"] == $sku){
                                                   $ebayqnty = $Variation["Quantity"];
                                               }
                                           }
                                             //$ebayqnty = 28;
                                              Log::info('here is the quantity from ebay  ' . $ebayqnty);
                                             
                                            echo "hiiiiiiiiii" . gettype($ebayqnty);
                                            //print_r('here is the ebayqnty '.json_encode($ebayqnty,true));
                                            $newqntyt = $ebayqnty + $quantity;
                                            Log::info('here is the newqntyt  ' . $newqntyt);
                                            Log::info('here is the ebayqnty  ' . $ebayqnty);
                                            $ebayResponse = [];

                                            if ($newqntyt <= 0) { //$ebayqnty == 0 ||

                                                Log::info('quantity is zero  and type is order in Newpendinginvenoryupdate job for ebayitemid');

                                                $inventoryStatus = new Types\InventoryStatusType();
                                                if (trim($sku)) {
                                                    $inventoryStatus->SKU = trim($sku);
                                                }

                                                $inventoryStatus->ItemID = $ebay_item_id;
                                                $inventoryStatus->Quantity = 0;
                                                $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::info("first " . json_encode($ebayResponse, true));

                                                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();
                                                        Log::info("second " . json_encode($ebayResponse, true));
                                                    }
                                                }

                                            } else {

                                            //     $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 = $newqntyt;
                                            //      $ebayItem->Quantity = 19;
                                            //     $ebayRequest->Item = $ebayItem;
                                            //     $item->SKU = 9349093004337;
                                            //     $ebayResponse = $ebayService->reviseItem($ebayRequest);
                                            //     $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
                                            
                                            
                                              
                                                $inventoryStatus = new Types\InventoryStatusType();
                                                if (trim($sku)) {
                                                    $inventoryStatus->SKU = trim($sku);
                                                }

                                                $inventoryStatus->ItemID = $ebay_item_id;
                                                $inventoryStatus->Quantity =  $newqntyt;
                                                $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::info("else  " . json_encode($ebayResponse, true));

                                            }

                                            if (isset($ebayResponse["Ack"]) && $ebayResponse["Ack"] != 'Failure') {
                                                //   print_r($quantity);
                                                 Log::info("else else " . json_encode($ebayResponse, true));
                                                // $listingVariant->last_inventory_synced = $ebayqnty + $quantity;
                                                // //   print_r($ebayResponse["Ack"]);
                                                // $listingVariant->last_inventory_synced_at = now()->toDateTimeString();
                                                // $listingVariant->save();

                                                // $listingVariant->listing->last_inventory_synced_at = $listingVariant->last_inventory_synced_at;
                                                // $listingVariant->listing->save();
                                                // $pendingInvArray[] = $pendingInv;
                                            } else {
                                                $accountErrors[] = $ebayResponse;
                                            }
                                        } catch (\Exception $e) {
                                            report($e);
                                            $accountErrors[] = $e->getMessage();
                                        }
                                    }
                                } catch (\Exception $e) {
                                    report($e);
                                    $accountErrors[] = $e->getMessage();
                                }

                            } elseif ($this->type === "webhook_order") {
                                try {

                                    Log::info('jhhhhhhhhhhhhhhhhhhhhhh');
                                    $listingVariant = $shopifyStore->listingVariants()->with('listing')->where("account_id", $account_id);

                                    if ($listingVariant && $listingVariant->listing) {
                                        $ebay_item_id = $listingVariant->listing->ebay_item_id;
                                        // $quantity = ($pendingInv->quantity > 0) ? $pendingInv->quantity : 0;
                                        $quantity = $this->quantity;
                                        $siteId = (isset($ebayAccount->siteid)) ? $ebayAccount->siteid : 0;
                                        $ebay_token = $ebayAccount->access_token;
                                        $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);

                                            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();

                                            $ebayqnty = $ebayItem->Quantity;

                                            $ebayResponse = [];
                                            if ($ebayqnty == 0 || $ebayqnty + $quantity <= 0) {
                                                $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 = 0;
                                                $ebayRequest->Item = $ebayItem;
                                                $ebayResponse = $ebayService->reviseItem($ebayRequest);
                                                $ebayResponse = ($ebayResponse) ? $ebayResponse->toArray() : array();
                                                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();
                                                    }
                                                }
                                            }
                                            //   else if($ebayqnty + $quantity <= 0){
                                            //     $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 {
                                                $inventoryStatus = new Types\InventoryStatusType();
                                                if (trim($sku)) {
                                                    $inventoryStatus->SKU = trim($sku);
                                                }

                                                $inventoryStatus->ItemID = $ebay_item_id;
                                                $inventoryStatus->Quantity = $ebayqnty + $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();

                                                if (isset($ebayResponse["Ack"]) && $ebayResponse["Ack"] == 'Failure' && $ebayResponse["Errors"]) {
                                                    // we would not end the item here but add them in logs.
                                                    $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 = $ebayqnty + $quantity;
                                                $listingVariant->last_inventory_synced_at = now()->toDateTimeString();
                                                $listingVariant->save();

                                                $listingVariant->listing->last_inventory_synced_at = $listingVariant->last_inventory_synced_at;
                                                $listingVariant->listing->save();
                                                // $pendingInvArray[] = $pendingInv;
                                            } else {
                                                $accountErrors[] = $ebayResponse;
                                            }
                                        } catch (\Exception $e) {
                                            report($e);
                                            $accountErrors[] = $e->getMessage();
                                        }
                                    }
                                } catch (\Exception $e) {
                                    report($e);
                                    $accountErrors[] = $e->getMessage();
                                }

                            }
                        }
                    }

                } catch (\Exception $e) {
                    report($e);
                    $accountErrors[] = $e->getMessage();
                }
            }
            if ($accountErrors) {
                $errors = array_merge($errors, $accountErrors); 
                $output_data = array();
                $output_data["errors"] = $accountErrors;
                $logData = array();
                $logData["log_type"] = "sync_ebay_inventory";
                $logData["input_data"] = json_encode($skusArray);
                $logData["log_data_id"] = $ebayAccount->id;
                $logData["status"] = "error";
                $logData["output_data"] = json_encode($output_data, JSON_INVALID_UTF8_IGNORE);
                $logData["remarks"] = "error syncing inventory for " . $ebayAccount->name . " account";
                $logData["store_id"] = $shopifyStore->id;
                $logData["user_id"] = $shopifyStore->user_id;
                $shopifyStore->logs()->create($logData);
            }

        } catch (\Exception $e) {
            report($e);
            $errors[] = $e->getMessage();
        }
        // if($errors) file_put_contents("syncPendingInventoryError_".$shopify_store_id.".json",json_encode($errors));

        // AppHelper::updateCronJob($cronJob->type,0);

        return response()->json(['status' => 'success', 'msg' => "done"], 200);

    }

}
